import React, { useEffect, useRef, useState } from 'react';
import { Button, Card, Col, DatePicker, Form, Input, Row, Select, Table, Tooltip } from 'antd';
import moment from 'moment';
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { SaleOrderService } from '@gtpl/shared-services/sale-management';
import { InvoiceRequest } from 'libs/shared-models/sale-management/src/lib/sale-order/invoice-reqest';
import ExcelJS from 'exceljs';
import Highlighter from 'react-highlight-words';
import { CheckCircleOutlined, CloseCircleOutlined, RightSquareOutlined, EditOutlined, SearchOutlined } from '@ant-design/icons';
import { PlantsDropDown } from '@gtpl/shared-models/masters';
import { UnitcodeService } from '@gtpl/shared-services/masters';
import { PurchasesProductService } from '@gtpl/shared-services/finance';



const BuyerWiseReport = () => {
  const [page, setPage] = React.useState(1);
  const [pageSize, setPageSize] = useState<number>(100);
  const [data, setData] = useState([]);
  const [filterData, setFilterData] = useState([]);
  const [invoiceNumbers, setInvoiceNumbers] = useState([]);
  const service = new SaleOrderService();
  const [form] = Form.useForm();
  const { Option } = Select;
  const { RangePicker } = DatePicker;
  const searchInput = useRef(null);
  const [searchedColumn, setSearchedColumn] = useState('');
  const [searchText, setSearchText] = useState('');
  const [isFilter, SetisFilter] = useState(false);
  const [plantData, setPlantData] = useState<PlantsDropDown[]>([]);
    const unitsService = new UnitcodeService();
    const purchaseService = new PurchasesProductService()
    const [unitId, setUnitId] = useState<number>(0);
    const [factoriesData, setFactoriesData] = useState([]);


  useEffect(() => {
    // getInfo();
    getInvoiceNumbers();
    getAllPlants();
        getAllCompanyNames();
        if (Number(localStorage.getItem('unit_id')) != 5) {
          form.setFieldsValue({ unitId: Number(localStorage.getItem('unit_id')) })
      }
  }, []);

  const getInfo = () => {
    const req = new InvoiceRequest();
    const poNumber = form.getFieldValue('poNumber');
    const poDate = form.getFieldValue('poDate');
    const shipmentDate = form.getFieldValue('shipmentDate');
  
    // Check if any filters are applied
    const isFilterApplied = poNumber || (poDate && poDate.length > 0) || (shipmentDate && shipmentDate.length > 0);
  
    // Add filters only if they exist
    if (poNumber) {
      req.poNumber = poNumber;
    }
    if (poDate && poDate.length > 0) {
      req.poDateStartDate = moment(poDate[0]).format('YYYY-MM-DD');
      req.poDateEndDate = moment(poDate[1]).format('YYYY-MM-DD');
    }
    if (shipmentDate && shipmentDate.length > 0) {
      req.shipmentDateStartDate = moment(shipmentDate[0]).format('YYYY-MM-DD');
      req.shipmentDateEndDate = moment(shipmentDate[1]).format('YYYY-MM-DD');
    }
    if (form.getFieldValue('companyId') !== undefined) {
      req.companyId = form.getFieldValue('companyId')
    } 
    if (Number(localStorage.getItem('unit_id')) != 5) {
      req.unitId = Number(localStorage.getItem('unit_id'));
  } else {
      req.unitId = unitId
  }

    service.getBuyerWiseOrdersReport(req)
      .then((res) => {
        if (res.status) {
          setData(res.data);
          setFilterData(res.data);
        } else {
          handleError(res.internalMessage);
        }
      })
      .catch((err) => handleError(err.message));
  };
  const getAllPlants = () => {
    unitsService.getAllMainPlants().then((res) => {
        if (res.status) {
            setPlantData(res.data);
        } else {
            setPlantData([]);
        }
    }).catch(err => {
        AlertMessages.getErrorMessage(err.message);
        setPlantData([]);
    })
}
const getAllCompanyNames = () => {
    purchaseService.getAllCompanys().then((res) => {
        if (res.status) {
            setFactoriesData(res.data)
        }
    })
}
const handleUnit = (value) => {
  setUnitId(value)
}
  

  const getInvoiceNumbers = () => {
    service.getDistinctPoNumbers({ unitId: Number(localStorage.getItem('unit_id')) })
      .then((res) => {
        if (res.status) {
          setInvoiceNumbers(res.data);
        } else {
          handleError(res.internalMessage);
        }
      })
      .catch((err) => handleError(err.message));
  };

  const handleError = (message) => {
    setData([]);
    setFilterData([]);
    AlertMessages.getErrorMessage(message);
  };

  const onFinish = () => {
    getInfo();
    SetisFilter(true)
  };

  const onReset = () => {
    setData([]);
    setFilterData([]);
    SetisFilter(false)
  };


  const getColumnSearchProps = (dataIndex: any) => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={searchInput}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => handleSearch(selectedKeys, confirm, dataIndex)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
        />
        <Button
          type="primary"
          onClick={() => handleSearch(selectedKeys, confirm, dataIndex)}
          icon={<SearchOutlined />}
          size="small"
          style={{ width: 90, marginRight: 8 }}
        >
          Search
        </Button>
        <Button onClick={() => handleReset(clearFilters)} size="small" style={{ width: 90 }}>
          Reset
        </Button>
      </div>
    ),
    filterIcon: filtered => (
      <SearchOutlined type="search" style={{ color: filtered ? '#1890ff' : undefined }} />
    ),
    onFilter: (value, record) =>
      record[dataIndex]
        ? record[dataIndex]
          .toString()
          .toLowerCase()
          .includes(value.toLowerCase())
        : false,
    onFilterDropdownVisibleChange: visible => {
      if (visible) { setTimeout(() => searchInput.current.select()); }
    },
    render: text =>
      text ? (
        searchedColumn === dataIndex ? (
          <Highlighter
            highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
            searchWords={[searchText]}
            autoEscape
            textToHighlight={text.toString()}
          />
        ) : text
      )
        : null

  });

  function handleSearch(selectedKeys, confirm, dataIndex) {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
  };

  function handleReset(clearFilters) {
    clearFilters();
    setSearchText('');
  };
  useEffect(() => {
    setPage(1); 
}, [filterData]);
  const columns = [
    {
      title: 'S No',
      key: 'sno',
      width: 70,
      render: (text, object, index) => (page - 1) * pageSize + (index + 1),
    },
    {
      title: 'PO Number',
      dataIndex: 'poNumber',
      width: 110,
      ...getColumnSearchProps('poNumber'),
      render: (text, record) => record.poNumber || '-',
     

    },
    {
      title: 'PO Date',
      dataIndex: 'poDate',
      width: 150,
      render: (text, record) => record.poDate ? moment(record.poDate).format('YYYY-MM-DD') : '-',
    },
    {
      title: 'Certification',
      dataIndex: 'certificateDetails',
      width: 110,
      ...getColumnSearchProps('certificateDetails'),
      render: (text, record) => record.certificateDetails || '-',
    },
    {
      title: 'Company',
      dataIndex: 'company',
      width: 110,
      ...getColumnSearchProps('company'),
      render: (text, record) => record.company || '-',

      
    },
    {
      title: 'Buyer Name',
      dataIndex: 'buyerName',
      width: 110,
      ...getColumnSearchProps('buyerName'),
      render: (text, record) => record.buyerName || '-',

    },
    {
      title: 'Brand',
      dataIndex: 'brand',
      width: 110,
      render: (text, record) => record.brand || '-',
      ...getColumnSearchProps('brand'),

    },
    {
      title: 'Product',
      dataIndex: 'products',
      width: 120,
      render: (text) => (
        <Tooltip title={text || '-'}>
          {text ? `${text.substring(0, 20)}...` : '-'}
        </Tooltip>
      ),
      ...getColumnSearchProps('products'),

    },
    {
      title: 'Grade',
      dataIndex: 'grade',
      width: 90,
      render: (text, record) => record.grade || '-',
      ...getColumnSearchProps('grade'),

    },
    {
      title: 'NO.Of M/C',
      dataIndex: 'noOfCases',
      width: 90,
      ...getColumnSearchProps('noOfCases'),
      render: (text, record) => {
        return <span>{`${Number(text).toLocaleString('en-IN')}`}</span>
      }

    },
    {
      title: 'Pack',
      dataIndex: 'packMethodName',
      width: 90,
      render: (text, record) => record.packMethodName || '-',
      ...getColumnSearchProps('packMethodName'),

    },
    {
      title: 'Shipment Date',
      dataIndex: 'shipmentDate',
      width: 150,
      render: (text, record) => record.shipmentDate ? moment(record.shipmentDate).format('YYYY-MM-DD') : '-',
    },
    {
      title: 'Country',
      dataIndex: 'countryName',
      width: 90,
      render: (text, record) => record.countryName || '-',
      ...getColumnSearchProps('countryName'),

    },
    {
      title: 'Destination',
      dataIndex: 'destination',
      width: 150,
      render: (text, record) => record.destination || '-',
      ...getColumnSearchProps('destination'),

    },
    {
      title: 'Mixed Grades',
      dataIndex: 'gradeList',
      width: 120,
      render: (text) => (
        <Tooltip title={text || '-'}>
          {text ? `${text.substring(0, 20)}...` : '-'}
        </Tooltip>
      ),
      ...getColumnSearchProps('gradeList'),

    },
    {
      title: 'Shipment Term',
      dataIndex: 'shipmentTerms',
      width: 90,
      render: (text, record) => record.shipmentTerms || '-',
      ...getColumnSearchProps('shipmentTerms'),

    },
  ];

  const exportExcel = () => {
    const groupedData = filterData.reduce((acc, item) => {
      const country = item.countryName || 'Unknown';
      let shipmentTerms = item.shipmentTerms || 'Unknown';
  
      if (shipmentTerms === 'SHIPPED') {
        const month = item.shipmentDate ? moment(item.shipmentDate).format('MMMM') : 'Unknown';
        shipmentTerms = `${month}`;
      }
  
      if (!acc[shipmentTerms]) {
        acc[shipmentTerms] = {};
      }
      if (!acc[shipmentTerms][country]) {
        acc[shipmentTerms][country] = [];
      }
      acc[shipmentTerms][country].push(item);
  
      return acc;
    }, {});
  
    const monthOrder = [
      'January', 'February', 'March', 'April', 'May', 'June', 
      'July', 'August', 'September', 'October', 'November', 'December'
    ];
  
    const sortedShipmentTerms = Object.keys(groupedData).sort((a, b) => {
      const aMonth = a.split(' ')[0];
      const bMonth = b.split(' ')[0];
      return monthOrder.indexOf(aMonth) - monthOrder.indexOf(bMonth);
    });
  
    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet('ShipmentTermsWiseData');
  
    const header = [
      'S No',
      'PO Number',
      'PO Date',
      'Certification',
      'Company',
      'Buyer Name',
      'Brand',
      'Product',
      'Grade',
      'NO.Of M/C',
      'Pack',
      'Shipment Date',
      'Country',
      'Destination',
      'Mixed Grades',
      'Shipment Term'
    ];
  
    worksheet.columns = header.map((h) => ({ header: h, key: h, width: 20 }));
  
    sortedShipmentTerms.forEach((shipmentTerm) => {
      Object.keys(groupedData[shipmentTerm]).forEach((country) => {
        worksheet.addRow([shipmentTerm, country]).commit();
        
        const headerRow = worksheet.addRow(header);
        headerRow.commit();
        headerRow.eachCell((cell) => {
          cell.fill = {
            type: 'pattern',
            pattern: 'solid',
            fgColor: { argb: 'FFFF00' }
          };
        });
  
        let totalNoOfMC = 0; // Initialize total for NO.Of M/C
  
        groupedData[shipmentTerm][country].forEach((item, index) => {
          const noOfMC = item.noOfCases ? Number(item.noOfCases) : 0;
          totalNoOfMC += noOfMC; // Add to total
  
          worksheet.addRow({
            'S No': index + 1,
            'PO Number': item.poNumber || '-',
            'PO Date': item.poDate ? moment(item.poDate).format('YYYY-MM-DD') : '-',
            'Certification': item.certificateDetails || '-',
            'Company': item.company || '-',
            'Buyer Name': item.buyerName || '-',
            'Brand': item.brand || '-',
            'Product': item.products || '-',
            'Grade': item.grade || '-',
            'NO.Of M/C': noOfMC,
            'Pack': item.packMethodName || '-',
            'Shipment Date': item.shipmentDate ? moment(item.shipmentDate).format('YYYY-MM-DD') : '-',
            'Country': item.countryName || '-',
            'Destination': item.destination || '-',
            'Mixed Grades': item.gradeList || '-',
            'Shipment Term': item.shipmentTerms || '-'
          }).commit();
        });
  
        // Add a total row for NO.Of M/C
        const totalRow = worksheet.addRow({
          'S No': 'Total',
          'NO.Of M/C': totalNoOfMC
        });
        totalRow.eachCell((cell) => {
          cell.font = { bold: true };
        });
        totalRow.commit();
  
        worksheet.addRow([]).commit(); // Add an empty row between countries
      });
      worksheet.addRow([]).commit(); // Add an empty row between shipment terms
    });
  
    workbook.xlsx.writeBuffer().then((buffer) => {
      const dataBlob = new Blob([buffer], { type: 'application/octet-stream' });
      saveAs(dataBlob, 'shipment-terms-wise-country-report.xlsx');
    });
  };
  




  return (
    <>
    <style>
      {`
      .ant-card-head-title {
          display: inline-block;
          flex: 1;
          padding: 6px 0;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
      }
      
      `}
      </style>
      <Card
        title={<span style={{ color: 'white' }}>Order Planning Report</span>}
        extra={<Button onClick={exportExcel}>Get Excel</Button>}
        style={{ textAlign: 'center' }}
        headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
      >
        <Form form={form} layout="vertical" onFinish={onFinish}>
          <Row gutter={24}>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
            <Form.Item
                name="unitId"
                label="Unit"
                rules={[
                    {
                        required: false, message: 'Select Unit',
                    },
                ]}
            >
                <Select
                    showSearch
                    optionFilterProp="children"
                    filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                    placeholder="Select Unit"
                    allowClear
                    style={{ width: '100%' }}
                    onChange={handleUnit}
                    disabled={Number(localStorage.getItem('unit_id')) != 5 ? true : false}
                >
                    {plantData.map(dropData => {
                        return <Option value={dropData.plantId}>{dropData.plantCode}</Option>
                    })}
                </Select>
            </Form.Item>
        </Col>
        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 4 }} lg={{ span: 4 }} xl={{ span: 4 }}>
                <Form.Item name="companyId" label="Company" >
        
            
                    <Select
                        placeholder="Select Company"
                        showSearch
                        optionFilterProp="children"
                        filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                        allowClear
                        dropdownMatchSelectWidth={false}

                    >
                        {factoriesData.map(dropData => {
                            return <Option key={dropData.companyId} value={dropData.companyId}>{dropData.company}</Option>
                        })}
                    </Select>
                </Form.Item>
            </Col>
            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 6 }} lg={{ span: 6 }} xl={{ span: 6 }}>
              <Form.Item name="poNumber" label="PO Number">
                <Select
                  showSearch
                  placeholder="Select PO Number"
                  optionFilterProp="children"
                  allowClear
                >
                  {invoiceNumbers.map(inc => (
                    <Option key={inc.PoNumber} value={inc.PoNumber}>
                      {inc.PoNumber}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 6 }} lg={{ span: 6 }} xl={{ span: 6 }}>
              <Form.Item label="PO Date" name="poDate" rules={[{ required: false, message: 'PO Date is required' }]}>
                <RangePicker  />
              </Form.Item>
            </Col>
            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 6 }} lg={{ span: 6 }} xl={{ span: 6 }}>
              <Form.Item label="Shipment Date" name="shipmentDate" rules={[{ required: false, message: 'Shipment Date is required' }]}>
                <RangePicker  />
              </Form.Item>
            </Col>
            <Col style={{ paddingLeft: '10px', marginTop: '30px' }}>
              <Form.Item>
                <Button type="primary" htmlType="submit">
                  Get Report
                </Button>
              </Form.Item>
            </Col>
            <Col style={{ paddingLeft: '10px', marginTop: '30px' }}>
              <Form.Item>
                <Button type="primary" htmlType="reset" onClick={onReset}>
                  Reset
                </Button>
              </Form.Item>
            </Col>
          </Row>
          {/* <Table
            columns={columns}
            dataSource={filterData}
            pagination={{
              current: page,
              pageSize,
              total: filterData.length,
              onChange: (current, pageSize) => {
                setPage(current);
                setPageSize(pageSize);
              },
            }}
          /> */}
  {isFilter && (
          <>
          <Row gutter={16}>
              <Col>
                <Card
                  title={`Total : ${filterData.length}`}
                  style={{
                    textAlign: 'left',
                    width: 200,
                    height: 41,
                    backgroundColor: '#bfbfbf',
                  }}
                />
              </Col>

              <Col>
                <Card
                  title={`POs: ${
                    new Set(filterData.map((item) => item.poNumber).filter(Boolean)).size
                  }`}
                  style={{
                    textAlign: 'left',
                    width: 200,
                    height: 41,
                    backgroundColor: '#bfbfbf',
                  }}
                />
              </Col>
            </Row>
            <Table
            bordered
            className="custom-table-wrapper"
            scroll={{ x: "max-content" }}
            columns={columns}
            dataSource={filterData}
            size="small"
pagination={{
  current: page,
  pageSize: pageSize,
  onChange: (current) => {
      setPage(current);
  }
}}
            summary={(pageData) => {
              let totalCartons = 0;
            
              pageData.forEach(({ noOfCases }) => {
                  totalCartons += parseFloat(noOfCases) || 0;
                });
            
              return (
                <Table.Summary.Row>
                  <Table.Summary.Cell index={8} colSpan={9}>
                    Total
                  </Table.Summary.Cell>
                  <Table.Summary.Cell index={9}>
                    {totalCartons.toFixed(2)}
                  </Table.Summary.Cell>
                </Table.Summary.Row>
              );
            }}
          />
          
          </>
  )}
        </Form>
      </Card>
    </>
  );
};

export default BuyerWiseReport;
