import React, { useEffect, useState } from 'react';
import {Button, Card, Col, DatePicker, Form, Row} from 'antd'
import {WarehouseDashboardService} from '@gtpl/shared-services/analytics'
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import ReactHTMLTableToExcel from 'react-html-table-to-excel';

import './pages-reports-reports-components-container-wise-abstract.css';
import Table, { ColumnProps } from 'antd/lib/table';
import { ContainerWiseAbstractModel, ContainerWiseAbstractReq } from '@gtpl/shared-models/warehouse-management';
const { MonthPicker } = DatePicker;
/* eslint-disable-next-line */
export interface ContainerWiseAbstractProps {}

export const ContainerWiseAbstract = (props: ContainerWiseAbstractProps) => {
  const [page,setPage] = useState<number>(1)
  const [abstractInfo,setAbstractInfo] = useState<any[]>([])
  const [selectedMonth,setSelectedMonth] = useState<number>()
  const [countryWiseInfo,setCountryWiseInfo] = useState<any[]>([])
  const service = new WarehouseDashboardService()
  const [data,setData] = useState<ContainerWiseAbstractModel>()
  const [form] = Form.useForm()
  const [selectedYear,setSelectedYear] = useState<number>()
  const monthNames = ["JAN","FEB","MARCH","APRIL","MAY","JUNE","JULY","AUG","SEP","OCT","NOV","DEC"];
  const [pageSize, setPageSize] = useState<number>(1);


  useEffect(() => {
    const date = new Date();
    const currentMonth = date.getMonth();
    const monthNumber = currentMonth + 1;
    setSelectedMonth(monthNumber)
    const currentYear = date.getFullYear()
    setSelectedYear(currentYear)
    getAbstractInfo(monthNumber,currentYear)
    
  },[])

  const getAbstractInfo = (month,year) => {
    const req = new ContainerWiseAbstractReq(year,month)
    service.getContainerWiseAbstract(req).then(res => {
      if(res.status){
        setData(res.data)
        setAbstractInfo(res.data.containerWiseAbstract)
        setCountryWiseInfo(res.data.countryWiseAbstract)
      }else{
        setAbstractInfo([])
        AlertMessages.getErrorMessage(res.internalMessage)
      }
    })
  }

  const updateProductionCostAnalysis = () =>{
    service.updateProductionCostAnalysis().then(res=>{
        if (res.status){
            // AlertMessages.getSuccessMessage(res.internalMessage)
            getAbstractInfo(selectedMonth,selectedYear)
        } else {
            AlertMessages.getErrorMessage(res.internalMessage)
        }
    })
}

  const columns : ColumnProps<any>[] = [
    {
        title: 'S No',
        key: 'sno',
        width: '70px',
        responsive: ['sm'],
        render: (text, object, index) => (page - 1) * 10 + (index + 1)
    },
    {
      title:'INV NO',
      dataIndex:'poNumber',
      render: (text, record) => {
        return record.poNumber ? record.poNumber : '-'
      }

    },
    {
      title:'Buyer',
      dataIndex:'buyer',
      render: (text, record) => {
        return record.buyer ? record.buyer : '-'
      }

    },
    {
      title:'Product',
      dataIndex:'shortCode',
      render: (text, record) => {
        return record.shortCode ? record.shortCode : '-'
      }
    },
    {
      title:'Grade',
      dataIndex:'grade',
      render: (text, record) => {
        return record.grade ? record.grade : '-'
      }
    },
    {
      title:'Country',
      dataIndex:'country',
      render: (text, record) => {
        return record.country ? record.country : '-'
      }
    },
    {
      title:'Pack',
      dataIndex:'packStyle',
      render: (text, record) => {
        return record.packStyle ? record.packStyle : '-'
      }
    },
    {
      title:'Total Qty in Kgs',
      dataIndex:'totalQty',
      render: (text, record) => {
        return record.totalQty ? record.totalQty : '-'
      }
    },
    {
      title:'Exchange Rate',
      dataIndex:'exchangeRate',
      render: (text, record) => {
        return record.exchangeRate ? record.exchangeRate : '-'
      }
    },
    {
      title:'RM Count',
      dataIndex:'rmCount',
      render: (text, record) => {
        return record.rmCount ? record.rmCount : '-'
      }
    },
    {
      title:'RM Rate',
      dataIndex:'rmRate',
      render: (text, record) => {
        return record.rmRate ? record.rmRate : '-'
      }
    },
    {
      title:'RM Cost',
      dataIndex:'rmCost',
      render: (text, record) => {
        return record.rmCost ? record.rmCost : '-'
      }

    },
    {
      title:'MFG Cost',
      dataIndex:'mfgCost',
      render: (text, record) => {
        return record.mfgCost ? record.mfgCost : '-'
      }
    },
    {
      title:'Fixed Cost',
      dataIndex:'fixedCost',
      render: (text, record) => {
        return record.fixedCost ? record.fixedCost : '-'
      }
    },
    {
      title:'Packing Cost',
      dataIndex:'packingCost',
      render: (text, record) => {
        return record.packingCost ? record.packingCost : '-'
      }
    },
    {
      title:'Freight&Forwarding Cost',
      dataIndex:'freightAndForwardingCost',
      render: (text, record) => {
        return record.freightAndForwardingCost ? record.freightAndForwardingCost : '-'
      }
    },
    {
      title:'Total Expenses',
      dataIndex:'totalExpenses',
      render: (text, record) => {
        return record.totalExpenses ? record.totalExpenses : '-'
      }
    },
    {
      title:'Total Cost Of Sales',
      dataIndex:'totalCostOfSales',
      render: (text, record) => {
        return record.totalCostOfSales ? record.totalCostOfSales : '-'
      }
    },
    {
      title:'Cost Of Sales Per LB/KG in USD',
      dataIndex:'costOfSalesPerLbKgUsd',
      render: (text, record) => {
        return record.costOfSalesPerLbKgUsd ? record.costOfSalesPerLbKgUsd : '-'
      }

    },
    {
      title:'Export Rate Per LB/KG',
      dataIndex:'exportRate',
      render: (text, record) => {
        return record.exportRate ? record.exportRate : '-'
      }
    },
    {
      title:'P&L per LB/KG',
      dataIndex:'pLPerLbKg',
      render: (text, record) => {
        return record.pLPerLbKg ? record.pLPerLbKg : '-'
      }
    },
    {
      title:'Incentives Per LB/KG',
      dataIndex:'incentives',
      render: (text, record) => {
        return record.incentives ? record.incentives : '-'
      }
      
    }, 
    {
      title:'Total In USD P&L per LB/KG',
      dataIndex:'totalInUsdPLPerLbKg',
      render: (text, record) => {
        return record.totalInUsdPLPerLbKg ? record.totalInUsdPLPerLbKg : '-'
      }
    },
    {
      title:'Total P&L in INR',
      dataIndex:'toatlPLInInr',
      render: (text, record) => {
        return record.toatlPLInInr ? record.toatlPLInInr : '-'
      }
    }
  ]

  const countryWisecolumns : ColumnProps<any>[] = [
    {
      title:'Country',
      dataIndex:'country',
      render: (text, record) => {
        return record.country ? record.country : '-'
      }
     
    },
    {
      title:'No.Of FCL',
      dataIndex:'noOfFcl',
      render: (text, record) => {
        return record.noOfFcl ? record.noOfFcl : '-'
      }
    },
    {
      title:'P&L In Inr',
      dataIndex:'plInInr',
      render: (text, record) => {
        return record.plInInr ? record.plInInr : '-'
      }
      
    }
  ]

  const onSearch = () => {
    updateProductionCostAnalysis()
    console.log(form.getFieldValue('date'))
  }

  const handleMonthChange = (date, dateString) => {
    if (date) {
      const year = date.year();
      const month = date.month() + 1; // month() returns 0-11, so we add 1
      console.log('Selected year:', year);
      console.log('Selected month:', month);
      setSelectedMonth(month)
      setSelectedYear(year)
    }
  };

  const onReset = () => {
    setData(null)
    setAbstractInfo([])
    setCountryWiseInfo([])
    form.resetFields()
  }
  

  return (
    <Card size='small' title={<span style={{color:'white'}}>Container Wise Abstract</span>} 
    style={{textAlign:'center'}} headStyle={{backgroundColor: '#69c0ff', border: 0 }}>
        <Form onFinish={onSearch} form={form}>
          <Row gutter={24}>
            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 5 }}>
            <Form.Item name='date' label="Month">
              <MonthPicker style={{width:'100%'}} onChange={handleMonthChange} placeholder='Select Month'/>
            </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: '34px'}}>
            <Form.Item>
              <Button type='primary' onClick={onReset}>Reset</Button>
            </Form.Item>
            </Col>

          </Row>
        </Form>
        <br/>
        {
          data  ? ( <>
          <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
            <ReactHTMLTableToExcel
              id='excel-button'
              // className='download-table-xls-button'
              table='container-wise-abstract'
              filename='containerWiseAbstractxls'
              sheet="Sheet 1"
              buttonText='Get Excel'
              className="ant-btn ant-btn-primary"
              />
              </div>
            <h3>CONTAINER WISE COSTING FOR THE MONTH OF {monthNames[selectedMonth-1]}</h3>
            <Table columns={columns} dataSource={abstractInfo} scroll={{x:'max-content'}} pagination={{
            onChange(current,pageSize) {
              setPage(current);
              setPageSize(pageSize);
            }
          }}/>
            <br/>
            <Table columns={countryWisecolumns} dataSource={countryWiseInfo}/>
          </>) : (<></>)
        }


        { data ? (<>
        
          <table id='container-wise-abstract' hidden>
            <table style={{borderCollapse:'collapse',borderBlockColor:'black',overflow:'scroll',width:'100%'}}>
              <tr>
                <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>INV NO</th>
                <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>Buyer</th>
                <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>Product</th>
                <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>Grade</th>
                <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>Country</th>
                <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>Pack</th>
                <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>Total Qty in Kgs</th>
                <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>Exchange Rate</th>
                <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>RM Count</th>
                <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>RM Rate</th>
                <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>RM Cost</th>
                <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>MFG Cost</th>
                <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>Fixed Cost</th>
                <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>Packing Cost</th>
                <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>Freight&Forwarding Cost</th>
                <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>Total Expenses</th>
                <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>Total Cost Of Sales</th>
                <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>Cost Of Sales Per LB/KG in USD</th>
                <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>Export Rate Per LB/KG</th>
                <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>P&L per LB/KG</th>
                <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>Incentives Per LB/KG</th>
                <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>Total In USD P&L per LB/KG</th>
                <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>Total P&L in INR</th>
              </tr>
              {
                abstractInfo.map(rec => {
                  return(
                    <tr>
                      <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>{rec.poNumber}</th>
                      <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>{rec.buyer}</th>
                      <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>{rec.shortCode}</th>
                      <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>{rec.grade}</th>
                      <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>{rec.country}</th>
                      <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>{rec.packStyle}</th>
                      <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>{rec.totalQty}</th>
                      <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>{rec.exchangeRate}</th>
                      <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>{rec.rmCount}</th>
                      <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>{rec.rmRate}</th>
                      <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>{rec.rmCost}</th>
                      <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>{rec.mfgCost}</th>
                      <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>{rec.fixedCost}</th>
                      <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>{rec.packingCost}</th>
                      <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>{rec.freightAndForwardingCost}</th>
                      <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>{rec.totalExpenses}</th>
                      <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>{rec.totalCostOfSales}</th>
                      <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>{rec.costOfSalesPerLbKgUsd}</th>
                      <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>{rec.exportRate}</th>
                      <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>{rec.pLPerLbKg}</th>
                      <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>{rec.incentives}</th>
                      <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>{rec.totalInUsdPLPerLbKg}</th>
                      <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>{rec.toatlPLInInr}</th>

                    </tr>
                  )
                })
              }
            </table>
            <br/>
            <table style={{borderCollapse:'collapse',borderBlockColor:'black',width:'100%'}}>
              <tr>
                <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>Country</th>
                <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>No.Of FCL</th>
                <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>P&L In Inr</th>
              </tr>
              {
                countryWiseInfo.map(rec => {
                  return(
                    <tr>
                      <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>{rec.country}</th>
                      <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>{rec.noOfFcl}</th>
                      <th style={{textAlign:'center',fontSize:'15px',border:'2px solid black',width:'80px'}}>{rec.plInInr}</th>

                    </tr>
                  )
                })
              }
            </table>

          </table>
        </>) : (<></>)
         
        }
        
     

    </Card>
  );
}

export default ContainerWiseAbstract;
