import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { Button, Card, Col, DatePicker, Form, Input, Row, Select } from 'antd';
import Table, { ColumnProps } from 'antd/lib/table';
import React, { useEffect, useRef, useState } from 'react';
import { GradingService } from "@gtpl/shared-services/production";
import { Excel } from 'antd-table-saveas-excel';
import moment from 'moment';
import { SearchOutlined } from '@ant-design/icons';
import Highlighter from 'react-highlight-words';
import { GrnService } from '@gtpl/shared-services/procurement';

import form from 'antd/lib/form';
import { ProductionLogRequest } from 'libs/shared-models/production-management/src/lib/production-inv/production-log.req';

const GradingAnalysisReport = () => {
    const [page, setPage] = useState(1);
    const service = new GradingService();
    const [searchedColumn, setSearchedColumn] = useState('');
    const searchInput = useRef(null);
    const [searchText, setSearchText] = useState('');
    const [showTable, setShowTable] = useState(false);


    const [gradeData, setGradeData] = useState([]);
    const [selectedEstimatedFromDate, setSelectedEstimatedFromDate] = useState(undefined);
    const [selectedEstimatedToDate, setSelectedEstimatedToDate] = useState(undefined);
    const { RangePicker } = DatePicker;
    const [form] = Form.useForm();
    const [disable,setDisable]=useState<boolean>(false);
    const {Option}=Select;
    const loggedInUnitId = Number(localStorage.getItem('unit_id'));
    const [unitCodes, setUnitCodes] = useState([]);
    const grnService = new GrnService()

    useEffect(() => {
        // getAllGradeAnalysisReport();
    }, []);
    interface GroupedDataItem {
      scode: string;
      honQuantity: number;
      count: number;
      date: string | null;
      total: number;
      [key: string]: any;  // This allows additional dynamic keys for grades
    }

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

    const getAllGradeAnalysisReport = (onReset?:boolean) => {
        let fromDate = onReset ? undefined : selectedEstimatedFromDate;
        let toDate = onReset ? undefined : selectedEstimatedToDate;
      
        const req = new ProductionLogRequest();
        req.fromDate=fromDate
        req.toDate=toDate
        if(loggedInUnitId === 5) {
          if (form.getFieldValue('unitId') !== undefined) {
            req.unitId = form.getFieldValue('unitId');
          }}else{
            req.unitId = loggedInUnitId; // Convert number to string
          }
        service.getGradingAnalysisReport(req)
            .then((res) => {
                if (res.status) {
                    const transformedData = transformData(res.data);
                    setGradeData(transformedData);
                } else {
                    setGradeData([]);
                }
            }).catch(err => {
                AlertMessages.getErrorMessage(err.message);
                setGradeData([]);
            });
    };

    const getColumnSearchProps = (dataIndex) => ({
        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={() => handleSearch1(selectedKeys, confirm, dataIndex)}
              style={{ width: 188, marginBottom: 8, display: 'block' }}
            />
            <Button
              type="primary"
              onClick={() => handleSearch1(selectedKeys, confirm, dataIndex)}
              icon={<SearchOutlined />}
              size="small"
              style={{ width: 90, marginRight: 8 }}
            >
              Search
            </Button>
            <Button type="primary" onClick={() => handleReset(clearFilters)} size="small" style={{ width: 90 }}>
              Reset
            </Button>
          </div>
        ),
        filterIcon: filtered => (
          <SearchOutlined 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(), 100);
          }
        },
        render: text =>
          searchedColumn === dataIndex ? (
            <Highlighter
              highlightStyle={{ backgroundColor: '#ffc069', padding: 0 }}
              searchWords={[searchText]}
              autoEscape
              textToHighlight={text.toString()? text.toString() : ''}
            />
          ) : (
            text
          ),
      });
      const handleSearch1 = (selectedKeys, confirm, dataIndex) => {
        confirm();
        setSearchText(selectedKeys[0]);
        setSearchedColumn(dataIndex);
      };
    
      const handleReset = (clearFilters) => {
        clearFilters();
        setSearchText('');
      };


      const handleSearch = () => {
        // Check if the date filters are selected before showing the table
        if (selectedEstimatedFromDate && selectedEstimatedToDate) {
            getAllGradeAnalysisReport();
            setShowTable(true); // Show the table when "Search" is clicked
        } else {
            AlertMessages.getErrorMessage('Please select a date range');
        }
    };
    const EstimatedETDDate = (value) => {
      if (value) {
          // Format the dates as yyyy-MM-dd using the format method
          const fromDate = value[0].format('YYYY-MM-DD'); 
          const toDate = value[1].format('YYYY-MM-DD');
          
          // Save the formatted dates to state
          setSelectedEstimatedFromDate(fromDate);
          setSelectedEstimatedToDate(toDate);
          
          setShowTable(false);
  
          // Format response or log properly formatted dates
          const response = {
              fromDate,
              toDate,
          };
  
          console.log("Formatted Response:", response);
          // Or use this formatted response in your API or state update logic
      }
  };
  
  



      const onReset = () => {
        form.resetFields();
        setSelectedEstimatedFromDate(undefined);
        setSelectedEstimatedToDate(undefined);
          // setReportData([]);
        }

    const transformData = (data: any[]): GroupedDataItem[] => {
      // Create a map to group by `scode`, `honQuantity`, and `count` (excluding date)
      const groupedData: { [key: string]: GroupedDataItem } = {};
    
      data.forEach(item => {
        const key = `${item.scode}-${item.honQuantity}-${item.count}`;  // Removed date from the key
    
        if (!groupedData[key]) {
          // Initialize the base structure for each unique combination
          groupedData[key] = {
            scode: item.scode,
            honQuantity: parseFloat(item.honQuantity),
            count: parseFloat(item.count),
            date: moment(item.date).isValid() ? moment(item.date).format('YYYY-MM-DD') : null,
            total: parseFloat(item.quantity)
          };
        } else {
          // Accumulate total quantity
          groupedData[key].total += parseFloat(item.quantity);
        }
    
        const gradeKey = item.grade ? item.grade.replace("-", "/") : null;
    
        if (gradeKey) {
          // Accumulate quantity for each grade column
          if (!groupedData[key][gradeKey]) {
            groupedData[key][gradeKey] = 0;  // Initialize if not present
          }
          groupedData[key][gradeKey] += parseFloat(item.quantity);  // Add the quantity to the existing value
        }
      });
    
      // After all data is accumulated, calculate the correct yield
      Object.values(groupedData).forEach((group: GroupedDataItem) => {
        group.yield = ((group.total / group.honQuantity) * 100).toFixed(2) + '%';  // Correct yield calculation
      });
    
      // Return as an array
      return Object.values(groupedData);
    };
    
    
  
  
  
    
    

    const gradeColumns: ColumnProps<any>[] = [
        {
            title: 'S No',
            key: 'id',
            width: '70px',
            responsive: ['md'],
            align: 'left',
            render: (text, object, index) => (page - 1) * 10 + (index + 1),
        },
        {
            title: 'Date',
            key: 'date',
            dataIndex: 'date',
            width: '200px',
            responsive: ['md'],
            align: 'left',
            // render: (text: any, record: any) => { return record.date ? moment(record.date).format('YYYY-MM-DD') : '-' },

        },
        {
            title: 'S.Code',
            key: 'scode',
            dataIndex: 'scode',
            width: '70px',
            responsive: ['md'],
            align: 'left',
            ...getColumnSearchProps('scode'),

        },
        {
            title: 'Count',
            key: 'count',
            dataIndex: 'count',
            width: '70px',
            responsive: ['md'],
            align: 'left',
            ...getColumnSearchProps('count'),
          

        },
        {
            title: 'HON Quantity',
            key: 'honQuantity',
            dataIndex: 'honQuantity',
            width: '70px',
            responsive: ['md'],
            align: 'left',
           render: (text) => {
  const value = parseFloat(text);
  return isNaN(value) ? "-" : value.toFixed(2);
}
        },
        {
            title: '8/12',
            key: '8/12',
            dataIndex: '8/12',
            width: '70px',
            responsive: ['md'],
            align: 'left',
            render: (text) => {
              const value = parseFloat(text);
              return isNaN(value) ? "-" : value.toFixed(2);
            }
        },
        {
            title: '13/15',
            key: '13/15',
            dataIndex: '13/15',
            width: '70px',
            responsive: ['md'],
            align: 'left',
           render: (text) => {
  const value = parseFloat(text);
  return isNaN(value) ? "-" : value.toFixed(2);
}
        },
        {
            title: '16/20',
            key: '16/20',
            dataIndex: '16/20',
            width: '70px',
            responsive: ['md'],
            align: 'left',
           render: (text) => {
  const value = parseFloat(text);
  return isNaN(value) ? "-" : value.toFixed(2);
}
        },
        {
            title: '21/25',
            key: '21/25',
            dataIndex: '21/25',
            width: '70px',
            responsive: ['md'],
            align: 'left',
           render: (text) => {
  const value = parseFloat(text);
  return isNaN(value) ? "-" : value.toFixed(2);
}
        },
        {
            title: '26/30',
            key: '26/30',
            dataIndex: '26/30',
            width: '70px',
            responsive: ['md'],
            align: 'left',
           render: (text) => {
  const value = parseFloat(text);
  return isNaN(value) ? "-" : value.toFixed(2);
}
        },
        {
            title: '31/35',
            key: '31/35',
            dataIndex: '31/35',
            width: '70px',
            responsive: ['md'],
            align: 'left',
           render: (text) => {
  const value = parseFloat(text);
  return isNaN(value) ? "-" : value.toFixed(2);
}
        },
        {
            title: '36/40',
            key: '36/40',
            dataIndex: '36/40',
            width: '70px',
            responsive: ['md'],
            align: 'left',
           render: (text) => {
  const value = parseFloat(text);
  return isNaN(value) ? "-" : value.toFixed(2);
}
        },
        {
            title: '41/50',
            key: '41/50',
            dataIndex: '41/50',
            width: '70px',
            responsive: ['md'],
            align: 'left',
           render: (text) => {
  const value = parseFloat(text);
  return isNaN(value) ? "-" : value.toFixed(2);
}
        },
        {
            title: '51/60',
            key: '51/60',
            dataIndex: '51/60',
            width: '70px',
            responsive: ['md'],
            align: 'left',
           render: (text) => {
  const value = parseFloat(text);
  return isNaN(value) ? "-" : value.toFixed(2);
}
        },
        {
            title: '61/70',
            key: '61/70',
            dataIndex: '61/70',
            width: '70px',
            responsive: ['md'],
            align: 'left',
           render: (text) => {
  const value = parseFloat(text);
  return isNaN(value) ? "-" : value.toFixed(2);
}
        },
        {
            title: '71/90',
            key: '71/90',
            dataIndex: '71/90',
            width: '70px',
            responsive: ['md'],
            align: 'left',
           render: (text) => {
  const value = parseFloat(text);
  return isNaN(value) ? "-" : value.toFixed(2);
}
        },
        {
            title: '81/90',
            key: '81/90',
            dataIndex: '81/90',
            width: '70px',
            responsive: ['md'],
            align: 'left',
           render: (text) => {
  const value = parseFloat(text);
  return isNaN(value) ? "-" : value.toFixed(2);
}
        },
        {
            title: '91/110',
            key: '91/110',
            dataIndex: '91/110',
            width: '70px',
            responsive: ['md'],
            align: 'left',
           render: (text) => {
  const value = parseFloat(text);
  return isNaN(value) ? "-" : value.toFixed(2);
}
        },
        {
            title: '100/120',
            key: '110/200',
            dataIndex: '110/200',
            width: '70px',
            responsive: ['md'],
            align: 'left',
           render: (text) => {
  const value = parseFloat(text);
  return isNaN(value) ? "-" : value.toFixed(2);
}
        },
        {
            title: 'TOTAL',
            key: 'total',
            dataIndex: 'total',
            width: '70px',
            responsive: ['md'],
            align: 'left',
            render:(text) => parseFloat(text).toFixed(2)
        },
        {
            title: 'Yield %',
            key: 'yield',
            dataIndex: 'yield',
            width: '70px',
            responsive: ['md'],
            align: 'left',
        }
    ];

  //   const preprocessDataForExport = (data) => {
  //     return data.map(record => {
  //         // Validate and format date using moment
  //         const date = record.date && moment(record.date).isValid()
  //             ? moment(record.date).format('DD-MM-YYYY') 
  //             : '-'; 
  //         return { ...record, date };
  //     });
  // };



  const preprocessDataForExport = (data) => {
    return data.map(record => {
        // Format date without validation
        const date = record.date 
            ? moment(record.date).format('DD-MM-YYYY') 
            : '-'; 
        return { ...record, date };
    });
};
  
  

    const transformColumnsToExcelFormat = (columns) => {
        return columns.map(col => ({
            title: typeof col.title === 'string' ? col.title : 'Untitled',
            dataIndex: col.dataIndex || col.key,
            key: col.key
        }));
    };

    const exportExcel = () => {
        const preprocessedData = preprocessDataForExport(gradeData);

        const excel = new Excel();
        excel
            .addSheet('grading-analysis-report')
            .addColumns(transformColumnsToExcelFormat(gradeColumns))
            .addDataSource(preprocessedData, { str2num: true })
            .saveAs('grading-analysis-report.xlsx');
    };

    return (
        <div>
            <Card
                title={<span style={{ color: 'white' }}>Grading Analysis Report</span>}
                extra={<Button onClick={exportExcel}>Get Excel</Button>}
                style={{ textAlign: 'center' }}
                headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
            ></Card>
             <Form  form={form}>
              <Row gutter={24}>
             <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 6 }} lg={{ span: 6 }} xl={{ span: 6 }}>
            <Form.Item name="fromDate"
              label="Date Range"
              initialValue={undefined}
              rules={[
                {
                  required: true,
                  message: "select date range"
                },
              ]}>
              <RangePicker onChange={EstimatedETDDate} />
            </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: 6 }}>
            <Button type="primary" style={{ marginRight: '4px' }} disabled={disable} 
            onClick={handleSearch}
            >
              Get Report
            </Button>
            <Button style={{ marginLeft: '5px' }} type="primary" htmlType="submit" onClick={onReset}> Reset </Button>
          </Col>
          </Row>
             </Form>
             {showTable && (
            <Table
                className="gradingTable"
                size="small"
                rowKey="id"
                bordered
                dataSource={gradeData}
                columns={gradeColumns}
                scroll={{ x: true }}
                pagination={{ current: page, onChange: setPage }}
                summary={() => {
                  const totals = gradeColumns.reduce((acc, col) => {
                      const key = col.key;
                      if (key !== 'id' && key !== 'date' && key !== 'scode' && key !== 'count' && key !== 'yield') {
                          acc[key] = gradeData.reduce((sum, record) => sum + (record[key] || 0), 0);
                      }
                      return acc;
                  }, {});
          
                  return (
                      <Table.Summary.Row>
                          <Table.Summary.Cell index={0} colSpan={4}>Total</Table.Summary.Cell>
                          {gradeColumns.slice(4).map(col => (
                            <Table.Summary.Cell key={col.key} index={Number(col.key)}>
                                {(totals[col.key] || 0).toFixed(2)}
                              </Table.Summary.Cell>
                          ))}
                      </Table.Summary.Row>
                  );
              }}
            />
          )}
        </div>
    );
}

export default GradingAnalysisReport;
