import React, { useEffect, useState } from 'react';
import { WarehouseDashboardService } from "@gtpl/shared-services/analytics"
import {Button, Card, Col, DatePicker, Descriptions, Form, Row, Table} from 'antd'
import { Excel } from 'antd-table-saveas-excel';
import { ColumnProps } from 'antd/lib/table';
import { DayWiseProductionReq, ExportsProductsInfo } from '@gtpl/shared-models/warehouse-management';
import moment from 'moment';

const {RangePicker} = DatePicker


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

export const DayWiseProductionAnalysis = () => {
  
  const [dayWiseProductionData,setDayWiseProdcutionData] = useState<any[]>([])
  const service = new WarehouseDashboardService()
  const [page,setPage] = useState<number>(1)
  const [form] = Form.useForm()
  const [exportProductInfo,setExportProductsInfo] = useState<any[]>([])
  const [g2ProductInfo,setG2ProductsInfo] = useState<any[]>([])
  const [jumbleProductInfo,setJumbleProductsInfo] = useState<any[]>([])
  const [analysisData,setAnalysisData] = useState<any>()

  useEffect(() => {
    // getProductionInfo()
    // getDayWiseAnalysisInfo()
  },[])

  const getProductionInfo = () => {
    const fromdate = moment(form.getFieldValue('dateRange')[0]).format('YYYY-MM-DD')
    const toDate = moment(form.getFieldValue('dateRange')[1]).format('YYYY-MM-DD')
    const req = new DayWiseProductionReq(fromdate,toDate)
    // service.getDayWiseProdcutionReport(req).then(res => {
    //   if(res.status){
    //     setDayWiseProdcutionData(res.data)
    //   }
    // })
    service.dayWiseProductionReport(req).then(res => {
      if(res.status){
        setDayWiseProdcutionData(res.data)
      }
    })
  }

  const getDayWiseAnalysisInfo = () => {
    const fromdate = moment(form.getFieldValue('dateRange')[0]).format('YYYY-MM-DD')
    const toDate = moment(form.getFieldValue('dateRange')[1]).format('YYYY-MM-DD')
    const req = new DayWiseProductionReq(fromdate,toDate)
    service.getDayWiseAnalysisReport(req).then(res => {
      if(res.status){
        setAnalysisData(res.data)
        setExportProductsInfo(res.data.exportProductsInfo)
        setG2ProductsInfo(res.data.g2ProductsInfo)
        setJumbleProductsInfo(res.data.jumbleProductsInfo)
      }
    })
  }

  const tableColumns = (key) => {
    const columns :ColumnProps<any>[] =[
      {
        title: 'S No',
        key: 'sno',
        width: '70px',
        responsive: ['sm'],
        render: (text, object, index) => (page - 1) * 10 + (index + 1)
      },
      {
        title:'Product',
        dataIndex:'product'
      },
      {
        title: 'Grade',
        dataIndex:'grade'
      },
      {
        title: 'Pack Style',
        dataIndex:'packStyle'
      },
      {
        title:'Quantity In Kgs',
        dataIndex:'qtyInKgs',
      }
    ]

    const exportProductColumns : ColumnProps<any>[] = [
      {
        title:'Cost Of Sale In INR',
        dataIndex:'costOfSaleInInr'
      },
      {
        title:'Export Value In INR',
        dataIndex:'exportValueInInr'
      },
      {
        title:'P&L In Inr',
        dataIndex:'plInInr'
      }
    ]

    const g2Columns : ColumnProps<any>[] = [
      {
        title:'Cost Of Production',
        dataIndex:'costOfProduction'
      },
      {
        title:'Realisation In INR',
        dataIndex:'realisationInInr'
      },
      {
        title:'P&L In Inr',
        dataIndex:'plInInr'
      }
    ]

    const jumbleProductColumns : ColumnProps<any>[] = [
      {
        title:'Cost Of Production',
        dataIndex:'costOfProduction'
      },
    ]
    if(key == 1){
      return [...columns,...exportProductColumns]
    }else if(key == 2){
      return [...columns,...g2Columns]
    } else if(key == 3){
      return [...columns,...jumbleProductColumns]
    }else{
      return [...columns]
    }
  }


  let x = 1
  const excelData = [
      { title: 'S No', dataIndex: 'sNo', render: (text, object,index) => { return x++; } },
      { title: 'Batch Number', dataIndex: 'batchNo', render: (text, record) => { return record.batchNo ? record.batchNo : '-' } },
      { title: 'Product', dataIndex: 'product', render: (text, record) => { return record.product ? record.product : '-' } },
      { title: 'Grade', dataIndex: 'grade', render: (text, record) => { return record.grade ? record.grade : '-' } },
      { title: 'Pack Style', dataIndex: 'packStyle', render: (text, record) => { return record.packStyle ? record.packStyle : '-' } },
      { title: 'SO Number', dataIndex: 'saleOrderNum', render: (text, record) => { return record.saleOrderNum ? record.saleOrderNum : '-' } },
      { title: 'Buyer', dataIndex: 'buyer', render: (text, record) => { return record.buyer ? record.buyer : '-' } },
      { title: 'FG Qty in kgs', dataIndex: 'fgQtyInKgs', render: (text, record) => { return record.fgQtyInKgs ? Number(record.fgQtyInKgs).toFixed(2) : '-' } },
      { title: 'Yield', dataIndex: 'fgYield', render: (text, record) => { return record.fgYield ? record.fgYield : '-' } },
      { title: 'Pack Count', dataIndex: 'packCount', render: (text, record) => { return record.packCount ? record.packCount : '-' } },
      { title: 'RM Count', dataIndex: 'rmCount', render: (text, record) => { return record.rmCount ? record.rmCount : '-' } },
      { title: 'RM Rate', dataIndex: 'rnRatePerKg', render: (text, record) => { return record.rnRatePerKg ? record.rnRatePerKg : '-' } },
      { title: 'RM Cost', dataIndex: 'rmCostPerKg', render: (text, record) => { return record.rmCostPerKg ? record.rmCostPerKg : '-' } },
      { title: 'MFG Cost', dataIndex: 'mfgCosttPerKg', render: (text, record) => { return record.mfgCosttPerKg ? record.mfgCosttPerKg : '-' } },
      { title: 'Packing Cost', dataIndex: 'packingCostPerKg', render: (text, record) => { return record.packingCostPerKg ? record.packingCostPerKg : '-' } },
      { title: 'Freight & Forwarding Expenses Cost', dataIndex: 'freightAndForwardExp', render: (text, record) => { return record.freightAndForwardExp ? record.freightAndForwardExp : '-' } },
      { title: 'Total Cost of Sales Per Kg', dataIndex: 'totalCostOfSalesPerKg', render: (text, record) => { return record.totalCostOfSalesPerKg ? record.totalCostOfSalesPerKg : '-' } },
      { title: 'In INR', dataIndex: 'inInr', render: (text, record) => { return record.inInr ? record.inInr : '-' } },
      { title: 'Cost Of Sales LB/Kg In USD', dataIndex: 'costOfSaleLbkgInUsd', render: (text, record) => { return record.costOfSaleLbkgInUsd ? record.costOfSaleLbkgInUsd : '-' } },
      { title: 'Sales Rate LB/Kg In USD', dataIndex: 'SalesRateLbkgInUsd', render: (text, record) => { return record.SalesRateLbkgInUsd ? record.SalesRateLbkgInUsd : '-' } },
      { title: 'PL Per Kg/Lb In USD', dataIndex: 'pLPerKgLbInUsd', render: (text, record) => { return record.pLPerKgLbInUsd ? record.pLPerKgLbInUsd : '-' } },
      { title: 'Incentives', dataIndex: 'incentives', render: (text, record) => { return record.incentives ? record.incentives : '-' } },
      { title: 'Total PL Per Kg/Lb In USD', dataIndex: 'totalPLPerKfLbInUsd', render: (text, record) => { return record.totalPLPerKfLbInUsd ? record.totalPLPerKfLbInUsd : '-' } },
    ]

    const exportExcel = () => {
      const excel = new Excel();
      excel
        .addSheet('Daywise-Prodcution-Report')
        .addColumns(excelData)
      //   .addDataSource(data.productInfo, { str2num: true })
      dayWiseProductionData.forEach(row => {
          excel.addDataSource([row], { str2num: true });
      });
        excel.saveAs('Daywise Produciton.xlsx');
    }

    const onFinish = () => {
      getProductionInfo()
      getDayWiseAnalysisInfo()
    }

    const onReset = () => {
      form.resetFields()
      setExportProductsInfo([])
      setJumbleProductsInfo([])
      setG2ProductsInfo([])
    }

  return (
    <Card size='small' title={<span style={{color:'white'}}>Daywise Production Report</span>} 
    style={{textAlign:'center'}} headStyle={{backgroundColor: '#69c0ff', border: 0 }} extra={dayWiseProductionData.length > 0 ? (<><Button onClick={() => exportExcel()}>Get Excel</Button></>) : (<></>)} >
      <Form form={form} onFinish={onFinish}>
      <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/>
        </Form.Item>
        </Col>
        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 2 }}>
        <Form.Item>
          <Button htmlType='submit' type='primary'>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 onClick={onReset} type='primary'>Reset</Button>
        </Form.Item>
        </Col>
      </Row>
      </Form>
      {
        exportProductInfo.length > 0 ? (<>
        <h3>Export Products</h3>
        <Table columns={tableColumns(1)} dataSource={exportProductInfo}/>
        </>) : (<></>)
      }
      {
        g2ProductInfo.length > 0 ? (<>
        <h3>GII,DC,BKN Products</h3>
        <Table columns={tableColumns(2)} dataSource={g2ProductInfo}/>
        </>) : (<></>)
      }
      {
        jumbleProductInfo.length > 0 ? (<>
        <h3>JUMBLE Products</h3>
        <Table columns={tableColumns(3)} dataSource={jumbleProductInfo}/>
        </>) : (<></>)
      }
      {
        exportProductInfo.length > 0 || g2ProductInfo.length > 0 || jumbleProductInfo.length > 0 ? (<>
        <Descriptions>
          <Descriptions.Item label='Total Cost In INR'>{analysisData?.totalCostInInr}</Descriptions.Item>
          <Descriptions.Item label='Total Realisation In INR'>{analysisData?.totalRealisationInInr}</Descriptions.Item>
          <Descriptions.Item label='P&L In INR'>{analysisData?.plInInr}</Descriptions.Item>
        </Descriptions>
        </>) : (<></>)
      }

    </Card>
  );
}

export default DayWiseProductionAnalysis;
