import { Button, Card, Col, Form, Input, Row, Select, } from 'antd';
import Table, { ColumnProps } from 'antd/lib/table';
import React, { useEffect, useRef, useState } from 'react';
import { SearchOutlined } from '@ant-design/icons';
import Highlighter from 'react-highlight-words';
import { CommonResponse } from '@gtpl/shared-models/production-management';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { StockService } from '@gtpl/shared-services/procurement';
import { Excel } from 'antd-table-saveas-excel';
import { StockDto } from '@gtpl/shared-models/procurement-management';
import { stockDropdownData } from '@gtpl/shared-models/common-models';
import { PlantsDropDown } from '@gtpl/shared-models/masters';
import { UnitcodeService } from '@gtpl/shared-services/masters';

export function StockSummaryReport() {
  const [searchText, setSearchText] = useState('');
  const [searchedColumn, setSearchedColumn] = useState('');
  const searchInput = useRef(null);
  const { Option } = Select;

  const [disable, setDisable] = useState<boolean>(false);
  const req = new stockDropdownData();

  const [page, setPage] = useState(1);
  const service = new StockService();
  const [stock, setStock] = useState([]);
  const [itemSubDropDown, setItemSubDropDown] = useState<StockDto[]>([]);
  const [form] = Form.useForm()
  const [pageSize, setPageSize] = useState(100);
  const [plantData, setPlantData] = useState<PlantsDropDown[]>([]);
  const unitsService = new UnitcodeService();



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

  const getItemSubDropForStockReport = () => {
    service.getItemSubDropForStockReport({ unitId: Number(localStorage.getItem('unit_id')) }).then((res) => {
      if (res.status) {
        setItemSubDropDown(res.data);
      } else {
        setItemSubDropDown([]);
      }
    }).catch(err => {
      AlertMessages.getErrorMessage(err.message);
      setItemSubDropDown([]);
    })
  }

  const getAllPlants = () => {
    unitsService.getAllMainPlants().then((res) => {
      if (res.status) {
        setPlantData(res.data);
      } else {
        setPlantData([]);
      }
    }).catch(err => {
      AlertMessages.getErrorMessage(err.message);
      setPlantData([]);
    })
  }

  const getActiveStockSummary = () => {
    setDisable(true);
    const req = new stockDropdownData();
    if (form.getFieldValue('itemSubCategoryName') !== undefined) {
      req.itemSubCategoryId = form.getFieldValue('itemSubCategoryName');
    }
    
    if (Number(localStorage.getItem('unit_id')) != 5) {
      req.unitId = Number(localStorage.getItem('unit_id'));
    }

    service.getAllSubCategoryWiseStockSummaryReport(req)
      .then((res) => {
        setDisable(false);
        if (res.status) {
          setStock(res.data);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
          setStock([]);
        }
      })
      .catch((err) => {
        AlertMessages.getErrorMessage(err.message);
        setStock([]);
        setDisable(false);
      });
  };

  const handleSearch = (selectedKeys, confirm, dataIndex) => {
    confirm();
    setSearchText(selectedKeys[0]);
    setSearchedColumn(dataIndex);
  };

  const handleReset = (clearFilters) => {
    clearFilters();
    setSearchText('');
  };

  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={() => 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 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 ? text.toString() : ''}
        />
      ) : (
        text
      ),
  });

  const excelcolumns = [
    {
      title: 'S No',
      key: 'sNo',
      dataIndex: 'sNo',
      render: (text, object, index) => (page - 1) * 10 + (index + 1),
    },
    {
      title: 'Item SubCategory',
      dataIndex: 'itemSubCategoryName',
    },
    {
      title: 'Quantity',
      dataIndex: 'quantity',
      render: (text) => (text !== undefined && text !== '' ? parseFloat(text).toFixed(2) : undefined)

    },
    {
      title: 'Price',
      dataIndex: 'price',
    },
    {
      title: 'Amount',
      dataIndex: 'amount',
      render: (text) => parseFloat(text).toFixed(2),

    }
  ];

  const exportExcel = () => {
    
    let totalValue = 0;
    stock.forEach(({amount})=>{
      totalValue += parseFloat(amount) ||0
    });
    const totalRow: any = {
      sNo: undefined,
      itemSubCategoryName: 'Total',
      quantity: undefined,
      price: undefined,
      amount: totalValue.toFixed(2),
      
    };
    const exportData = [...stock, totalRow];
    const excel = new Excel();
    excel
      .addSheet('subCategorywiseSummaryReport')
      .addColumns(excelcolumns)
      .addDataSource(exportData)
      .saveAs('subCategorywiseSummaryReport.xlsx');
  }

  const stockColumns: ColumnProps<any>[] = [
    {
      title: 'S No',
      key: 'id',
      width: '70px',
      responsive: ['md'],
      align: 'left',
      render: (text, object, index) => (page - 1) * 10 + (index + 1),
    },
    {
      title: 'Item SubCategory',
      key: 'itemSubCategoryName',
      dataIndex: 'itemSubCategoryName',
      width: 100,
      responsive: ['md'],
      align: 'left',
      ...getColumnSearchProps('itemSubCategoryName'),
      sorter: (a, b) => a.itemSubCategoryName?.localeCompare(b.itemSubCategoryName),
      sortDirections: ['descend', 'ascend'],
    },
    {
      title: 'Quantity',
      key: 'quantity',
      dataIndex: 'quantity',
      width: 100,
      responsive: ['md'],
      align: 'left',
      ...getColumnSearchProps('quantity'),
      sorter: (a, b) => a.quantity?.localeCompare(b.quantity),
      sortDirections: ['descend', 'ascend'],
      render: (text, record) => {
        const qty = Number(record.quantity); // Convert to a number
        return !isNaN(qty) // Check if qty is a valid number
            ? qty % 1 === 0 // Check if qty is a whole number
                ? qty.toFixed(0) // No decimal places
                : qty.toFixed(2) // One decimal place
            : '-';
    }
      

    },
    {
      title: 'Price',
      key: 'price',
      dataIndex: 'price',
      width: 100,
      responsive: ['md'],
      align: 'left',
      ...getColumnSearchProps('price'),
      sorter: (a, b) => a.price?.localeCompare(b.price),
      sortDirections: ['descend', 'ascend'],
      render: (text) => parseFloat(text).toFixed(2),

    },
    {
      title: 'Amount',
      key: 'value',
      dataIndex: 'amount',
      width: 100,
      responsive: ['md'],
      align: 'left',
      ...getColumnSearchProps('amount'),
      // render: (text) => parseFloat(text).toFixed(2),
      sorter: (a, b) => a.amount?.localeCompare(b.amount),
      sortDirections: ['descend', 'ascend'],
      render: (text, record) => {
        const qty = Number(record.amount); // Convert to a number
        return !isNaN(qty) // Check if qty is a valid number
            ? qty % 1 === 0 // Check if qty is a whole number
                ? qty.toFixed(0) // No decimal places
                : qty.toFixed(2) // One decimal place
            : '-';
    }

    },
  ];

  const handleFormReset = () => {
    form.resetFields(); 
    getActiveStockSummary(); 
    if (Number(localStorage.getItem('unit_id')) != 5) {
      form.setFieldsValue({ unitId: Number(localStorage.getItem('unit_id')) })
    }
  }

  return (
    <div>
      <Card
        size="small"
        title={<span style={{ color: 'white' }}>Sub Category Wise Summary Report</span>}
        extra={<Button onClick={() => { exportExcel(); }}>Get Excel</Button>}
        style={{ textAlign: 'center' }}
        headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
      >
        <Form form={form} layout='vertical'>
        <Row gutter={24}>
        <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 6 }} lg={{ span: 6 }} xl={{ span: 6}}>
            <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
                disabled={Number(localStorage.getItem('unit_id')) != 5 ? true : false}
                style={{ width: '100%' }}
              >
                {plantData.map(dropData => {
                  return <Option value={dropData.plantId}>{dropData.plantName}</Option>
                })}
              </Select>
            </Form.Item>

          </Col>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 6 }} xl={{ span: 6 }}>
            <Form.Item label="Item SubCategory"
              name='itemSubCategoryName'
            >
              <Select showSearch
                allowClear
                placeholder="Select Item SubCategory"
                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }>
                {itemSubDropDown === undefined ? '' : itemSubDropDown.map(dropData => {
                  return <Option key={dropData.itemSubCategoryId} value={dropData.itemSubCategoryId}>{dropData.itemSubCategoryName}</Option>
                })}
              </Select>
            </Form.Item>
          </Col>

          <Col style={{marginTop:28}}>
            <Button type="primary" style={{ marginRight: '1px' }} disabled={disable} onClick={getActiveStockSummary}>Get Report</Button>
            <Button type="primary" style={{ marginLeft: '10px' }} onClick={handleFormReset}>Reset</Button>
          </Col>
          </Row>
        </Form>
      
      </Card>
      <Table
       rowKey={record => record.itemSubCategoryId}
        columns={stockColumns}
        dataSource={stock}
        scroll={{ x: true }}
        pagination={{pageSize:100}}
        summary={(pageData) => {
                    let totalAmount = 0;
                  
                    pageData.forEach(({ amount }) => {
                        totalAmount += parseFloat(amount) || 0;
                      });
                  
                    return (
                      <Table.Summary.Row>
                        <Table.Summary.Cell index={3} colSpan={4}>
                          Total
                        </Table.Summary.Cell>
                        <Table.Summary.Cell index={4}>
                          {totalAmount.toFixed(2)}
                        </Table.Summary.Cell>
                      </Table.Summary.Row>
                    );
                  }} 
      />
    </div>
  );
}

export default StockSummaryReport;
