import React, { useEffect, useState } from 'react';
import {Button, Card, Col, DatePicker, Form, Row} from 'antd'
import {ProductAnalysisModel,ProductAnalysisReq, ProductionQuantity} from '@gtpl/shared-models/warehouse-management'
import {WarehouseDashboardService} from '@gtpl/shared-services/analytics'
import moment from 'moment';
import ReactHTMLTableToExcel from 'react-html-table-to-excel';
import { GlobalVariableValues } from '@gtpl/shared-models/common-models';

const {RangePicker} = DatePicker


/* eslint-disable-next-line */
export interface ProductionAnalysisProps {}

export const ProductionAnalysis = () => {
  const [form] = Form.useForm()
  const [iqfData,setIqfData] = useState<any[]>([])
  const [blockData,setBlockData] = useState<any[]>([])
  const [data,setData] = useState<any>()
  const servcie = new WarehouseDashboardService()
  const [selectedDateRange, setSelectedDateRange] = useState(null);

  // useEffect(() => {
  //   getData()
  // },[])

  const getData = () => {
    const req = new ProductAnalysisReq(null,null)
    if(form.getFieldValue('dateRange') != undefined){
      req.fromDate = moment(form.getFieldValue('dateRange')[0]).format('YYYY-MM-DD')
      req.toDate = moment(form.getFieldValue('dateRange')[1]).format('YYYY-MM-DD')
    }
    servcie.getMISproductDetailedReport(req).then(res => {
      if(res.status){
        setData(res.data)
        setIqfData(res.data.iqfProductsInfo)
        setBlockData(res.data.blockProductsInfo)
      }
    })
  }


  const onReset = () => {
    form.resetFields()
    setData(null)
    setIqfData([])
    setBlockData([])

  }

  const onSubmit = () => {
    getData()
  }

  const handleDateChange = (dates) => {
    setSelectedDateRange(dates);
  };

  const formattedMonthYear = selectedDateRange
  ? `${selectedDateRange[1].format('MMMM')} ${selectedDateRange[1].year()}`
  : '';

  const totalProductPercentage = (grossTotalWeight) => {
    if (data?.totals?.totalGrossWeight && grossTotalWeight) {
      return ((grossTotalWeight / data.totals.totalGrossWeight) * 100).toFixed(3);
    }
    return '-';
  };
 

  const procureWeight=data?.productionQuantity[0]?.quantity?data?.productionQuantity[0]?.quantity:"-"
  const reweighmentQuantity=data?.productionQuantity[0]?.reweighmentQuantity?data?.productionQuantity[0]?.reweighmentQuantity:"-"
  const purchaseDifference=reweighmentQuantity-procureWeight

  const honProductionSum = (() => {
    const iqfSum = data?.iqfProductsInfo?.reduce((acc, product) => {
        return product.va1 == GlobalVariableValues.HONProductId
            ? acc + (product.totalEquivalentHeadOnWeight || 0)
            : acc;
    }, 0) || 0;

    const blockSum = data?.blockProductsInfo?.reduce((acc, product) => {
        return product.va1 == GlobalVariableValues.HONProductId
            ? acc + (product.totalEquivalentHeadOnWeight || 0)
            : acc;
    }, 0) || 0;

    return iqfSum + blockSum;

})();

const netHonForProduction=reweighmentQuantity-honProductionSum

const totalHeadOnWeight=data?.totals?.totalHeadOnWeight?data?.totals?.totalHeadOnWeight:"0"
const differInProductionWeight=totalHeadOnWeight-reweighmentQuantity

const yieldVariation=differInProductionWeight/netHonForProduction

const netTotalWeight=data?.totals?.totalNetWeight?data?.totals?.totalNetWeight:"0"
const netYield=netTotalWeight/netHonForProduction

const grossTotalWeight=data?.totals?.totalGrossWeight?data?.totals?.totalGrossWeight:"0"
const grossYield=grossTotalWeight/netHonForProduction

const totalProductionPercentageSum = (() => {
  // Calculate the percentage for each product in iqfProductsInfo
  const iqfSum = data?.iqfProductsInfo?.reduce((acc, product) => {
      const percentage = String((acc.grossTotalWeight / Number(data?.totals?.totalGrossWeight))*100)
      return percentage !== '-' ? acc + parseFloat(percentage) : acc;
  }, 0) || 0;

  // Calculate the percentage for each product in blockProductsInfo
  const blockSum = data?.blockProductsInfo?.reduce((acc, product) => {
      const percentage =String((acc.grossTotalWeight / Number(data?.totals?.totalGrossWeight))*100)
      return percentage !== '-' ? acc + parseFloat(percentage) : acc;
  }, 0) || 0;

  // Sum of iqf and block percentages
  return iqfSum + blockSum;
})();



  return (
    <Card size='small' title={<span style={{color:'white'}}>Production Yield Report</span>} 
    style={{textAlign:'center'}} headStyle={{backgroundColor: '#69c0ff', border: 0 }}>
      <Form form={form} onFinish={onSubmit}>
        <Row gutter={24}>
              <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 8 }}>
            <Form.Item name='dateRange' label='Range'>
                <RangePicker onChange={handleDateChange}/>
            </Form.Item>
            </Col>
            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 2 }}>
            <Form.Item >
                <Button type='primary' htmlType='submit'>Get Report</Button>
            </Form.Item>
            </Col>
            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 2 }} style={{ paddingLeft: '30px' }}>
            <Form.Item>
                <Button type='primary' onClick={onReset}>Reset</Button>
            </Form.Item>
            </Col>
        </Row>
      </Form>
      {
        data ? (<>
         <div >
          <Card >
            <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
          <ReactHTMLTableToExcel
            id='excel-button'
            // className='download-table-xls-button'
            table='production-anlysis'
            filename='ProductionAnalysisxls'
            sheet="Sheet 1"
            buttonText='Get Excel'
            className="ant-btn ant-btn-primary"
          />
          </div>
          <br />
          <table style={{borderCollapse:'collapse',borderBlockColor:'black',width:'100%'}} id='production-anlysis'>
            <tr>
              <td colSpan={8}><h1>Production Analysis For The Month Of {formattedMonthYear}</h1></td>
            </tr>
            <br />
            <tr>
              <td colSpan={3} style={{textAlign:'left',fontSize:'15px'}}>Raw Material Procurement Weight in KG:</td>
              <th>{data?.productionQuantity[0]?.quantity ? Number(data?.productionQuantity[0]?.quantity) : '-'}</th>
              <td colSpan={3} style={{textAlign:'left',fontSize:'15px'}}>Raw Material Received Weight at Plant in KG:</td>
              <th>{data?.productionQuantity[0]?.reweighmentQuantity ? Number(data?.productionQuantity[0]?.reweighmentQuantity) : '-'}</th>
              </tr>
              <tr>
              <td colSpan={3} style={{textAlign:'left',fontSize:'15px'}}>Purchase Difference in KG:</td>
              <th>{purchaseDifference.toFixed(3)}</th>
              <td colSpan={3} style={{textAlign:'left',fontSize:'15px'}}>HON Production in KG:</td>
              <th>{honProductionSum !== null ? honProductionSum : '-'}</th>
            </tr>
              <tr>
              <td colSpan={3} style={{textAlign:'left',fontSize:'15px'}}>Net HON For Other Prodution in KG:</td>
              <th>{netHonForProduction}</th>
              <td colSpan={3} style={{textAlign:'left',fontSize:'15px'}}>HON to HLSO Weight:</td>
              <th>{data?.honToHlsoWeight != null ? Number(data?.honToHlsoWeight) : '-'}</th>
              </tr>
            <tr>
              <td colSpan={3} style={{textAlign:'left',fontSize:'15px'}}>HON to HLSO Yield:</td>
              <th>{data?.honToHlsoYield ? Number(data?.honToHlsoYield) : '-'}</th>
            </tr>
            <br />
            <tr style={{backgroundColor:'lightblue'}}>
              <th style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>Product Type</th>
              <th style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>No of Slabs</th>
              <th style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>Weight per Slab(per kg)</th>
              <th style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>Net Total Weight</th>
              <th style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>Gross Total Weight</th>
              <th style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>Yield %</th>
              <th style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>Total Equalent Head on Weight</th>
              <th style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>Production %</th>
            </tr>
            {iqfData.length > 0 ? ( <tr>
              <th colSpan={8} style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>IQF</th>
            </tr> ) : (<></>)}
            {
              iqfData?.map(rec => {
                return(
                  <>
                  <tr>
                  <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{rec.productType}</td>
                  <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{rec.noOfSlabs}</td>
                  <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{rec.weightPerSlab ? Number(rec.weightPerSlab.toFixed(3)) : '-'}</td>
                  <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{rec.netTotalWeight ? Number(rec.netTotalWeight.toFixed(3)) : '-'}</td>
                  <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{rec.grossTotalWeight ? Number(rec.grossTotalWeight.toFixed(3)) : '-'}</td>
                  <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{rec.yieldPer ? Number(rec.yieldPer.toFixed(1)) : '-'}</td>
                  <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{rec.totalEquivalentHeadOnWeight ? Number(rec.totalEquivalentHeadOnWeight.toFixed(3)) : '-'}</td>
                  <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{rec.grossTotalWeight ? ((rec.grossTotalWeight / Number(data?.totals?.totalGrossWeight))*100).toFixed(3):'-'}</td>
                  </tr>
                  </>
                )
              })
            }
            { blockData.length > 0 ? (<>
            <tr>
              <th colSpan={8} style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>BLOCK</th>
            </tr>
            </>) : (<></>)}
            {
              blockData?.map(rec => {
                return(
                  <>
                  <tr>
                  <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{rec.productType}</td>
                  <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{rec.noOfSlabs}</td>
                  <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{rec.weightPerSlab ?Number(rec.weightPerSlab.toFixed(3)) : '-'}</td>
                  <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{rec.netTotalWeight ?Number(rec.netTotalWeight.toFixed(3)) : '-'}</td>
                  <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{rec.grossTotalWeight ?Number(rec.grossTotalWeight.toFixed(3)) : '-'}</td>
                  <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{rec.yieldPer ?Number(rec.yieldPer.toFixed(3)) : '-'}</td>
                  <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{rec.totalEquivalentHeadOnWeight ?Number(rec.totalEquivalentHeadOnWeight.toFixed(3)) : '-'}</td>
                  <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{rec.grossTotalWeight ? ((rec.grossTotalWeight / Number(data?.totals?.totalGrossWeight))*100).toFixed(3):'-'}</td>
                  </tr>
                  </>
                )
              })
            }
            <tr>
              <th style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>Total</th>
              <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{data?.totals?.totalNumberOfSlabs}</td>
              <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{}</td>
              <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{data?.totals?.totalNetWeight ? Number(data?.totals?.totalNetWeight) : '-'}</td>
              <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{data?.totals?.totalGrossWeight ?Number(data?.totals?.totalGrossWeight) : '-'}</td>
              <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{}</td>
              <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}>{data?.totals?.totalHeadOnWeight ?Number(data?.totals?.totalHeadOnWeight.toFixed(3)) : '-'}</td>
              <td style={{textAlign:'center',fontSize:'15px',border:'1px solid black'}}> {totalProductionPercentageSum !== 0 ? totalProductionPercentageSum.toFixed(3) : '-'}</td>
            </tr>
            <br />
            <tr>
              <td colSpan={2} style={{textAlign:'left',fontSize:'15px'}}>Difference in production Weight in Kg (+/-)</td>
              <th colSpan={2}>{differInProductionWeight?.toFixed(3)}</th>
              <td colSpan={2} style={{textAlign:'left',fontSize:'15px'}}>Yield Variation (+/-)</td>
              <th colSpan={2}>{yieldVariation?.toFixed(3)}</th>
              </tr>
            <tr>
              <td colSpan={2} style={{textAlign:'left',fontSize:'15px'}}>Net Yield</td>
              <th colSpan={2}>{netYield?.toFixed(3)}</th>
              <td colSpan={2} style={{textAlign:'left',fontSize:'15px'}}>Gross Yield</td>
              <th colSpan={2}>{grossYield?.toFixed(3)}</th>
              </tr>
          </table>
          </Card>
        </div>
        </>) : (<></>)
      }
     
    </Card>
  );
}

export default ProductionAnalysis;
