import React, { useEffect, useRef, useState } from 'react';
import { ColumnProps } from 'antd/lib/table';
import { Divider, Table, Popconfirm, Card, Tooltip, Switch, Input, Button, Tag, Row, Col, Drawer, Modal, Tabs, Empty } from 'antd';
import { Link, Redirect } from 'react-router-dom';
import { CheckCircleOutlined, CloseCircleOutlined, RightSquareOutlined, DoubleRightOutlined, EyeOutlined, EditOutlined, SearchOutlined, PrinterOutlined } from '@ant-design/icons';

import { CodeListMainService } from '@gtpl/shared-services/planning';
import { CodeListMainDto } from '@gtpl/shared-models/planning'
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { CodeListMainForm } from '@gtpl/pages/planning/planning-components/code-list-main-form'
import Highlighter from 'react-highlight-words';
import './code-list-main-grid.css';
import CodeListPrint from './code-list-print';
import CodeListPrintbeforeSubJob from './code-list-print-two';
import { any } from 'prop-types';
import { EmployeeRolesEnum, UnitRequest } from '@gtpl/shared-models/common-models';
import { ArrayMaxSize } from 'class-validator';
import { saleOrder, SaleOrderService } from '@gtpl/shared-services/sale-management';
import { UnitsOfWeightInput } from '@gtpl/shared-models/sale-management';

/* eslint-disable-next-line */
export interface CodeListAllocationGridProps { }

