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 { 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 form from 'antd/lib/form';
import moment from 'moment';

const StoreConsumptionSummaryReport = () => {
  const { RangePicker } = DatePicker;
    const [searchText, setSearchText] = useState('');
    const [searchedColumn, setSearchedColumn] = useState('');
    const searchInput = useRef(null);
    const [page, setPage] = useState(1);
    const service = new StockService();
    const [store, setStore] = useState([]);
    const { Option } = Select;
    const [form]=Form.useForm()
    const [disable, setDisable] = useState<boolean>(false);
    const [pagination, setPagination] = useState({
      current: 1,
      pageSize: 100,
  });
  



    const [itemSubDropDown, setItemSubDropDown] = useState<StockDto[]>([]);

    



    useEffect(() => {
        getStore();
        getItemSubDropForStockReport();
      }, []);

      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 getStore = () => {
        setDisable(true);

        const req = new stockDropdownData();
        if (form.getFieldValue('itemSubCategoryName') !== undefined) {
            req.itemSubCategoryId = form.getFieldValue('itemSubCategoryName');
        }
        if (form.getFieldValue('consumedDate') !== undefined) {
          req.fromDate = (form.getFieldValue('consumedDate')[0]).format('YYYY-MM-DD');
        }
        if (form.getFieldValue('consumedDate') !== undefined) {
          req.toDate = (form.getFieldValue('consumedDate')[1]).format('YYYY-MM-DD');
        }
        service.getStoreConsumptionSummary(req) 
            .then((res) => {
              setDisable(false);

                if (res.status) {
                    setStore(res.data);
                } else {
                    AlertMessages.getErrorMessage(res.internalMessage);
                    setStore([]);
                }
            })
            .catch((err) => {
                AlertMessages.getErrorMessage(err.message);
                setStore([]);
                setDisable(false);

            });
    };
    const onReset = () => {
      form.resetFields();
      getStore()

   
    };

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

  const handleReset = (clearFilters) => {
    clearFilters();
    setSearchText('');
  };
  const getColumnSearchProps = (dataIndex) => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <Card 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>
      </Card>
    ),
    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 handleTableChange = (pagination) => {
    setPagination(pagination);
};



  const excelcolumns = [
  
    {
        title: 'Item SubCategory',
        dataIndex: 'itemSubCategoryName',
    },
   
    {
        title: 'Quantity',
        dataIndex:'quantity',
    },
    {    title: 'Average Price',
        dataIndex: 'averagePrice',

    },
   
    {
        title: 'Amount',
        dataIndex: 'amount',
    }
    
    
  ];

  const exportExcel=()=>{
    const excel = new Excel();
          excel
            .addSheet('StoreConsumptionSummaryReport')
            .addColumns(excelcolumns)
            .addDataSource(store)
            .saveAs('StoreConsumptionSummaryReport.xlsx');
    }

    const stockColumns1: ColumnProps<any>[] = [
        {
          title: 'S No',
          key: 'id',
          responsive: ['md'],
          align: 'left',
          render: (_, __, index) => ((pagination.current - 1) * pagination.pageSize) + index + 1,
        },
        {
          title: 'Date',
          dataIndex: 'consumedDate',
          sorter: (a, b) => a.consumedDate?.localeCompare(b.consumedDate),
          sortDirections: ['descend', 'ascend'],
    
          render: (text, record) => {
            const consumedDate = moment(record.consumedDate);
            return record.consumedDate
            ? moment(record.consumedDate).format('DD-MM-YYYY') : '-'; // Check if date is valid
          },},
          
        {
            title: 'Item SubCategory',
            key: 'itemSubCategoryName',
            dataIndex: 'itemSubCategoryName',
            responsive: ['md'],
            align: 'left',
            ...getColumnSearchProps('itemSubCategoryName'),
            sorter: (a, b) => a.itemSubCategoryName?.localeCompare(b.itemSubCategoryName),
            sortDirections: ['descend', 'ascend'],
          },
         
        {
          title: 'Quantity',
          key: 'quantity',
          dataIndex: 'quantity',
          responsive: ['md'],
          align: 'left',
          ...getColumnSearchProps('quantity'),
          // sorter: (a, b) => a.quantity - b.quantity,
          // sortDirections: ['descend', 'ascend'],
          render: (text) => parseFloat(text).toFixed(2),

          
          
        },
        {
            title: 'Average Price',
            key: 'averagePrice',
            dataIndex: 'averagePrice',
            responsive: ['md'],
            align: 'left',
            ...getColumnSearchProps('averagePrice'),
            render: (text) => parseFloat(text).toFixed(2),
          },
        {
        title: 'Amount',
        key: 'amount',
        dataIndex: 'amount',
        responsive: ['md'],
        align: 'left',
        ...getColumnSearchProps('amount'),
        // sorter: (a, b) => a.amount - b.amount,
        // sortDirections: ['descend', 'ascend'],
        render: (text) => parseFloat(text).toLocaleString()

      },
        
      ];


  return (
    <div style={{ marginTop:'10px' }}>
    <Card
      size="small"
      title={<span style={{ color: 'white' }}>  Store Consumption Summary Report</span>}
      extra={<Button onClick={() => {exportExcel();}}>Get Excel</Button>}
      style={{ textAlign: 'center' }}
      headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
    >
<Form form={form}>
  <Row gutter={24}>
    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 7 }} lg={{ span: 7 }} xl={{ span: 7 }}>
                <Form.Item label=" Date" name="consumedDate" 
                // rules={[{ required: true, message: 'Shipment Date is required' }]}
                 >
                  <RangePicker format="DD-MM-YYYY"/>
                </Form.Item>
              </Col>
    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 6 }} xl={{ span: 9 }}>
        <Form.Item label="Item SubCategory" name='itemSubCategoryName'>
            <Select
                showSearch
                allowClear
                placeholder="Select Item SubCategory"
                filterOption={(input, option) =>
                    option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
            >
                {store.map(dropData => (
                    <Option key={dropData.itemSubCategoryId} value={dropData.itemSubCategoryId}>
                        {dropData.itemSubCategoryName}
                    </Option>
                ))}
            </Select>
        </Form.Item>
    </Col>
    <Col  >
            <Button type="primary" style={{ marginRight: '1px' }} disabled={disable} onClick={getStore}>Get Report</Button>
            <Button
                type="primary"
                onClick={onReset}
                style={{marginLeft:10}}
              >
                Reset
              </Button>
          </Col>
          </Row>
</Form>


    <Table
      columns={stockColumns1}
      dataSource={store}
      scroll={{ x: 'max-content' }}
      style={{ marginTop: '10px' }}
      pagination={{
        pageSize: pagination.pageSize,
        current: pagination.current,
        onChange: (page, pageSize) => handleTableChange({ current: page, pageSize }),
    }}
    onChange={handleTableChange}
    />
    </Card>
  </div>
  )
}


export default StoreConsumptionSummaryReport