import React, { useEffect, useState } from 'react';
import { Button, Card, Col, DatePicker, Form, Row, Select, Table } from 'antd';
import moment from 'moment';
import { saveAs } from 'file-saver';
import ExcelJS from 'exceljs';
import { ProductionInventoryService } from 'libs/shared-services/production/src/lib/production-inventory.service';
import { InvoiceRequest, ReportRequest } from 'libs/shared-models/sale-management/src/lib/sale-order/invoice-reqest';
import { ProductionProcessDashboardReq } from '@gtpl/shared-models/production-management';
import { ProdlogService } from '@gtpl/shared-services/production';
import { GrnService } from '@gtpl/shared-services/procurement';

const SoakingAnalysisReport = () => {
  const [data, setData] = useState<any[]>([]);
  const [form] = Form.useForm();
  const service = new ProductionInventoryService()
  const [pageSize, setPageSize] = useState(20);
  const [page, setPage] = useState(1);
  const [soakingData,setSoakingData]=useState<any[]>([])
    const {Option}=Select;
    const loggedInUnitId = Number(localStorage.getItem('unit_id'));
    const [unitCodes, setUnitCodes] = useState([]);
    const grnService = new GrnService()

  const getInfo = () => {
    const req = new ReportRequest();
    const dateRange = form.getFieldValue('dateRange');
    if (dateRange !== undefined) {
      req.startDate = moment(dateRange[0]).format('YYYY-MM-DD');
      req.endDate = moment(dateRange[1]).format('YYYY-MM-DD');
    }
    if(loggedInUnitId === 5) {
      if (form.getFieldValue('unitId') !== undefined) {
        req.unitId = form.getFieldValue('unitId');
      }}else{
        req.unitId = loggedInUnitId; // Convert number to string
      }
    service.getSoackingData(req)
      .then((res) => {
        if (res.status) {
          setData(res.data);
        } else {
          handleError(res.internalMessage);
        }
      })
      .catch((err) => handleError(err.message));
  };

      useEffect(() => {
        getAllUnits();
      }, []);
    
      const getAllUnits = () => {
        grnService.getUnitsForCeoDashboard().then((res) => {
          if (res.status) {
            setUnitCodes(res.data);
          }
        });
      };

  const getSoakingDataForProductionReport = () => {
    const req = new ProductionProcessDashboardReq()
    const dateRange = form.getFieldValue('dateRange');
    if (dateRange !== undefined) {
      req.startDate = moment(dateRange[0]).format('YYYY-MM-DD');
      req.endDate = moment(dateRange[1]).format('YYYY-MM-DD');
    }
    if(loggedInUnitId === 5) {
      if (form.getFieldValue('unitId') !== undefined) {
        req.unitId = form.getFieldValue('unitId');
      }}else{
        req.unitId = loggedInUnitId; // Convert number to string
      }
    // const selectedDate = form.getFieldValue('date')

    // if (selectedDate) {
    //   req.date = moment(selectedDate).format('YYYY-MM-DD')
    // }

    service.getSoakingDataForSoakingReport(req).then((res) => {
      if (res.status) {
        setSoakingData(res.data)
      } else {
        setSoakingData([])
      }
    })
  }

  const handleError = (message: string) => {
    setData([]);
    console.error(message);
    // Handle error message display or other actions as needed
  };

  const onFinish = (values: any) => {
    console.log('Search values:', values);
    getInfo();
    getSoakingDataForProductionReport()
  };

  const onReset = () => {
    form.resetFields();
    setData([]);
  };

  const calculateTotals = (productGroup: any[]) => {
    const totals = {
      soakqty: 0,
      production: 0,
      yield: 0,
    };
    let totalEntries = 0;

    productGroup.forEach((product) => {
      product.data.forEach((entry) => {
        totals.soakqty += parseFloat(entry.soakqty || 0);
        totals.production += parseFloat(entry.production || 0);
        totals.yield += parseFloat(entry.yield || 0);
        totalEntries += 1;
      });
    });

    totals.yield = totalEntries > 0 ? totals.yield / totalEntries : 0; // Average yield
    return totals;
  };

  const exportExcel = () => {
    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet('Soaking Analysis Report');

    // Define styles for headers and rows
    const headerStyle = {
      font: { bold: true },
      alignment: { vertical: 'middle', horizontal: 'center' },
      border: {
        bottom: { style: 'thin', color: { argb: '00000000' } }
      },
      fill: { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FFFFFF00' } }
    };

    const rowStyle = {
      alignment: { vertical: 'middle', horizontal: 'center' },
      border: {
        bottom: { style: 'thin', color: { argb: '00000000' } }
      }
    };

    const chunkArray = (arr, size) =>
      arr.reduce((acc, _, i) => (i % size ? acc : [...acc, arr.slice(i, i + size)]), []);

    const productChunks = chunkArray(data, 5);

    const generateTable = (worksheet, productGroup, startRow) => {
      const uniqueDates = Array.from(new Set([].concat(...productGroup.map(product => product.data.map(entry => moment(entry.date).format('DD-MM-YYYY'))))));
      const sortedDates = uniqueDates.sort((a, b) => moment(a, 'DD-MM-YYYY').diff(moment(b, 'DD-MM-YYYY')));

      const headerRow1 = [];
      const headerRow2 = [];
      productGroup.forEach(product => {
        headerRow1.push(product.product, '', '', '');
        headerRow2.push('DATE', 'SOAK IN KGS', 'PRODUCTION IN KGS', 'YIELD %');
      });

      const row1 = worksheet.getRow(startRow);
      const row2 = worksheet.getRow(startRow + 1);
      row1.values = headerRow1;
      row2.values = headerRow2;

      let colStart = 1;
      productGroup.forEach(() => {
        worksheet.mergeCells(startRow, colStart, startRow, colStart + 3);
        colStart += 4;
      });

      row1.eachCell(cell => {
        cell.style = headerStyle;
      });
      row2.eachCell(cell => {
        cell.style = headerStyle;
      });

      sortedDates.forEach((date, index) => {
        const row = worksheet.getRow(startRow + 2 + index);
        const rowData = [];
        productGroup.forEach(product => {
          const entry = product.data.find(d => moment(d.date).format('DD-MM-YYYY') === date);
          rowData.push(
            date,
            entry ? parseFloat(entry.soakqty) : '',
            entry ? parseFloat(entry.production) : '',
            entry ? ((parseFloat(entry.production) / parseFloat(entry.soakqty)) * 100).toFixed(2) : ''
          );
        });
        row.values = rowData;
        row.eachCell(cell => {
          cell.style = rowStyle;
        });
      });

      const totalRow = worksheet.getRow(startRow + 2 + sortedDates.length);
      const totalRowData = [];
      productGroup.forEach(product => {
        const totalSoakQty = product.data.reduce((acc, curr) => acc + parseFloat(curr.soakqty), 0);
        const totalProduction = product.data.reduce((acc, curr) => acc + parseFloat(curr.production), 0);
        const totalYield = ((totalProduction / totalSoakQty) * 100).toFixed(2);
        totalRowData.push('TOTAL', totalSoakQty, totalProduction, totalYield);
      });
      totalRow.values = totalRowData;
      totalRow.eachCell(cell => {
        cell.style = rowStyle;
        cell.font = { bold: true };
      });

      // Adding the summary table for all products
      const summaryStartRow = startRow + 4 + sortedDates.length;
      const summaryHeader = ['PRODUCT', 'SOAK IN TONS', 'PRODUCTION IN TONS', 'PICK UP %', 'TARGET %'];

      const summaryData = soakingData.map(product => {
        const totalSoakQty = product.inputQuantity ? parseFloat(product.inputQuantity) : 0;
        const totalProduction = product.actualOutputQuantity ? parseFloat(product.actualOutputQuantity).toFixed(2) : '0.00';
        const pickUpPercentage = product.yieldPercent ? parseFloat(product.yieldPercent).toFixed(2) : '0.00';
        const target = product.soakingYield ? parseFloat(product.soakingYield).toFixed(2) : '0.00';
      
        return [product.product, totalSoakQty, totalProduction, pickUpPercentage, target];
      });
      if (summaryData.length > 0) {
        worksheet.addRow([]);
      const summaryHeaderRow = worksheet.addRow(summaryHeader);
      summaryHeaderRow.eachCell(cell => {
        cell.style = headerStyle;
      });
    }

      summaryData.forEach(rowData => {
        worksheet.addRow(rowData).eachCell(cell => {
          cell.style = rowStyle;
        });
      });

      worksheet.columns.forEach(column => {
        let maxWidth = 10;
        column.eachCell(cell => {
          const columnWidth = cell.value ? cell.value.toString().length : 10;
          if (columnWidth > maxWidth) {
            maxWidth = columnWidth;
          }
        });
        column.width = maxWidth < 20 ? 20 : maxWidth;
      });
    };

    let currentRow = 1;
    productChunks.forEach((chunk, index) => {
      if (index !== 0) {
        currentRow += chunk[0].data.length + 4;
      }
      generateTable(worksheet, chunk, currentRow);
    });

    workbook.xlsx.writeBuffer().then(buffer => {
      const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      saveAs(blob, 'soaking_analysis_report.xlsx');
    });
  };

  const { RangePicker } = DatePicker;

  // Generate columns dynamically
  const columns = [];
  data.forEach(product => {
    columns.push(
      {
        title: product.product,
        children: [
          {
            title: 'S No',
            key: 'sNo',
            width: 70,
            // render: (text, record, index) => (page - 1) * pageSize + index + 1,
            render: (_, record, index) => (record.key === 'total' ? '' : index + 1),
          },
          {
            title: 'Date',
            dataIndex: `date_${product.product}`,
            key: `date_${product.product}`,
            width: 130,
            align: 'center',
          },
          {
            title: 'Soak in KGS',
            dataIndex: `soakqty_${product.product}`,
            key: `soakqty_${product.product}`,
            width: 110,
            align: 'center',
          },
          {
            title: 'Production in KGS',
            dataIndex: `production_${product.product}`,
            key: `production_${product.product}`,
            width: 120,
            align: 'center',
          },
          {
            title: 'Yield %',
            dataIndex: `yield_${product.product}`,
            key: `yield_${product.product}`,
            width: 110,
            align: 'center',
          }
        ]
      }
    );
  });

  // Generate data source dynamically
  const uniqueDates = Array.from(new Set([].concat(...data.map(product => product.data.map(item => moment(item.date).format('DD-MM-YYYY'))))));
  const dataSource = uniqueDates.map(date => {
    const rowData = { key: date };
    data.forEach(product => {
      const entry = product.data.find(item => moment(item.date).format('DD-MM-YYYY') === date);
      rowData[`date_${product.product}`] = date;
      rowData[`soakqty_${product.product}`] = entry ? parseFloat(entry.soakqty) : '';
      rowData[`production_${product.product}`] = entry ? parseFloat(entry.production) : '';
      rowData[`yield_${product.product}`] = entry ? parseFloat(entry.yield) : '';
    });
    return rowData;
  });

  const totalRow = { key: 'total', date: 'TOTAL' };
data.forEach(product => {
  const totalSoakQty = dataSource.reduce((sum, row) => sum + (row[`soakqty_${product.product}`] || 0), 0);
  const totalProduction = dataSource.reduce((sum, row) => sum + (row[`production_${product.product}`] || 0), 0);
  const totalYield = totalProduction && totalSoakQty ? ((totalProduction / totalSoakQty) * 100).toFixed(2) : 0;

  totalRow['S No'] = '';
  totalRow[`date_${product.product}`] = 'TOTAL';
  totalRow[`soakqty_${product.product}`] = totalSoakQty;
  totalRow[`production_${product.product}`] = totalProduction;
  totalRow[`yield_${product.product}`] = totalYield;
});

dataSource.push(totalRow);

const SoakingColumns=[
  {
    title:"PRODUCT",
    dataIndex:"product"
  },
  {
    title:"SOAK IN TONS",
    dataIndex:"inputQuantity"
  },
  {
    title:"PRODUCTION IN TONS",
    dataIndex:"actualOutputQuantity"
  },
  {
    title:"PICK UP %",
    dataIndex:"yieldPercent"
  },
  {
    title:"TARGET %",
    dataIndex:"soakingYield"
  }
]

  return (
    <Card
      title={<span style={{ color: 'white' }}>Soaking Analysis Report</span>}
      extra={<Button onClick={exportExcel}>Get Excel</Button>}
      style={{ textAlign: 'center' }}
      headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
    >
      <Form form={form} layout="horizontal" onFinish={onFinish}>
        <Row gutter={24}>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 6 }} lg={{ span: 6 }} xl={{ span: 7 }}>
            <Form.Item label="Date Range" name="dateRange">
              <RangePicker style={{width:'100%'}}/>
            </Form.Item>
          </Col>
          <Col
              xs={{ span: 24 }}
              sm={{ span: 24 }}
              md={{ span: 6 }}
              lg={{ span: 6 }}
              xl={{ span: 6 }}
            >
              <Form.Item name="unitId" label="Unit">
                <Select
                  placeholder="Select Unit"
                  showSearch
                  optionFilterProp="children"
                  filterOption={(input, option) =>
                    option.children
                      .toLowerCase()
                      .indexOf(input.toLowerCase()) >= 0
                  }
                  allowClear
                  disabled={
                    Number(localStorage.getItem('unit_id')) != 5 ? true : false
                  }
                  defaultValue={
                    loggedInUnitId == 5
                      ? ''
                      : Number(localStorage.getItem('unit_id'))
                  }
                >
                  {unitCodes.map((dropData) => {
                    return (
                      <Option value={dropData.unitCodeId}>
                        {dropData.plantCode}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 6 }} lg={{ span: 6 }} 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: 6 }} lg={{ span: 6 }} xl={{ span: 2 }}>
            <Form.Item>
              <Button type="primary" htmlType="reset" style={{marginLeft:'15px'}} onClick={onReset}>
                Reset
              </Button>
            </Form.Item>
          </Col>
        </Row>
      </Form>
    {
      dataSource.length > 0 ? (<>
        <Table
          bordered
          className="custom-table-wrapper"
          scroll={{ x: "max-content", y: 450 }}
          columns={columns}
          dataSource={dataSource}
          size="small"
          pagination={{
            pageSize: 100,
            onChange(current, pageSize) {
              setPage(current);
              setPageSize(pageSize);
            },
          }}
        />
      
      </>) : (<></>)
    }

      <br />
      {
        soakingData.length > 0 ? (<>
              <Table style={{width:"60%"}} columns={SoakingColumns} dataSource={soakingData}/>
        </>) : (<></>)
      }
    </Card>
  );
};

export default SoakingAnalysisReport;
