import React, { useEffect, useState } from 'react';
import {Form,Select,Card,Row,Col,InputNumber,Button,Input} from 'antd';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import './product-convertion-form.css';
import {LotCodeOpsService,ProductConversionService,ProductionInventoryService} from '@gtpl/shared-services/production';
import { Link, useHistory } from 'react-router-dom';
import {OperationTypeEnum,OpertionTypeDropDown,UnitRequest} from '@gtpl/shared-models/common-models';
import {LotCodeDropDown} from '@gtpl/shared-models/production-management';
import { SaleOrderService } from '@gtpl/shared-services/sale-management';
import { StockService } from '@gtpl/shared-services/procurement';
import { OperationInventoryRequest, OperationsDropDown, ProductionInventoryDetails } from '@gtpl/shared-models/production-management';

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

export function ProductConvertionForm(props: ProductConvertionFormProps) {
  const Option = Select;
  let history = useHistory();
  const [inventoryTransfer] = Form.useForm();
  const [lotNumbers, setLotNumbers] = useState<LotCodeDropDown[]>([]);
  const lotCodeService = new LotCodeOpsService();
  const [disableSubmit, setDisableSubmit] = useState<boolean>(false);
  const { TextArea } = Input;
  const [fromOperation, setFromOperation] = useState<OperationTypeEnum>(undefined);
  const [fromSaleOrderData, setFromSaleOrderData] = useState<any>([]);
  const [toSaleOrderData, setToSaleOrderData] = useState<any>([]);
  const SoService = new SaleOrderService();
  const [reasons, setReasons] = useState<any[]>([]);
  const [sOItemId, setSOItemId] = useState<number>(0);
  const stockService = new StockService();
  const [loading, setLoading] = useState<boolean>(false);
  const [inventory, setInventoryData] = useState<ProductionInventoryDetails[]>([]);
  const inventoryService = new ProductionInventoryService();
  const productConversionService = new ProductConversionService();
  const operations = OpertionTypeDropDown;
  const onFinish = (values) => {
    console.log(values, '*********');
    productConversionService.createProductConversion(values).then((res) => {
      if (res.status) {
        AlertMessages.getSuccessMessage(res.internalMessage);
        history.push('/product-convertion-grid');
      } else {
        if (res.intlCode) {
          AlertMessages.getErrorMessage(res.internalMessage);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
      }
    }).catch(err => {
      AlertMessages.getErrorMessage(err.message);
    })
  };

  let createdUser = '';
  useEffect(() => {
    inventoryTransfer.setFieldsValue({ plantId: Number(localStorage.getItem("unit_id"))});
    createdUser = localStorage.getItem('createdUser');
    getSaleOrderData();
    getReasonsForCycleChecker();
  }, []);

  const calQty = (val) => {
    console.log(val);
    let soItemId = sOItemId;
    let qty = fromSaleOrderData.find((t) => t.saleOrderItemId === soItemId).quantity;
    let boxes = fromSaleOrderData.find((t) => t.saleOrderItemId === soItemId).boxes;
    let boxQty = Number(qty) / Number(boxes);
    let totalQty = Number(boxQty)*Number(val);
    inventoryTransfer.setFieldsValue({quantity:Number(totalQty).toFixed(2)});

  }
  const getReasonsForCycleChecker = () => {
    stockService
      .getReasonsForCycleChecker()
      .then((res) => {
        if (res.data) {
          setReasons(res.data);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
      })
      .catch((err) => {
        AlertMessages.getErrorMessage(err.message);
        setReasons([]);
      });
  };

  
  const getSaleOrderData = () => {
    const req = new UnitRequest(Number(localStorage.getItem('unit_id')));
    SoService.getsoitemforIndent(req)
      .then((res) => {
        if (res.status) {
          setToSaleOrderData(res.data);
        } else {
          if (res.intlCode) {
            AlertMessages.getErrorMessage(res.internalMessage);
          } else {
            AlertMessages.getErrorMessage(res.internalMessage);
          }
          setToSaleOrderData([]);
        }
      })
      .catch((err) => {
        AlertMessages.getErrorMessage(err.message);
        setToSaleOrderData([]);
        // form.resetFields(['saleOrderId'])
      });
  };
  const onFocus = () => {
    //console.log('focus');
  };
  const onSearch = (val) => {
    //console.log('search:', val);
  };
  const onBlur = () => {
    //console.log('blur');
  };

  const getAllLotNumbers = (val) => {
    setFromOperation(val);
    inventoryService.getInventoryLots({plant:Number(localStorage.getItem('unit_id')),operation:val})
      .then((res) => {
        if (res.status) {
          setLotNumbers(res.data);
        } else {
          setLotNumbers([]);
        }
      })
      .catch((err) => {
        AlertMessages.getErrorMessage(err.message);
        setLotNumbers([]);
      });
  };
  const getLotNumberInfo = (val) => {
    inventoryService.getSaleOrdersByLot({lotNumber:val,plantId:Number(localStorage.getItem("unit_id")),presentOperation:fromOperation}).then((res) => {
      if (res.status) {
        setFromSaleOrderData(res.data);
      } else {
        setFromSaleOrderData([]);
      }
    }).catch((err) => {
      AlertMessages.getErrorMessage(err.message);
      setFromSaleOrderData([]);
    });
  }

  const updateToSaleOrderId = (val) => {
    let toSaleOrder = toSaleOrderData.find((t) => t.saleOrderItemId === val).saleOrderId;
    inventoryTransfer.setFieldsValue({ toSaleOrder: toSaleOrder});
  }
  const getInventoryQtyInfo = (val) =>{
    setSOItemId(val);
    console.log(fromSaleOrderData);
    console.log(val);
    let qty = fromSaleOrderData.find((t) => t.saleOrderItemId === val).quantity;
    let boxes = fromSaleOrderData.find((t) => t.saleOrderItemId === val).boxes;
    let count = fromSaleOrderData.find((t)=> t.saleOrderItemId === val).output_grade;
    let prodInvId = fromSaleOrderData.find((t) => t.saleOrderItemId === val).prodInvId;
    let fromSaleOrder = fromSaleOrderData.find((t) => t.saleOrderItemId === val).saleOrderId;
    console.log(qty);
    console.log(boxes);
    console.log(prodInvId);
    inventoryTransfer.setFieldsValue({quantity : qty, boxes: boxes,count:count, prodInvId:prodInvId, fromSaleOrder: fromSaleOrder});
  }
  const getInventoryInfo = () => {
    const operation = inventoryTransfer.getFieldValue('operation');
    if (operation) {
      setInventoryData([]);
      setLoading(true);
      const req = new OperationInventoryRequest(operation, Number(localStorage.getItem('unit_id')))
      inventoryService.getProductionInventoryInfo(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);
        });
    }
  }

  console.log(lotNumbers);

  return (
    <div>
      <Card
        title={<span style={{ color: 'white' }}>Product Conversion</span>}
        style={{ textAlign: 'center' }}
        headStyle={{ backgroundColor: '#69c0ff', border: 0 }}  extra={<Link to="/product-convertion-grid"><Button className='panel_button' >View</Button></Link>}
      >
        <Form layout="vertical" form={inventoryTransfer} onFinish={onFinish}>
            <Form.Item name="productConversionLogId" style={{ display: 'none' }}>
              <Input hidden />
            </Form.Item>
            <Form.Item name="prodInvId" style={{ display: 'none' }}>
              <Input hidden />
            </Form.Item>
            <Form.Item name="fromSaleOrder" style={{ display: 'none' }}>
              <Input  />
            </Form.Item>
            <Form.Item name="toSaleOrder" style={{ display: 'none' }}>
              <Input  />
            </Form.Item>
            <Form.Item name="plantId" style={{ display: 'none' }}>
              <Input  />
            </Form.Item>
            <Form.Item
              style={{ display: 'none' }}
              name="createdUser"
              initialValue={createdUser}
            >
              <Input hidden />
            </Form.Item>
          <Row gutter={24}>
            <Col span={3} style={{ marginLeft: '1%' }}>
              <Form.Item
              name="fromOperation"
              label="From Operation"
              rules={[{ required: true, message: 'Missing From details' }]}
                
              >
                <Select
                  placeholder="Select Operation"
                  allowClear
                  showSearch
                  style={{ width: '100%' }}
                  filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                  onSelect={getAllLotNumbers}
                >

                  <Option key={'operation'} value={''}>Select Operation</Option>
                  {operations.map(dropData => {
                    return <Option value={dropData.name}>{dropData.name}</Option>
                })}
                </Select>
              </Form.Item>

            </Col>
            <Col
              span={4}
            >
              <Form.Item
                name="lotCode"
                label="Lot Code"
                rules={[{ required: true, message: 'Missing Lot No' }]}
              >
                <Select
                  placeholder="Select Lot Code"
                  allowClear
                  showSearch
                  filterOption={(input, option) =>
                    option.children
                      .toLowerCase()
                      .indexOf(input.toLowerCase()) >= 0
                  }
                  onChange={getLotNumberInfo}

                >
                  {lotNumbers.map((dropData) => {
                    return (
                      <Option
                        key={dropData.lotNumber}
                        value={dropData.lotNumber}
                      >
                        {dropData.lotNumber + '-' + (dropData.plantLotNumber != null ? dropData.plantLotNumber:'')}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>

            <Col
              span={10}
            >
              <Form.Item
                name="fromSaleOrderItemId"
                label="From : Product(So & So Item)"
                rules={[{ required: true, message: 'Missing From details' }]}
              >
                <Select
                  showSearch
                  //style={{ width: 200 }}
                  placeholder="Select soitem"
                  optionFilterProp="children"
                  // onSelect={handlesaleorderId}
                  filterOption={(input, option) =>
                    option.children
                      .toLowerCase()
                      .indexOf(input.toLowerCase()) >= 0
                  }
                  onChange={getInventoryQtyInfo}
                >
                  <Option key={0} value={null}>
                    Select Product
                  </Option>
                  {fromSaleOrderData?.map((dropData) => {
                    return (
                      <Option
                        key={dropData.saleOrderItemId}
                        value={dropData.saleOrderItemId}
                      >
                        {dropData.sublotandplantlot}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col span={3} >
                <Form.Item
                  name="boxes"
                  label="Boxes"
                  rules={[{ required: true, message: 'Missing Boxes' }]}
                >
                  {/* onBlur={e=>calQty(e.target.value)} */}
                  <InputNumber style={{ width: '100%' }} min={0} />
                </Form.Item>
            </Col>
            <Col
              span={3}
            >
              <Form.Item
                name="quantity"
                label="Quantity"
                rules={[{ required: true, message: 'Missing quantity' }]}
              >
                <InputNumber style={{ width: '100%' }} min={0} disabled={false}/>
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={24}>
            
          <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 5 }} lg={{ span: 5 }} xl={{ span: 4 }}>
            <Form.Item name="count" label="Count" rules={[{ required: true, message: 'Missing Count' }]}>
                <InputNumber style={{ width: '100%' }} min={0} disabled />
            </Form.Item>
          </Col>
            <Col span={3}  style={{ marginLeft: '1%' }}>
              <Form.Item
              name="toOperation"
              label="To Operation"
              rules={[{ required: true, message: 'Missing From details' }]}
                
              >
                <Select
                  placeholder="Select Operation"
                  allowClear
                  showSearch
                  style={{ width: '100%' }}
                  filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                  onSelect={getInventoryInfo}
                >
                  <Option key={'operation'} value={''}>Select Operation</Option>
                  {(operations.filter((rec) => rec.name != 'REJECTION')).map(dropData => {
                      return <Option value={dropData.value}>{dropData.name}</Option>
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col
              span={10}
            >
              <Form.Item
                name="toSaleOrderItemId"
                label="To : Product(So & So Item)"
                rules={[{ required: true, message: 'Missing To details' }]}
              >
                <Select
                  showSearch
                  //style={{ width: 200 }}
                  placeholder="Select soitem"
                  optionFilterProp="children"
                  // onSelect={handlesaleorderId}
                  filterOption={(input, option) =>
                    option.children
                      .toLowerCase()
                      .indexOf(input.toLowerCase()) >= 0
                  }
                  onChange={updateToSaleOrderId}
                >
                  <Option key={0} value={null}>
                    Select Product
                  </Option>
                  {toSaleOrderData?.map((dropData) => {
                    return (
                      <Option
                        key={dropData.saleOrderItemId}
                        value={dropData.saleOrderItemId}
                      >
                        {dropData.soItem}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>

            <Col
              span={4}
            >
              <Form.Item
                name="conversionReason" 
                label="Conversion Reason"
                rules={[{ required: true, message: 'Missing Assigned Time' }]}
              >
                <Select
                  showSearch
                  // style={{ width: 240 }}
                  placeholder="Select Item"
                  optionFilterProp="children"
                  onBlur={onBlur}
                  onSearch={onSearch}
                  filterOption={(input, option) =>
                    option.children
                      .toLowerCase()
                      .indexOf(input.toLowerCase()) >= 0
                  }
                >
                  <Option key={0} value={0}>
                    Select Reason
                  </Option>
                  {reasons.map((reasonDrop) => {
                    return (
                      <Option key={reasonDrop.reason} value={reasonDrop.reason}>
                        {reasonDrop.reason}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </Col>
            <Col
              span={6}
            >
              <Form.Item
                name="remarks"
                label="Remarks"
                rules={[{ required: false, message: 'Missing Remark' }]}
              >
                <TextArea rows={2} />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={24}>
            <Col span={5} style={{ textAlign: 'right', paddingTop: '26px' }}>
              <Form.Item>
                <Button
                  type="primary"
                  htmlType="submit"
                  disabled={disableSubmit}
                  block
                  // onClick={onFinish}
                >
                  Submit
                </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Card>
    </div>
  );
}

export default ProductConvertionForm;
