import { GlobalVariableValues, OperationTypeEnum } from "@gtpl/shared-models/common-models";
import { OperationInventoryRequest, ProductionInventoryDetails, SendStockTransferDto, StockTransferData } from "@gtpl/shared-models/production-management";
import { Alert, Button, Card, Col, DatePicker, Divider, Empty, Form, Input, InputNumber, Row, Select, Spin, Table, Tooltip } from "antd"
import Link from "antd/lib/typography/Link";
import React, { useEffect, useRef, useState } from "react"
import { SearchOutlined, DoubleRightOutlined, UndoOutlined } from '@ant-design/icons';
import Highlighter from 'react-highlight-words';
import { ProductionInventoryService, StockTransferService } from "@gtpl/shared-services/production";
import { AlertMessages } from "@gtpl/shared-utils/alert-messages";
import { PlantsDropDown } from "@gtpl/shared-models/masters";
import { UnitcodeService } from "@gtpl/shared-services/masters";
import moment from "moment";

const { Option } = Select;

export const MultipleLotsStockTransfer = () => {
    const searchInput = useRef(null);
    const [searchText, setSearchText] = useState('');
    const [searchedColumn, setSearchedColumn] = useState('');
    const [selectedOperation, setSelectedOperation] = useState('');
    const [inventoryTransfer] = Form.useForm();
    const inventoryService = new ProductionInventoryService();
    const [inventoryData, setInventoryData] = useState<any[]>([]);
    const [loading, setLoading] = useState<boolean>(false);
    const [batchNumbers,setBatchNumbers] = useState<any[]>([])
    const [selectedRowsData, setSelectedRowsData] = useState<any[]>([]);
    const [subPlantData, setSubPlantData] = useState<PlantsDropDown[]>([]);
    const unitService = new UnitcodeService();
    const transferService = new StockTransferService();
    const [selectedRowKeysData, setSelectedRowKeysData] = useState<string[]>([]);
    const [transferBtnDisable,setTransferBtnDisable] = useState<boolean>(true)
    const [transferPlant,setTransferPlant] = useState<string>()

    useEffect(() => {
        getSubPlants()
    },[])

    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 onTranferQtyChange = (e,index,data) => {
        if(Number(e.target.value) <= data.physicalQuantity){
            inventoryData[index].transferQty = Number(e.target.value)
        }else{
            AlertMessages.getErrorMessage('Transfer Qty should be less than physical qty')
        }
    }

    const onTranferBoxesChange = (e,index) => {
        inventoryData[index].transferBoxes = Number(e.target.value)
    }
    

    const columnsSkelton: any = [
        {
          title: 'Lot Code',
          dataIndex: 'lotNumber',
          sorter: (a, b) => a.lotNumber?.localeCompare(b.lotNumber),
          sortDirections: ['descend', 'ascend'],
          ...getColumnSearchProps('lotNumber'),
          render: (value, record) => {
            return record.lotNumber
          }
        },
        {
          title: 'Input Count',
          dataIndex: 'inputGrade',
          sorter: (a, b) => a.inputGrade?.localeCompare(b.inputGrade),
          sortDirections: ['descend', 'ascend'],
          ...getColumnSearchProps('inputGrade'),
          render:(text,data) => {
            return text ? text :"-"
          },
        },
        {
          title: 'Output Count',
          dataIndex: 'outputGrade',
          sorter: (a, b) => a.outputGrade?.localeCompare(b.outputGrade),
          sortDirections: ['descend', 'ascend'],
          ...getColumnSearchProps('outputGrade'),
          render:(text,data) => {
            return text ? text :"-"
          },
        },
        // selectedOperation == OperationTypeEnum.BE_HEADING || selectedOperation == OperationTypeEnum.VALUE_ADDITION ? 
        {
          title: 'Product',
          dataIndex: 'product',
          sorter: (a, b) => a.product?.localeCompare(b.product),
          sortDirections: ['descend', 'ascend'],
          ...getColumnSearchProps('product'),
          render:(text,data) => {
            return text ? text :"-"
          },
    
         
        } ,
        // : '',
    
        {
          title: 'I/P Boxes',
          dataIndex: 'boxes',
          render: (value) => {
            return <div style={{ textAlign: 'right', color: "black", fontWeight: 'bold' }}>{value}</div>
          }
        },
        {
          title: 'O/P Boxes',
          dataIndex: 'opBoxes',
          render: (value) => {
            return <div style={{ textAlign: 'right', color: "black", fontWeight: 'bold' }}>{value}</div>
          }
        },
        // {
        //   title: 'WIP QTY',
        //   dataIndex: 'wipQuantity',
        //   render: (value) => {
        //     return <div style={{ textAlign: 'right', color: "black", fontWeight: 'bold' }}>{value}</div>
        //   }
        // },
        {
          title: "Transferred Qty",
          dataIndex: 'transferedQty',
          render: (value) => {
            return <div style={{ textAlign: 'right', color: "black", fontWeight: 'bold' }}>{value}</div>
          }
        },
        // {
        //   title: 'Wastage QTY',
        //   dataIndex: 'wastageQuantity',
        //   render: (value) => {
        //     return <div style={{ textAlign: 'right', color: "black", fontWeight: 'bold' }}>{value}</div>
        //   }
        // },
        {
          title: selectedOperation === OperationTypeEnum.GRN || selectedOperation === OperationTypeEnum.VALUE_ADDITION ? 'Input Qty(HON)' : 'Output Qty(HL)',
          dataIndex: 'issuedQuantity',
          render: (value) => {
            return <div style={{ textAlign: 'right', color: "black", fontWeight: 'bold' }}>{value}</div>
          }
        },
        {
          title: 'QTY',
          dataIndex: 'physicalQuantity',
          render: (value, rowData: ProductionInventoryDetails) => {
            return <div style={{ textAlign: 'right', color: "black", fontWeight: 'bold' }}> {value} </div>
          }
        },
        {
            title:'Transfer Qty',
            dataIndex:'transferQty',
            render:(text,record,index) => {
                return(
                    <>{<Input placeholder="Enter Qty" onChange={(e) => {onTranferQtyChange(e,index,record)}}/>}</>
                )
            }
        },
        {
          title:'Transfer Boxes',
          dataIndex:'tranferBoxes',
          render:(text,record,index) => {
              return(
                  <>
                  <Input placeholder="Enter Boxes" onChange={(e) => {onTranferBoxesChange(e,index)}}
                      />
                  </>
               
              )
          }
      }
    ];

    const getBatchNumbersForStockTransfer = () => {
        const operation = inventoryTransfer.getFieldValue('operation');
        setSelectedOperation(operation); 
        const req = new OperationInventoryRequest(operation, Number(localStorage.getItem('unit_id')))
        inventoryService.getBatchNumbersForStockTransfer(req).then(res => {
            if(res.status){
                setBatchNumbers(res.data)
            }else{
                setBatchNumbers([])
            }
        })
    }

    const getInventoryInfo = () => {
        const operation = inventoryTransfer.getFieldValue('operation');
        setSelectedOperation(operation); 
        if (operation) {
          setInventoryData([]);
          setLoading(true);
          const req = new OperationInventoryRequest(operation, Number(localStorage.getItem('unit_id')),inventoryTransfer.getFieldValue('batchNumbers'))
          inventoryService.getStockInventory(req).then((res) => {
            if (res.status) {
              setInventoryData(res.data);
              setLoading(false);
            } else {
              if (res.intlCode) {
                AlertMessages.getErrorMessage(res.internalMessage);
              } else {
                AlertMessages.getErrorMessage(res.internalMessage);
              }
              setLoading(false);
              setInventoryData([]);
            }
          })
            .catch((err) => {
              setLoading(false);
              setInventoryData([]);
              AlertMessages.getErrorMessage(err.message);
            });
        }
      }  

    const OnSearch = () => {
        getInventoryInfo()
    }

    const rowSelection = {
        onChange: (selectedRowKeys, selectedRows) => {
          console.log(selectedRows);
         const selectedQtyFlag = new Set<boolean>()
          selectedRows.forEach((data,index) => {
            if (Number(data.transferQty) > 0 && Number(data.transferQty) <= data.physicalQuantity && Number(data.transferBoxes) > 0) {
              selectedQtyFlag.add(true)
            } else {
              selectedQtyFlag.add(false)
            }
        })

        if(!selectedQtyFlag.has(false)){
            setSelectedRowKeysData(selectedRowKeys);
            setSelectedRowsData(selectedRows);
            if(inventoryTransfer.getFieldValue('subPlantId') != undefined && inventoryTransfer.getFieldValue('estimatedDate') != undefined){
                setTransferBtnDisable(false)
            }
        }else{
            AlertMessages.getErrorMessage('Please Enter Transfer Boxes and Qty')
        }

    
    }
    };

    const onReset = () => {
        inventoryTransfer.resetFields()
        setInventoryData([])
        setTransferPlant(null)
        setTransferBtnDisable(true)
        setBatchNumbers([])
        setSelectedRowsData([])
        setSelectedRowKeysData([])
    }

    const onStockTransfer = () => {
        const info = []
        for(const rec of selectedRowsData){
            info.push(new StockTransferData(rec.lotNumber,rec.subLotNumber,Number(localStorage.getItem('unit_id')),rec.plantName,inventoryTransfer.getFieldValue('subPlantId'),transferPlant,rec.transferQty,rec.transferBoxes,rec.count,rec.prodInvId,rec.operation,rec.nextOperation,localStorage.getItem('createdUser'),inventoryTransfer.getFieldValue('estimatedDate'),rec.plantId,rec.previousOperation))
        }
        console.log(info,'=================')
        const req = new SendStockTransferDto()
        req.sendStocks = info
        transferService.sendStock(req).then((res) => {
            if (res.status) {
              AlertMessages.getSuccessMessage(res.internalMessage);
              onReset()
            } else {
              AlertMessages.getErrorMessage(res.internalMessage);
            }
          }).catch((err) => {
            AlertMessages.getErrorMessage(err.message);
          });
    }

    const getSubPlants = () => {
        unitService.getAllPlants().then((res) => {
          if (res.status) {
            // if(props.inventoryInfo.nextOperation === "SOAKING" || props.inventoryInfo.nextOperation === "FREEZING" || props.inventoryInfo.nextOperation === "COOKING"){
            //   setSubPlantData(res.data.filter((rec) => rec.plantType === "PLANT"));
            // }
            // else{
              setSubPlantData(res.data);
            // }
          } else {
            setSubPlantData([]);
          }
        }).catch((err) => {
          AlertMessages.getErrorMessage(err.message);
          setSubPlantData([]);
        });
    }

    const onSubPlantChange = (val,obj) => {
        setTransferPlant(obj?.transferPlant)
    }


    return(
        <Card title={<span style={{ color: 'white' }}>Stock Transfer</span>}
        style={{ textAlign: 'center' }} headStyle={{ backgroundColor: '#69c0ff', border: 0 }}>

        <Form form={inventoryTransfer}>
        <Row gutter={24}>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 5 }}>
            <Form.Item
            label='Operation'
              name={"operation"}
              rules={[
                {
                  required: false,  
                  message: `Please Select Operation`,
                },
              ]}
            >
              <Select
                placeholder="Select Operation"
                allowClear
                showSearch
                style={{ width: '100%' }}
                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                onSelect={(value: string | number) => {
                  setSelectedOperation(String(value)); 
                  setTimeout(() => {
                    getBatchNumbersForStockTransfer();
                  }, 0);  // Use setTimeout to ensure state updates before continuing
                }}
              >
                <Option key={'operation'} value={''}>Select Operation</Option>
                <Option key={1} selected value={OperationTypeEnum.GRN}>{OperationTypeEnum.GRN}</Option>
                <Option key={2} value={OperationTypeEnum.BE_HEADING}>{OperationTypeEnum.BE_HEADING}</Option>
                <Option key={3} value={OperationTypeEnum.GRADING}>{OperationTypeEnum.GRADING}</Option>
                <Option key={4} value={OperationTypeEnum.VALUE_ADDITION}>{OperationTypeEnum.VALUE_ADDITION}</Option>
               {GlobalVariableValues.productionVersion == 'V2'? '' :<>
               <Option key={5} value={OperationTypeEnum.SOAKING}>{OperationTypeEnum.SOAKING}</Option>
                <Option key={6} value={OperationTypeEnum.FREEZING}>{OperationTypeEnum.FREEZING}</Option>
                <Option key={7} value={OperationTypeEnum.PACKING}>{OperationTypeEnum.PACKING}</Option>
               </> }
              </Select>
            </Form.Item>

          </Col>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 8 }}>
          <Form.Item name='batchNumbers' label='Batch Numbers'>
          <Select allowClear showSearch optionFilterProp="children" mode="multiple" placeholder='Select Batch Numbers'>
            {
                batchNumbers.map(e => {
                    return(
                        <Option key={e.lotNumber} value={e.lotNumber}>{e.lotNumber}</Option>
                    )
                })
            }
          </Select>
          </Form.Item>
          </Col>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 3 }}>
          <Form.Item>
            <Button type="primary" onClick={OnSearch} icon={<SearchOutlined/>}>Search</Button>
          </Form.Item>
          </Col>
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 3 }}>
          <Form.Item>
            <Button danger icon={<UndoOutlined/>} onClick={onReset}>Reset</Button>
          </Form.Item>
          </Col>
          {

          }
         
        </Row>
        {
            inventoryData.length > 0 ? (<>
                <Row>
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 8 }}>
                    <Form.Item
                    name={"subPlantId"}
                    label="Plant/Sub Plant"
                    rules={[
                        {
                        required: true,
                        message: `Please Select Sub Plant!`,
                        },
                    ]}
                    >
                    <Select
                        placeholder="Select To Sub Plant"
                        allowClear
                        showSearch
                        style={{ width: '100%' }}
                        filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                        onChange={onSubPlantChange}
                    >
                        {subPlantData.map(dropData => {
                        return (dropData.plantId != Number(localStorage.getItem('unit_id'))) ? <Option key={dropData.plantId} value={dropData.plantId} transferPlant={dropData.plantName}>{dropData.plantCode}</Option> : ''
                        })}
                    </Select>
                    </Form.Item>
                    </Col>
                    <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 6 }}>
                    <Form.Item
                    name={"estimatedDate"}
                    label="ETD"
                    style={{ margin: 0 }}
                    rules={[
                        {
                        required: true,
                        message: `Please Expected Del Date`,
                        },
                    ]}
                    initialValue={moment()}
                    >
                    <DatePicker showTime style={{ width: '100%' }} />
                    </Form.Item>
                </Col>
                <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 3 }}>
                <Button style={{marginLeft:'88%',backgroundColor:'lightgreen'}} disabled={transferBtnDisable} onClick={onStockTransfer}>Transfer</Button>
                </Col>
                </Row>
            
            </>) : (<></>)
        }
      </Form> <br />
      {inventoryData.length ? 
      <>
        <Table
        rowSelection={{
            ...rowSelection
          }}
          columns={columnsSkelton}
          // key={selectedOperation} 

          pagination={{
            defaultPageSize: 50,
          }}
          summary={() => (
            <Table.Summary fixed>
              <Table.Summary.Row className='tableFooter'>
                
                <Table.Summary.Cell index={2} colSpan={7}>{'Total'}</Table.Summary.Cell>

                {GlobalVariableValues.productionVersion =='V1'?(<>
                <Table.Summary.Cell index={4}>
                  {inventoryData.reduce(function (previousValue, currentValue) {
                    return previousValue + Number(currentValue.wipQuantity);
                  }, 0)}
                </Table.Summary.Cell>
                </>):(<></>)}
                
                <Table.Summary.Cell index={7}>
                  {inventoryData.reduce(function (previousValue, currentValue) {
                    return previousValue + Number(currentValue.transferedQty);
                  }, 0)}
                </Table.Summary.Cell>
                {GlobalVariableValues.productionVersion =='V1' ?(<>
                  <Table.Summary.Cell index={6}>
                  {inventoryData.reduce(function (previousValue, currentValue) {
                    return previousValue + Number(currentValue.wastageQuantity);
                  }, 0)}
                  </Table.Summary.Cell>
                </>):(<></>)}
                
                <Table.Summary.Cell index={8}>{inventoryData.reduce(function (previousValue, currentValue) {
                  return previousValue + Number(currentValue.issuedQuantity);
                }, 0)}</Table.Summary.Cell>

                {GlobalVariableValues.productionVersion =='V1' ?(<>
                  <Table.Summary.Cell index={8}>{inventoryData.reduce(function (previousValue, currentValue) {
                  return previousValue + Number(currentValue.rejectedQuantity);
                  }, 0)}</Table.Summary.Cell>
                </>):(<></>) }
                

                <Table.Summary.Cell index={9}>{inventoryData.reduce(function (previousValue, currentValue) {
                  return previousValue + Number(currentValue.physicalQuantity);
                }, 0)}</Table.Summary.Cell>
                <Table.Summary.Cell index={10}></Table.Summary.Cell>
                <Table.Summary.Cell index={11}></Table.Summary.Cell>

              </Table.Summary.Row>
            </Table.Summary>
          )}
          dataSource={inventoryData}
          rowKey={(record) => record.prodInvId}
          bordered
        />
        </> 
      : <>{(loading) ? <Spin tip="Loading...">
        <Alert
          message="Please Wait"
          description={"getting " + inventoryTransfer.getFieldValue('operation') + " Inventory"}
          type="info" />
      </Spin> : <Empty />}</>}
        </Card>
    )

}

export default MultipleLotsStockTransfer