import React, { useEffect, useRef, useState } from 'react';
import {  Divider, Table, Popconfirm, Card, Tooltip, Switch,Input,Button,Tag,Row, Col, Drawer, Form, Select,DatePicker, Typography } from 'antd';

import {SaleOrderService} from '@gtpl/shared-services/sale-management';
import { SaleOrderDropDownDto } from '@gtpl/shared-models/sale-management';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { PoDropDownDto, PoReportDto, StockDto } from '@gtpl/shared-models/procurement-management';
import { VendorDropDownDto } from '@gtpl/shared-models/masters';
import moment from 'moment';
import { StockService } from '@gtpl/shared-services/procurement';
import { ColumnProps } from 'antd/lib/table';


export interface SoPackingStatusReportProps {}

export function SoPackingStatusReport(
    props: SoPackingStatusReportProps
  ) {
    const searchInput = useRef(null);
    const [form] = Form.useForm();
    const [poNumbers, setPoNumbers] = useState<PoDropDownDto[]>([]);
    const [page, setPage] = React.useState(1);
    const [searchText, setSearchText] = useState(''); 
    const [searchedColumn, setSearchedColumn] = useState('');
    const [saleOrderData, setSaleOrderData] = useState<SaleOrderDropDownDto[]>([]);
    const [poReportData, setPoReportData] = useState<PoReportDto[]>([])
    const [vendorData, setVendorData] = useState<VendorDropDownDto[]>([]);
    const [subCategories, setSubCategories] = useState<string[]>([]);
    const [brandsData, setBrandsData] = useState<string[]>([]);
    const [sizeData, setSizeData] = useState<string[]>([]);
    const [variantsData, setVariantsData] = useState<string[]>([]);
    const [filterStockData, setFilterStockData] = useState<StockDto[]>([]);
    const [stockData, setStockData] = useState<StockDto[]>([]);
    const saleOrderService = new SaleOrderService;
    const service = new StockService;
    const { Option } = Select;


    useEffect(() => {
        getSaleOrderData(); 
        getAllStock();
  
      }, [])

      useEffect(() => {
        getFiltersDropdownData(filterStockData);
      }, [filterStockData])


      const getSaleOrderData = () => {
        saleOrderService.getSaleOrdersDropDownList().then((res) => {
          if (res.status) {
            console.log(res.data);
            setSaleOrderData(res.data);
          } else {
            if (res.intlCode) {
              AlertMessages.getErrorMessage(res.internalMessage);
            } else {
              AlertMessages.getErrorMessage(res.internalMessage);
            }
            setSaleOrderData([]);
          }
        }).catch((err) => {
          AlertMessages.getErrorMessage(err.message);
          setSaleOrderData([]);
        });
      }
      const getFiltersDropdownData = (stockData) => {
        let brandData: any[] = [];
        let variantData: any[] = [];
        let itemSubCategoriesData: any[] = [];
        let sizesData: any[] = [];
        stockData.forEach(element => {
          if (element.variantName && (!brandData.includes(element.brandName))) {
            brandData.push(element.brandName)
          }
          if (element.variantName && (!variantData.includes(element.variantName))) {
            variantData.push(element.variantName)
          }
          if (element.itemSubCategoryName && (!itemSubCategoriesData.includes(element.itemSubCategoryName))) {
            itemSubCategoriesData.push(element.itemSubCategoryName)
          }
          if (element.sizeName && (!sizesData.includes(element.sizeName))) {
            sizesData.push(element.sizeName)
          }
    
        });
        setBrandsData(brandData)
        setVariantsData(variantData)
        setSubCategories(itemSubCategoriesData)
        setSizeData(sizesData)
      }
      const getAllStock = () => {
        service.getAllStockData().then(res => {
          if (res.data) {
            setStockData(res.data);
            setFilterStockData(res.data)
          } else {
            if (res.intlCode) {
              setStockData([]);
              setFilterStockData([]);
              AlertMessages.getErrorMessage(res.internalMessage);
            } else {
              AlertMessages.getErrorMessage(res.internalMessage);
            }
          }
        }).catch(err => {
          AlertMessages.getErrorMessage(err.message);
          setStockData([]);
          setFilterStockData([]);
        })
      }
    
      function unique(data, key){
        return [
            ...new Map(
              data.map(x=> [key(x),x])
            ).values()
        ]
      }
      const handleSoNumber=(value, item)=>{
        const newPoReportData = poReportData.filter(po =>
          po.soNumber == value
        )
        setPoReportData(newPoReportData);
        setPoNumbers(JSON.parse(JSON.stringify(unique(newPoReportData, it => it.purchaseOrderId))));
        setVendorData(JSON.parse(JSON.stringify(unique(newPoReportData, it => it.vendorName))));
         
      }

      const columnsSkelton1: ColumnProps<any>[] = [

        {
          title: 'S No',
          key: 'sno',
          width: '60px',
          render: (text, object, index) => (page - 1) * 10 + (index + 1)
        },

        {
          title: 'Item Sub category',
          dataIndex: 'itemSubCategoryName',
          sorter: (a, b) => a.itemSubCategoryName.localeCompare(b.itemSubCategoryName),
          sortDirections: ['descend', 'ascend'],
        
        },

        {
          title: 'Item',
          dataIndex: 'itemName',
          sorter: (a, b) => a.itemName.localeCompare(b.itemName),
          sortDirections: ['descend', 'ascend'],
          // ...getColumnSearchProps('itemName')
        },
        {
          title: 'Required Quantity',
          dataIndex: 'requiredQuantity',
          sorter: (a, b) => a.itemSubCategoryName.localeCompare(b.itemSubCategoryName),
          sortDirections: ['descend', 'ascend'],
        
        },
    
        {
          title: 'Po Quantity',
          dataIndex: 'poQuantity',
          sorter: (a, b) => a.itemSubCategoryName.localeCompare(b.itemSubCategoryName),
          sortDirections: ['descend', 'ascend'],
        
        },
        {
          title: 'Recieved Quantity',
          dataIndex: 'recievedQuantity',
          sorter: (a, b) => a.itemSubCategoryName.localeCompare(b.itemSubCategoryName),
          sortDirections: ['descend', 'ascend'],
        
        },
        {
          title: 'Assigned Quantity',
          dataIndex: 'assignedQuantity',
          sorter: (a, b) => a.itemSubCategoryName.localeCompare(b.itemSubCategoryName),
          sortDirections: ['descend', 'ascend'],
        
        },
        {
          title: 'Issued Quantity',
          dataIndex: 'issueQuantity',
          sorter: (a, b) => a.itemSubCategoryName.localeCompare(b.itemSubCategoryName),
          sortDirections: ['descend', 'ascend'],
        
        },
        {
          title: 'FG Quantity',
          dataIndex: 'FGQuantity',
          sorter: (a, b) => a.itemSubCategoryName.localeCompare(b.itemSubCategoryName),
          sortDirections: ['descend', 'ascend'],
        
        },
        {
          title: 'balance Quantity',
          dataIndex: 'BalanceQuantity',
          sorter: (a, b) => a.itemSubCategoryName.localeCompare(b.itemSubCategoryName),
          sortDirections: ['descend', 'ascend'],
        
        },


      ]


      


      return(
          <Card title={<span style={{ color: 'white' }}>So Packing Status Report</span>}
          style={{ textAlign: 'center' }} headStyle={{ backgroundColor: '#69c0ff', border: 0 }}>
          <br></br>
          <Form form={form} layout={'vertical'} style={{ padding: '0px' }}  >
            <Row gutter={[24, 24]}>
                 
              <Col>
              <Form.Item
                name="saleOrderId"
                label="Sale Order No"
                rules={[
                  {
                    required: false, message: 'Select Sale Order',
                  },
                ]}
              >
                <Select
                  placeholder="Select Sale Order"
                  onChange={handleSoNumber}
                  allowClear
                >
                  {saleOrderData.map(saleOrderDropDown => {
                    return <Option value={saleOrderDropDown.saleOrderId}>{saleOrderDropDown.saleOrderNumber}</Option>
                  })}
                </Select>
              </Form.Item>
              </Col>
              <Col span={5}>
                    <Form.Item label="Item Sub category"
                      name={'itemSubcategory'}
                    >
                      <Select
                        placeholder="Select Sub Category"
                        allowClear
                        showSearch
                      // disabled={updateDisableField}

                      >
                        {subCategories.map(itemsubcategory => {
                          return <Option label={'itemSubCategory'} key={itemsubcategory} value={itemsubcategory}>{itemsubcategory}</Option>
                        })}
                      </Select>
                    </Form.Item>

                  </Col>
              <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 5 }}>
              <Form.Item name="FromDate" label="From Date" initialValue={moment()}>
                <DatePicker style={{ width: '100%' }} format="YYYY-MM-DD"
                  showToday={true} />
              </Form.Item>
            </Col>
            
            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 5 }}>
              <Form.Item name="ToDate" label="To Date" initialValue={moment()}>
                <DatePicker style={{ width: '100%' }} format="YYYY-MM-DD"
                  showToday={true} />
              </Form.Item>

            </Col>
            
            <Col span={4} style={{ paddingTop: '33px' }}>
                    <Form.Item >
                      <Button type='primary' >Get Details</Button>

                      <Button htmlType="button" >
                        Reset
                      </Button>

                    </Form.Item>
                  </Col>

                </Row>
                </Form>
                <Table
                rowKey={record => record.stockId}
                columns={columnsSkelton1}
                // dataSource={stockData.filter(res => res.saleOrderId != 0)}
                pagination={{
                  onChange(current) {
                    setPage(current);
                  }
                }}
                // onChange={onChange}
                scroll={{ x: true }}
                size="small"
                bordered />
          </Card>

          
      );
}
export default SoPackingStatusReport;