import { ItemForBrandReq, ItemsDropDownDto, ItemSubCategoryDropDownDto, SubCatReqForCategoryId } from '@gtpl/shared-models/masters';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { Button, Card, Col, Form, Input, InputNumber, Radio, Row, Select, Table } from 'antd'
import { FormInstance } from 'rc-field-form';
import React, { useEffect, useState } from 'react';
import { OperationService, ProductionInventoryService } from '@gtpl/shared-services/production';
import { ColumnProps } from 'antd/lib/table';
import { OperationTypeEnum } from '@gtpl/shared-models/common-models';

interface AddlotCodeFormProps{
  lotData: (lotItemDto: any[]) => void;
  operation:string
  form:FormInstance<any>
  totalQuantity:(totalQuantity:any) =>void
  visibletable:boolean;
}
export default function AddlotCodeForm(props:AddlotCodeFormProps){
const { Option } = Select
const [childform] = Form.useForm();
const [tableData, setTableData] = useState<any[]>([]);
const [lotInfo,setLotInfo] = useState<any[]>([])
const operationservice = new OperationService();

useEffect(() =>{
  console.log(props.operation);
  if(props.operation){
    childform.resetFields();
    getLotNumbersDropDownForLotClub(props.operation);
  }
},[props.operation])


useEffect(() =>{
  let totalQuantity = 0
  if(tableData.length > 0){
    tableData.forEach(item =>{totalQuantity +=Number(item.quantity) ? Number(item.quantity):0})
    console.log(totalQuantity)
    props.totalQuantity(totalQuantity)
  }
},[tableData])


  const columns: ColumnProps<any>[] = [
 {
      title: 'Sub Lot Code',
      dataIndex: 'subLotNumber',
    },
    {
      title: 'Lot Code',
      dataIndex: 'lotCodesAvailable',
    },

    {
      title: 'Quantity ',
      dataIndex: 'quantity',
    },
    {
      title:'O/P Boxes',
      dataIndex:'opBoxes',

    },
    {
      title: 'Action',
      dataIndex: 'action',
      render: (text, rowData: any, index) => {
        return(
        <Button size='small' shape='round' type='primary' onClick={() => { deletelot(index) }} >Delete</Button>
        )
      }
    }

  ];

  const saveitems = ( ) =>{   
     childform.validateFields().then(res =>{
      // const obj = {subLotNumber:res.subLotNumber,lotcode : res.lotCodesAvailable,quantity:res.quantity,opBoxes:res.opBoxes}
      console.log(res)
      setTableData((prev) => {return [...prev,res]})
      console.log(tableData)
        childform.resetFields()
        props.lotData([...tableData,res])
        props.visibletable === true;
     })
  }

  const deletelot = (index) =>{
    tableData.splice(index,1)
    setTableData([...tableData])
    props.lotData([...tableData])
    console.log(tableData)
  }

    const getLotNumbersDropDownForLotClub = (value) => {
      operationservice.getLotNumbersDropDownForLotClub({operation:value,plant: Number(localStorage.getItem('unit_id'))}).then((res) => {
        if (res.status) {
          setLotInfo(res.data);
  
        } else {
          setLotInfo([]);
        }
      }).catch((err) => {
        AlertMessages.getErrorMessage(err.message);
        setLotInfo([]);
      });
  
    }
    const subLotOnchange = (e,option) => {
      const lotNumber = lotInfo.filter((el) => {return el.prod_inv_id == e})
      console.log (lotNumber)
      childform.setFieldsValue({lotCodesAvailable:lotNumber[0]?.lotNumber,opBoxes:lotNumber[0]?.opBoxes,quantity:lotNumber[0]?.quantity,lotNumber:option?.lotNumber,count:option?.count})
      // physicalquantity(lotNumber[0].lotNumber);
    }

    return(
        <Card title={<span style={{ color: 'white' }}>Add Lots For Clubbing</span>}
        style={{ textAlign: 'center' }} headStyle={{ backgroundColor: '#69c0ff', border: 0 }}>
        <Form form={childform} layout={'vertical'}  
        // onFinish={saveitems}
        >
          <Row gutter={24}>
            <Form.Item name='lotNumber' hidden>
              <Input/>
            </Form.Item>
            <Form.Item name='count' hidden>
              <Input/>
            </Form.Item>
          <Col span={7}>
            <Form.Item
              name="subLotNumber"
              label="Sub Lot codes Available"
              rules={[
                {
                  required: true,
                  message: 'SubLot code is required'
                }
              ]}

            >
              <Select
                showSearch
                optionFilterProp="children"
                // filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select SubLotCode"
                allowClear
                onChange={(e,option) =>{subLotOnchange(e,option)}}
              >
                 <Option key={0} value={null}>Please select SubLot</Option>
                    {lotInfo.map((dropData) => {
                      return (
                        <Option
                          key={dropData.prod_inv_id}
                          value={dropData.prod_inv_id}
                          lotNumber={dropData.subLotNumber}
                          count={props.operation == OperationTypeEnum.GRADING ? dropData.output_grade : dropData.input_grade}
                        >
                          {dropData.sublotnplsntlot}-{props.operation == OperationTypeEnum.GRADING ? dropData.output_grade : dropData.input_grade}{props.operation == OperationTypeEnum.VALUE_ADDITION ? `- ${dropData.product}` : ''}
                        </Option>
                      );
                    })}
              </Select>
            </Form.Item>
          </Col>
          <Col span={7} >
          <Form.Item
              name="lotCodesAvailable"
              label="Lot code "
              rules={[
                {
                  required: true,
                  message: 'Lot codes Available is required'
                }
              ]}

            >
            <Input disabled/>
            </Form.Item>
            </Col>
          <Col span={4}>
              <Form.Item
                  label="Quantity"
                  name="quantity"
                  rules={[{ required: true, message: 'Missing quantity' }
                  ]}
                >
                  <Input type='number' style={{ width: '100%' } } disabled
                  //  onChange={e => appendInputData(e.target.value, 'quantity')}
                   />
                </Form.Item>
              </Col>
              <Col span={4}>
              <Form.Item
                  label="O/P Boxes"
                  name="opBoxes"
                  rules={[{ required: true, message: 'Missing opBoxes' }
                  ]}
                >
                  <Input type='number' style={{ width: '100%' }} disabled
                   />
                </Form.Item>
              </Col>
              <Col span={2}>
              <Button style={{ backgroundColor: "#67b32d", color: "white", marginTop: "28px" }} type="primary" onClick={saveitems}>
               ADD
              </Button>
          </Col>
          </Row>
          <br />
          {tableData.length ?
          <Row>
            <Table   rowKey={(row) => row.lotCodesAvailable }        
               scroll={{ y: 1600 }}
              dataSource={tableData}
              columns={columns} 
              pagination={false}
              style={{display : props.visibletable === false ? 'none' : 'block'}}
              /> 
          </Row>:<></>
          }
            </Form>                
            </Card>
    )
}