import React, { useEffect, useRef, useState } from 'react'
import ReprocessingJobItemsJobId from './reprocessing-repacking-jobid';
import { Button, Card, Col, Divider, Input, Modal, Popconfirm, Row, Tabs, Tooltip } from 'antd';
import Table, { ColumnProps } from 'antd/lib/table';
import { ForkLiftJobRequestDTO, JobItemsJobIdreq } from '@gtpl/shared-models/warehouse-management';
import { ForkLiftJobService } from '@gtpl/shared-services/warehouse-management';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import Highlighter from 'react-highlight-words';

import { CheckCircleOutlined,DoubleRightOutlined, CloseCircleOutlined, RightSquareOutlined, EyeOutlined, EditOutlined, SearchOutlined } from '@ant-design/icons';
import { Redirect } from 'react-router-dom';
import moment from 'moment';


const ReprocessingRepackinglabsamplesgrid = () => {
    const [printDisable, setPrintVisable] = useState<boolean>(false);
    const [printId, setPrintId] = useState<any>([]);
    const [rowData, setRowData] = useState<any>(undefined);
    const [ close,setClosing] = useState<any[]>([])
    const service = new ForkLiftJobService;
    const [availableStockData, setAvailableStockData] = useState<any[]>([]);
    const [labCodes,setlabcodesData]= useState<any[]>([])
    const [searchText, setSearchText] = useState('');
    const [searchedColumn, setSearchedColumn] = useState('');
    const searchInput = useRef(null);
    const [page, setPage] = React.useState(1);
    const { TabPane } = Tabs;
    const [pageSize, setPageSize] = useState<number>(null);
    const onChange = (pagination, filters, sorter, extra) => {
        console.log('params', pagination, filters, sorter, extra);
      }
  
  useEffect(()=>{
    getLabSamplesAndComplements()

  },[])




      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
    
      });

      function handleSearch(selectedKeys, confirm, dataIndex) {
        confirm();
        setSearchText(selectedKeys[0]);
        setSearchedColumn(dataIndex);
      };
    
      function handleReset(clearFilters) {
        clearFilters();
        setSearchText('');
      };
  







    
  const openModal = (val)=>{
    setPrintVisable(true);
    setPrintId(val);
  }
  const handelCancel = () =>{
    setPrintVisable(false)
  }


//   const getClosingLabsampling = () => {
//     const plant = Number(localStorage.getItem('unit_id'));

//     const req = new JobItemsJobIdreq();
//     req.unitId = plant

 
//     service.getForkliftJobCodeswithLabSamples(req)
//       .then(res => {
//         if (res.status) {
//           setlabcodesData(res.data);
//           setAvailableStockData(res.data1);
  
//           if (res.data && res.data.length > 0) {
//             const jobId = res.data[0].jobId;
  
//             const closeReq = new JobItemsJobIdreq(jobId);
  