export function CodeListAllocationGrid(
  props: CodeListAllocationGridProps
) {
  
  const [codeListData, setCodeListData] = useState<any[]>([]);
  const [codeListItemData, setCodeListItemData] = useState<any[]>([]);
  const [saleOrderItemDetails, setSaleOrderItemDetails] = useState<any[]>([]);
  const [selectedCodeListData, setSelectedCodeListData] = useState<any>(undefined);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const searchInput = useRef(null);
  const [searchText, setSearchText] = useState('');
  const [searchedColumn, setSearchedColumn] = useState('');
  const [isModalVisible, setIsModalVisible] = useState<boolean>(false);
  const [page, setPage] = React.useState(1);
  const [selectedInformation, setSelectedInformation] = useState<CodeListMainDto>();
  const [codeListMainId, setCodeIdListState] = useState<number>(null);
  const [defaultTab, setDefaultTab] = useState<string>("1");
  const [object, setObject] = useState<number>(0);

  const [modal, setModal] = useState('')
  const codeListService = new CodeListMainService();
  const saleOrderService = new SaleOrderService();

  const { TabPane } = Tabs;

  useEffect(() => {
    getCodeListsData();
  }, []);

  const getCodeListsData = () => {
    const req = new UnitRequest(Number(localStorage.getItem('unit_id')))
    codeListService.getAllCodeListsTabView(req).then(res => {
      if (res.status) {
        console.log(res)
        setCodeListData(res.data);
      } else {
        if (res.intlCode) {
          setCodeListData([]);
          AlertMessages.getErrorMessage(res.internalMessage);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
      }
    }).catch(err => {
      setCodeListData([]);
      AlertMessages.getErrorMessage(err.message);
    })
  }

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

  function handleReset(clearFilters) {
    clearFilters();
    setSearchText('');
  };

  const getColumnSearchProps = (dataIndex: string) => ({
    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

  });


  const openFormWithData = (viewData: CodeListMainDto) => {
    console.log('open form')
    setDrawerVisible(true);
    setSelectedCodeListData(viewData);
  }
  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const displayModel = (data: CodeListMainDto, modalName) => {
    setSelectedInformation(data);
    setIsModalVisible(true);
    setModal(modalName)

  };



  const detail = (data: CodeListMainDto) => {
    setSelectedInformation(data);
    setIsModalVisible(true);
  };

  const closeDrawer = () => {
    setDrawerVisible(false);
  }
  const setCodeListId = (rowdata) => {
    setCodeIdListState(rowdata.codeListMainId)
  }


  /**
  * 
  * @param productData 
  */
  // const deleteProduct = (codeListData:CodeListMainDto) => {
  //   codeListData.isActive=codeListData.isActive?false:true;
  //   codeListService.activateOrDeactivateProduct(codeListData).then(res => { console.log(res);
  //     if (res.status) {
  //       getCodeListsData();
  //       AlertMessages.getSuccessMessage('Success'); 
  //     } else {
  //       if (res.intlCode) {
  //         AlertMessages.getErrorMessage(res.internalMessage);
  //       } else {
  //         AlertMessages.getErrorMessage(res.internalMessage);
  //       }
  //     }
  //   }).catch(err => {
  //     AlertMessages.getErrorMessage(err.message);
  //   })
  // }

  /**
    * 
    * @param variantData 
    */
  // const updateCodeList = (codeListData: CodeListMainDto) => {
  //   codeListService.updateCodeList(codeListData).then(res => { console.log(res);
  //     if (res.status) {
  //       AlertMessages.getSuccessMessage('Updated Successfully');
  //       getCodeListsData();
  //       setDrawerVisible(false);
  //     } else {
  //       if (res.intlCode) {
  //         AlertMessages.getErrorMessage(res.internalMessage);
  //       } else {
  //         AlertMessages.getErrorMessage(res.internalMessage);
  //       }
  //     }
  //   }).catch(err => {
  //     AlertMessages.getErrorMessage(err.message);
  //   })
  // }
  const codeListItemTable = (record) => {

    return (record.saleOrderId) ? <>
       <Card style={{ overflow: 'auto', overflowY: 'hidden', backgroundColor: 'white', height: 20, margin: 1 ,textAlign:'center'}} title={<span></span>}></Card>
     <Table
      rowKey={record => record.saleOrderId}
      columns={codeListItemTableSkelton1}
      dataSource={codeListItemData}
      className="components-table-nested"
      // pagination={false}
      // scroll={{ x: true }}
      bordered /> </> : <Empty />
  }

  const getCodeListItemData = (id) => {
    codeListService.getCodeListItemData({codeListMainId:id}).then(res => {
      if (res.status) {
        console.log(res)
        setCodeListItemData(res.data);
      } else {
        if (res.intlCode) {
          setCodeListItemData([]);
          AlertMessages.getErrorMessage(res.internalMessage);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
      }
    }).catch(err => {
      setCodeListItemData([]);
      AlertMessages.getErrorMessage(err.message);
    })
  }

  const getSaleOrderItemsBySaleOrderId = (id,poNo) => {
    saleOrderService.getAllSaleOrderItemDetails(new saleOrder(id,0,poNo) ).then(res => {
      if (res.status) {
        console.log(res)
        setSaleOrderItemDetails(res.data);
      } else {
        if (res.intlCode) {
          setSaleOrderItemDetails([]);
          AlertMessages.getErrorMessage(res.internalMessage);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
      }
    }).catch(err => {
      setSaleOrderItemDetails([]);
      AlertMessages.getErrorMessage(err.message);
    })
  }

  

  const saleOrderItemDetailsTable = (record) => {
    return (record.saleOrderId) ? <>
       <Card style={{ overflow: 'auto', overflowY: 'hidden', backgroundColor: 'white', height: 20, margin: 1 ,textAlign:'center'}} title={<span></span>}></Card>
     <Table
      rowKey={record => record.saleOrderId}
      columns={saleOrderItemTableSkelton1}
      dataSource={saleOrderItemDetails}
      className="components-table-nested"
      // pagination={false}
      // scroll={{ x: true }}
      bordered /> </> : <Empty />
  }

  const setObjectValues = (rowData: any) => {
    console.log(rowData)
    setObject(rowData.saleOrderId);
  }

  const saleOrderItemTableSkelton1: ColumnProps<any>[] = [
    {
      title: 'S No',
      key: 'sno',
      width: '70px',
      responsive: ['sm'],
      render: (text, object, index) => (page - 1) * 10 + (index + 1)
    },
    {
      title:'Job Type',
      dataIndex:'jobType'
    },
    {
      title: 'Brand',
      dataIndex: 'brand',
      align: 'left',
      fixed: 'left',
      
    },
    {
      title: 'Short Code',
      dataIndex: 'shortCode',

      align: 'left',
      render: (text, data, index) => {
        console.log(text, data, index)
        return <span>{`${text}`}</span>
      }
    },

    {
      title: 'Pack Type',
      dataIndex: 'pouches',

      align: 'left',
      render: (text, data, index) => {
        const uomData = UnitsOfWeightInput.find(uom => uom.value == data.uomId);
        console.log(text, data, index)
        return <span>{`${data.pouches}  *  ${Number(Number(data.pouchWeight)?.toFixed(2))} ${uomData.name}`}</span>
      }
    },

    {
      title: 'Category',
      dataIndex: 'category',
      align: 'center',
    },
    {
      title: 'Variety',
      dataIndex: 'variety',
      align: 'center',
      render: (text, data, index) => {
        console.log(text, data, index)
        return <span>{text ? text : 'N/A'}</span>
      }
    },

    {
      title: 'No of Cases',
      dataIndex: 'cases',

      align: 'left',
    },
    {
      title: 'Job cases',
      dataIndex: 'jobCases',

      align: 'left',
    },
    {
      title: 'Style Weighment',
      dataIndex: 'styleWeighment',

      align: 'left',
    },
   
  ]
  const codeListItemTableSkelton1: ColumnProps<any>[] = [
    {
      title: 'S No',
      key: 'sno',
      width: '70px',
      responsive: ['sm'],
      render: (text, object, index) => (page - 1) * 10 + (index + 1)
    },
    {
      title: 'SO Item',
      dataIndex: 'soItem',
      // responsive: ['lg'],
      sorter: (a, b) => a.soItem?.localeCompare(b.soItem),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('soItem')
    },
    {
      title: 'Code',
      dataIndex: 'code',
      // responsive: ['lg'],
      sorter: (a, b) => a.code?.localeCompare(b.code),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('code')
    },

    {
      title: 'Tracebility COde',
      dataIndex: 'traceabilityCode',
      // responsive: ['lg'],
      sorter: (a, b) => a.traceabilityCode?.localeCompare(b.traceabilityCode),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('traceabilityCode')
    },
    {
      title: 'Production Date',
      dataIndex: 'productionDate',
      // responsive: ['lg'],
      sorter: (a, b) => a.productionDate?.localeCompare(b.productionDate),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('productionDate')
    },
    {
      title: 'Best before Date',
      dataIndex: 'bestBeforeDate',
      // responsive: ['lg'],
      sorter: (a, b) => a.bestBeforeDate?.localeCompare(b.bestBeforeDate),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('bestBeforeDate')
    },
    {
      title: 'Cartons',
      dataIndex: 'cartons',
      // responsive: ['lg'],
      sorter: (a, b) => a.cartons?.localeCompare(b.cartons),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('cartons')
    },
  ]
  const columnsSkelton1: ColumnProps<any>[] = [
    {
      title: 'S No',
      key: 'sno',
      width: '70px',
      responsive: ['sm'],
      render: (text, object, index) => (page - 1) * 10 + (index + 1)
    },
    {
      title: 'SO Number',
      dataIndex: 'poNumber',
      // responsive: ['lg'],
      sorter: (a, b) => a.poNumber?.localeCompare(b.poNumber),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('poNumber'),
      render: (text, object, index) => {
        return object.jobType ? (text + " (" + object.jobType + ")") : (text)
      }
    },
    {
      title: 'Country',
      dataIndex: 'countryName',
      // responsive: ['lg'],
      sorter: (a, b) => a.countryName?.localeCompare(b.countryName),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('countryName')
    },
    {
      title: 'Buyer',
      dataIndex: 'endCustomerName',
      // responsive: ['lg'],
      sorter: (a, b) => a.endCustomerName?.localeCompare(b.endCustomerName),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('endCustomerName')
    },
    {
      title: 'Brand',
      dataIndex: 'brandName',
      // responsive: ['lg'],
      sorter: (a, b) => a.brandName?.localeCompare(b.brandName),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('brandName')
    },

    {
      title: 'Total Cartons',
      dataIndex: 'totalCartons',
      // responsive: ['lg'],
      sorter: (a, b) => a.totalCartons - b.totalCartons,
      sortDirections: ['descend', 'ascend'],
      // ...getColumnSearchProps('productCode')
    },

    {
      title: `Action`,
      dataIndex: 'action',
      render: (text, rowData) => (
        <span>
         <Tooltip placement="top" title='Allocate Code' > <DoubleRightOutlined className={'editSamplTypeIcon'} type="Allocate Codes"
                onClick={() => {
                    setObjectValues(rowData);
                } }
                style={{ color: '#1890ff', fontSize: '14px' }} /></Tooltip>
        </span>
      )
    }
  ]

  const columnsSkelton2: ColumnProps<any>[] = [
    {
      title: 'S No',
      key: 'sno',
      width: '70px',
      responsive: ['sm'],
      render: (text, object, index) => (page - 1) * 10 + (index + 1)
    },
    {
      title: 'SO Number',
      dataIndex: 'poNumber',
      // responsive: ['lg'],
      sorter: (a, b) => a.poNumber?.localeCompare(b.poNumber),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('poNumber'),
      render: (text, object, index) => {
        return object.jobType ? (text + " (" + object.jobType + ")") : (text)
      }
    },
    {
      title: 'Country',
      dataIndex: 'countryName',
      // responsive: ['lg'],
      sorter: (a, b) => a.countryName?.localeCompare(b.countryName),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('countryName')
    },
    {
      title: 'Buyer',
      dataIndex: 'endCustomerName',
      // responsive: ['lg'],
      sorter: (a, b) => a.endCustomerName?.localeCompare(b.endCustomerName),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('endCustomerName')
    },
    {
      title: 'Brand',
      dataIndex: 'brandName',
      // responsive: ['lg'],
      sorter: (a, b) => a.brandName?.localeCompare(b.brandName),
      sortDirections: ['descend', 'ascend'],
      ...getColumnSearchProps('brandName')
    },

    {
      title: 'Total Cartons',
      dataIndex: 'totalCartons',
      // responsive: ['lg'],
      sorter: (a, b) => a.totalCartons - b.totalCartons,
      sortDirections: ['descend', 'ascend'],
      // ...getColumnSearchProps('productCode')
    },

    {
      title: `Action`,
      dataIndex: 'action',
      render: (text, rowData) => (
        <span>
          {
                  ((JSON.parse(localStorage.getItem('role'))) === EmployeeRolesEnum.ADMIN || (JSON.parse(localStorage.getItem('role'))) === EmployeeRolesEnum.QAQC_PERSON)?
                  <>
          <EditOutlined className={'editSamplTypeIcon'} type="edit"
            onClick={() => {
              openFormWithData(rowData);
            }}
            style={{ color: '#1890ff', fontSize: '14px' }}
          />
          </>:""}
          <Divider type='vertical' />
          <Tooltip placement="top" title='Before Subjob'>
            <PrinterOutlined className={'editSamplTypeIcon'} type="edit"
              onClick={() => {
                displayModel(rowData, 'printone')
              }}
              style={{ color: '#1890ff', fontSize: '14px' }}
            />
          </Tooltip>
         {Number(rowData.count) > 1 ? <> <Divider type='vertical' />
          <Tooltip placement="top" title='After SubJob'>
            <PrinterOutlined className={'editSamplTypeIcon'} type="edit"
              onClick={() => {
                displayModel(rowData, 'printtwo')

              }}
              style={{ color: 'green', fontSize: '14px' }}
            />
          </Tooltip> </> :<></>}
        </span>
      )
    }
  ]
//   if (key === "1") {
//     console.log('1')
//     setDefaultTab("1")
//     return [...columnsSkelton,...actionColumn]

//   }
//   else if (key === "2") {
//     console.log('2')
//     setDefaultTab("2")
//     return [...columnsSkelton]

//   }
// }
 
const onChange = (pagination, filters, sorter, extra) => {
  // console.log('params', pagination, filters, sorter, extra);
}

  

  return (
    <>
    {(object) ? <Redirect to={{ pathname: "/code-list-main-form", state: {saleOrderId: object} }} /> : null}
    <Card
      title={<span style={{ color: 'white' }}>Code List Allocation</span>}
      style={{ textAlign: 'center' }}
      headStyle={{ backgroundColor: '#69c0ff', border: 0 }}
    >
      <div>
          <Row justify='end' >
            <PrinterOutlined className={'editSamplTypeIcon'} type="edit"
              style={{ color: '#1890ff', fontSize: '14px' }}
            />
            <p style={{paddingTop : '4px'}}> -- Print before subjob data</p>
            <Divider type='vertical' />
            <PrinterOutlined className={'editSamplTypeIcon'} type="edit"
              style={{ color: 'green', fontSize: '14px' }}
            />
            <p style={{paddingTop : '4px'}} > -- Print after subjob data</p>
          </Row>
          <br></br>
          <Tabs key={defaultTab} type={'card'} tabPosition={'top'} defaultActiveKey={defaultTab}>
            <TabPane
              key="1"
              tab={<span style={{ color: "#f5222d" }} >Open: {codeListData.filter((rs) => rs.coItemCount != rs.soItemCount).length}</span>}
            >
              
                <Table
                  rowKey={record => record.saleOrderId}
                  columns={codeListData.length > 0 ? columnsSkelton1: []}
                  dataSource={codeListData.filter((rs) => rs.coItemCount != rs.soItemCount)}
                  expandable={{
                    expandedRowRender: (record) => saleOrderItemDetailsTable(record),
                    onExpand(expanded, record) {
                      getSaleOrderItemsBySaleOrderId(record.saleOrderId,record.poNumber);
                    },
                    rowExpandable: record => record.saleOrderId,
                  }}
                  expandIconColumnIndex={0}
                  pagination={{
                    onChange(current) {
                      setPage(current);
                    },
                  }}
                  onChange={onChange}
                  size="middle"
                  bordered
                />
            </TabPane>
            <TabPane
              key="2"
              tab={<span style={{ color: "#52c41a" }} >Closed: {codeListData.filter((rs) => rs.coItemCount === rs.soItemCount).length}</span>}
            >
                <Table
                  rowKey={record => record.saleOrderId}
                  columns={codeListData.length > 0 ? columnsSkelton2: []}
                  dataSource={codeListData.filter((rs) => rs.coItemCount === rs.soItemCount)}
                  expandable={{
                    expandedRowRender: (record) => codeListItemTable(record),
                    onExpand(expanded, record) {
                      getCodeListItemData(record.codeListMainId);
                    },
                    rowExpandable: record => record.saleOrderId,
                  }}
                  expandIconColumnIndex={0}
                  pagination={{
                    onChange(current) {
                      setPage(current);
                    },
                  }}
                  onChange={onChange}
                  size="middle"
                  bordered
                />
            </TabPane>
          </Tabs>
          <Drawer bodyStyle={{ paddingBottom: 80 }} title='Update' width={window.innerWidth > 768 ? '90%' : '95%'}
          onClose={closeDrawer} visible={drawerVisible} closable={true}>
          <Card headStyle={{ textAlign: 'center', fontWeight: 500, fontSize: 16 }} size='small'>
            <CodeListMainForm key={Date.now()}
              isUpdate={true}
              // saveItem={saveVariant}
              selectedData={selectedCodeListData}
              closeForm={closeDrawer} />
          </Card>
        </Drawer>
          <Modal key={Date.now()} visible={isModalVisible} onCancel={() => setIsModalVisible(false)} closable width={'80%'} footer={null}>
          {
            modal == 'printone' ?
              <CodeListPrint selectedData={selectedInformation} />
              : <CodeListPrintbeforeSubJob selectedData={selectedInformation} />

          }
        </Modal>
        </div>
    </Card>
    </>
  );
}

export default CodeListAllocationGrid;