//             service.closeForkliftJobManually(closeReq)
//               .then(closeRes => {
//                 if (closeRes.status) {
//                   AlertMessages.success('Forklift job closed successfully');
//                 } else {
//                   AlertMessages.showError('Failed to close forklift job');
//                 }
//               })
//               .catch(err => {
//                 AlertMessages.getErrorMessage(err.message);
//               });
//           }
//         } else {
//           if (res.intlCode) {
//           } else {
//           }
//         }
//       })
//       .catch(err => {
//         AlertMessages.getErrorMessage(err.message);
//         setlabcodesData([]);
//       });
//   };
const getClosingLabSampling = (job) => {
  const req = new JobItemsJobIdreq();
  req.jobId = job.jobId;  // Pass the job ID to the request
  service.closeForkliftJobManually(req).then(res => {
    if (res.status) {
      setClosing(res.data)
      AlertMessages.getSuccessMessage('Lab Sampling job closed successfully');
    } else {
      if (res.intlCode) {
        // Handle intlCode scenario
      } else {
        AlertMessages.getWarningMessage('Failed to close Lab Sampling job');
      }
    }
  }).catch(err => {
    AlertMessages.getErrorMessage(err.message);
    setClosing([])
  });
};




  const getLabSamplesAndComplements = () => {

    const plant = Number(localStorage.getItem('unit_id'));
    const req = new ForkLiftJobRequestDTO()
    req.unitId = plant
    service.getForkliftJobCodeswithLabSamples(req).then(res => {
      if (res.status) {
        setlabcodesData(res.data);
        setAvailableStockData(res.data1)
      }
      else {
        if (res.intlCode) {
        } else {
            
        }
      }
    }).catch(err => {
      AlertMessages.getErrorMessage(err.message);
      setlabcodesData([]);
    })
  }


    const columnsSkelton: ColumnProps<any>[] = [
        {
          title: 'S No',
          key: 'sno',
          width: '70px',
          responsive: ['sm'],
          render: (text, object, index) => (page - 1) * 10 + (index + 1)
        },
        {
          title: 'Job Purpose',
          dataIndex: 'jobPurpose',
          // responsive: ['lg'],
          sorter: (a, b) => a.jobPurpose.localeCompare(b.jobPurpose),
          sortDirections: ['descend', 'ascend'],
          // ...getColumnSearchProps('jobPurpose')
    
        },
        {
          title: 'Stock Type',
          dataIndex: 'stockType',
          // responsive: ['lg'],
          sorter: (a, b) => a.stockType.localeCompare(b.stockType),
          sortDirections: ['descend', 'ascend'],
          // ...getColumnSearchProps('jobPurpose')
    
        },
        {
          title:'Date',
          dataIndex:'jobDate',
          render:(text,record) => {
            return(
              record.jobDate ? moment(record.jobDate).format('YYYY-MM-DD') : '-'
            )
          }
        },
        {
          title: 'Job Code',
          dataIndex: 'jobCode',
          // responsive: ['lg'],
          sorter: (a, b) => a.jobCode.localeCompare(b.jobCode),
          sortDirections: ['descend', 'ascend'],
          ...getColumnSearchProps('jobCode'),
          render: (text, record) => (
            <Button
              type="link"
              onClick={() => openModal(record)}
            >
              {text}
            </Button>
            
          ),
        },
        {
          title: 'Customer PO',
          dataIndex: 'poNumber',
          // responsive: ['lg'],
          sorter: (a, b) => a.poNumber.localeCompare(b.poNumber),
          sortDirections: ['descend', 'ascend'],
          ...getColumnSearchProps('poNumber')
        },
        // {
        //   title: 'Product SKU',
        //   dataIndex: 'shortCode',
        //   // responsive: ['lg'],
        //   sorter: (a, b) => a.shortCode.localeCompare(b.shortCode),
        //   sortDirections: ['descend', 'ascend'],
        //   ...getColumnSearchProps('shortCode')
        // },
        // {
        //   title: 'Pack Style',
        //   dataIndex: 'packStyle',
        //   // responsive: ['lg'],
        //   sorter: (a, b) => a.packStyle.localeCompare(b.packStyle),
        //   sortDirections: ['descend', 'ascend'],
        //   ...getColumnSearchProps('packStyle')
        // },
        {
          title: 'Total Cartons',
          dataIndex: 'totalJobCartons',
          align: 'right',
          // responsive: ['lg'],
          render: (status, rowData) => (
            <>
              {rowData.totalJobCartons + "(Qty : " + Number(rowData.totIssuedQuantity) + ")"}
    
            </>
          ),
        },
        {
          title: 'Received Quantity',
          dataIndex: 'totReceivedQuantity', 
          align: 'right',
          // responsive: ['lg'],
          sorter: (a, b) => a.totReceivedQuantity.localeCompare(b.totReceivedQuantity),
          sortDirections: ['descend', 'ascend'],
          ...getColumnSearchProps('totReceivedQuantity'),
        render:(text,record) => {
          return(
            <>{record.totReceivedQuantity ? Number(record.totReceivedQuantity) : '-'}</>
          )
        }
        },
        {
          title: 'Excess Quantity',
          dataIndex: 'excessQuantity',
          align: 'right',
          // responsive: ['lg'],
          sorter: (a, b) => a.excessQuantity.localeCompare(b.excessQuantity),
          sortDirections: ['descend', 'ascend'],
          ...getColumnSearchProps('excessQuantity'),
          render:(text,record) => {
            return(
              <>{record.excessQuantity ? Number(record.excessQuantity) : '-'}</>
            )
          }
        },
        {
          title: 'Damage Quantity',
          dataIndex: 'damagedCartons',
          align: 'right',
          // responsive: ['lg'],
          // sorter: (a, b) => a?.damagedCartons.localeCompare(b?.damagedCartons),
          // sortDirections: ['descend', 'ascend'],
          ...getColumnSearchProps('damagedCartons')
        },
        {
          title: 'Status',
          dataIndex: 'status',
          // responsive: ['lg'],
          sorter: (a, b) => a.status.localeCompare(b.status),
          sortDirections: ['descend', 'ascend'],
          ...getColumnSearchProps('status')
        },
        {
          title: 'Action',
          dataIndex: 'action',
          render: (status, rowData) => (
            <>
              {rowData.status != "Completed" ? (
               
                <>
                  {rowData.jobPurpose === "labsamples" && rowData.status !== "Completed" ? (
                    rowData.status === "Completed" ? "-" : (
                      <>
                        <Tooltip placement="topLeft" title={"Close lab sample"}>
                          <Popconfirm
                            title="Are you sure you want to close the lab sample?"
                            onConfirm={() => {
                              getClosingLabSampling(rowData);
                              getLabSamplesAndComplements();
                            }}
                            okText="Yes"
                            cancelText="No"
                          >
                            <CloseCircleOutlined
                              style={{
                                color: 'red',
                                fontSize: '14px',
                              }}
                            />
                          </Popconfirm>
                        </Tooltip>
                        <Divider type="vertical" />
                      </>
                    )
                  ) : " "}
                  
                  {rowData.status === "Completed" ? "-" : (
                    <>
                      <DoubleRightOutlined
                        onClick={() => setRowData(rowData)}
                        style={{ color: '#1890ff', fontSize: '14px' }}
                      />
                      <Divider type="vertical" />
                    </>
                  )}
                </>
              ):''}
            </>
          ),
        }
        
        
        
        
        
      ];
    
  return (
    <div>
              {(rowData) ? <Redirect to={{ pathname: "/stock-in", state: rowData }} /> : null}

        
    <Tabs type={'card'} tabPosition={'top'} onChange={() => { setPageSize(10); setPage(1); } }>
      

        <TabPane
      key="5"

    //   tab={<span style={{ color: "#0ec92d" }}>{'LabSamples & complements Jobs: ' + (labCodes.length)}</span>}
    >
      <Row gutter={40}>
        <Col>
          <Card title={'Total Jobs: ' + labCodes.length} style={{ textAlign: 'left', width: 200, height: 41, backgroundColor: '#bfbfbf' }}></Card>
        </Col>
        <Col>
          <Card title={'Pending Jobs: ' + labCodes.filter((rec) => rec.status === "Pending").length} style={{ textAlign: 'left', width: 200, height: 41, backgroundColor: '#bfbfbf' }}></Card>
        </Col>
        <Col>
          <Card title={'Completed Jobs: ' + labCodes.filter((rec) => rec.status === "Completed").length} style={{ textAlign: 'left', width: 200, height: 41, backgroundColor: '#bfbfbf' }}></Card>
        </Col>
      </Row><br></br>
      <Table
        rowKey={record => record.jobId}
        columns={columnsSkelton}
        dataSource={labCodes}
        pagination={{
          onChange(current) {
            setPage(current);
          }
        }}
        scroll={{ x: true }}
        onChange={onChange}
        bordered />
    </TabPane>
     </Tabs>

<Modal
        key={'modal3' + Date.now()}
        width={'70%'}
        style={{ top: 30, alignContent: 'right' }}
        visible={printDisable}
        title={<React.Fragment>
    </React.Fragment>}
        onCancel={handelCancel}
        footer={null}
      >
        <ReprocessingJobItemsJobId  
         
         jobId = {printId.jobId}
         jobCode={printId.jobCode}
         shortCode={printId.shortCode}
         packStyle={printId.packStyle}
         poNumber={printId.poNumber}
         totalJobCartons={printId.totalJobCartons}
         totReceivedQuantity={printId.jobId}
        
        />
        
      </Modal>
    </div>
  )
}

export default ReprocessingRepackinglabsamplesgrid