import React, { useEffect, useState } from 'react';
import { Form, Input, Button, Select, Card, Row, Col, message, DatePicker, Space, Radio } from 'antd';
import './inquiry.css';
import { CountryDto, CountryRequest, CurrencyDto, CusAddressInfo, DeliveryTermsDropDownDto, DestinationDto, PaymentTermsDropDownDto, PlantsDropDown, ShippingTermsDropDownDto } from '@gtpl/shared-models/masters';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import { CountryService, CurrencyService, CustomersService, DeliveryTermsService, DestinationService, EndCustomerService, EndCustomersService, HrmsEmpDetService, PaymentTermsService,UnitcodeService, ShippingTermsService, UomsService } from '@gtpl/shared-services/masters';
import {EnquiryAssessmentUpdateReq, EnquiryByIdModel, EnquirymanagementReq, OrderTypeEnum, SourceFromEnum, enquiryInfo} from '@gtpl/shared-models/enquiry-management'
import InQuiryProductForm from './inquiry-products-form';
import { EnquiriesService } from 'libs/shared-services/enquiry-management/src/lib/enquiries-service';
import moment from 'moment';
import { Link, Redirect, useHistory } from 'react-router-dom';
import EnquiryPackingProductForm from './enquiry-product-packing-details.fom';
import ContainerCapturingAgainstEnquiry from './containers-capturing-info';
import { GlobalVariableValues } from '@gtpl/shared-models/common-models';

const {RangePicker} = DatePicker

/* eslint-disable-next-line */
export interface InquiryFormProps {
  // enquiryId:number
  isUpdate:boolean
  closeForm:() =>void
  enquiryData:any
  enquiryId: number
  updateEnquiryData:(val:EnquirymanagementReq)=> void
}

export function InquiryForm(
  props: InquiryFormProps
) {
  const [inquiryform] = Form.useForm()
  const {Option} = Select
  const [customersData, setcustomersData] = useState<any[]>([]);
  const [endcustomersData, setendcustomersData] = useState<any[]>([]);
  const [employeeData, setEmployeeData] = useState<any[]>([]);
  const [deliveryTerms, setDeliveryTerms] = useState<DeliveryTermsDropDownDto[]>([]);
  const [shippingTerms, setShippingTerms] = useState<ShippingTermsDropDownDto[]>([]);
  const [paymentTerms, setPaymentTerms] = useState<PaymentTermsDropDownDto[]>([]);
  const [currency, setCurrency] = useState<CurrencyDto[]>([]);
  const [destinationData, setdestinationData] = useState<DestinationDto[]>([]);
  const [customerAddress, setCustomerAddress] = useState<any[]>(undefined);
  const [countriesData, setcountriesData] = useState<CountryDto[]>([]);
  const [isManufacturingUnitDisable, setIsManufacturingUnitDisable] = useState<boolean>(false);
  const [factoriesData, setFactoriesData] = useState<PlantsDropDown[]>([]);
  const [endCustomerAddress, setEndCustomerAddress] = useState<CusAddressInfo[]>(undefined);
  const [agentVisble, setAgentVisible] = useState<boolean>(false)
  const [encustomerId, setEncustomerId] = useState<number>(0);
  const [data, setData] = useState<any>([])
  const [enqUpdateData, setEnqUpdateData] = useState([])
  const [ uomData, setUomData ] = useState<any[]>([])
  const enquiryService = new EnquiriesService()
  const customersService = new CustomersService();
  const currencyService = new CurrencyService();
  const endcustomerservice = new EndCustomersService();
  const countriesservice = new CountryService();
  const destinationservice = new DestinationService();
  const employeeService = new HrmsEmpDetService();
  const deliveryTermsService = new DeliveryTermsService();
  const shippingTermsService = new ShippingTermsService();
  const paymentTermsService = new PaymentTermsService();
  const unitService = new UnitcodeService();
  const uomService = new UomsService()
  let history =  useHistory()
  const [ packBomData, setPackBomData] = useState<any>([])
  const [containersAddedStatus,setContainersAddedStatus] = useState<boolean>(false)
  const [containersCount,setContainersCount] = useState<number>()
  const [totalContainers,setTotalContainers] = useState<number>()
  const role = JSON.parse(localStorage.getItem('role'))
  const [processingFactoriesData, setProcessingFactoriesData] = useState<PlantsDropDown[]>([]);
  const [countryId,setCountryId] = useState<number>()

  useEffect(() =>{
    getCustomersData()
    getEndCustomersData()
    getAllPaymentTerms()
    getSalesPersonsData()
    getAllDeliveryterms()
    getAllShippingTerms()
    getAllFinalCountries()
    getPlantsData()
    getCurrencyData()
    getUom()
    getManufacturingPlants()
  },[])

  useEffect(() =>{
      if(props?.isUpdate){
        getEnquiryDetailsById(props?.enquiryId)
    }
  },[props.enquiryId])

  const getUom = ()=>{
    uomService.getAllUomsDropDownData().then((res)=>{
      if(res.status){
        setUomData(res.data)
      }
    })
  }
  
  const getEnquiryDetailsById = (enquiryId) =>{
    enquiryService.getAllEnquiryDetailsById({enquiryid:enquiryId}).then(res =>{
      if(res.status){
        setEnqUpdateData(res.data)
      }else{
        setEnqUpdateData([])
      }
    })
  }

  useEffect(()=>{
    if(enqUpdateData){
      console.log(enqUpdateData,'==')
      inquiryform.setFieldsValue({
        enquiryId: enqUpdateData[0]?.enquiryId,
        enquiryNumber : enqUpdateData[0]?.enquiryNumber,
          // orderType: enqUpdateData[0]?.orderType,
          sourceFrom: enqUpdateData[0]?.sourceFrom,
          agentId: enqUpdateData[0]?.agentId,
          buyerId: enqUpdateData[0]?.buyerId,
          salePersonId: enqUpdateData[0]?.salePersonId,
          enquiryDate: moment(enqUpdateData[0]?.enquiryDate),
          agentAddressId: enqUpdateData[0]?.agentAddressId,
          buyerAddressId: enqUpdateData[0]?.buyerAddressId,
          countryId: enqUpdateData[0]?.countryId,
          destinationId: enqUpdateData[0]?.destinationId,
          etd: [enqUpdateData[0]?.etd ? moment(enqUpdateData[0]?.etd) : null, enqUpdateData[0]?.toEtd ? moment(enqUpdateData[0]?.toEtd) : null],
          eta: enqUpdateData[0]?.eta ? moment(enqUpdateData[0]?.eta) : null,
          deliveryTermsId: enqUpdateData[0]?.deliveryTermsId,
          paymentTermsId: enqUpdateData[0]?.paymentTermsId,
          shipmentTermsId: enqUpdateData[0]?.shipmentTermsId,
          processingUnitId: enqUpdateData[0]?.processingUnitId,
          manufacturingUnitId: enqUpdateData[0]?.manufacturingUnitId,
          currencyId: enqUpdateData[0]?.currencyId,
          noOfContainers: enqUpdateData[0]?.noOfContainers,
          salesCommission: enqUpdateData[0]?.salesCommission,
          remarks: enqUpdateData[0]?.remarks,
          uomId:enqUpdateData[0]?.uomId,
          isFOB:enqUpdateData[0]?.isFOB
      })
      setCountryId(enqUpdateData[0]?.countryId)
      getendCustomerAddress(enqUpdateData[0]?.buyerId)
      getFinalDestinationData(enqUpdateData[0]?.countryId)
      setContainersCount(Number(enqUpdateData[0]?.noOfContainers))
    }
  },[enqUpdateData])

  const countryOnchange = (selectedValue) => {
    console.log(selectedValue)
    setCountryId(selectedValue)
    inquiryform.setFieldsValue({destinationId:undefined})
    getFinalDestinationData(selectedValue)
  }

  const endCustomerOnchange = (value) =>{
    getendCustomerAddress(value)
    setEncustomerId(value)
  }

  // currency[0].currencyId
  const getCurrencyData = () => {
    currencyService.getAllActiveCurrencys().then((res) => {
      if (res.status) {
        setCurrency(res.data);
      } else {
        setCurrency([]);
      }
    }).catch((err) => {
      AlertMessages.getErrorMessage(err.message);
      setCurrency([]);
    });
  }

  const getendCustomerAddress = (value) => {
    endcustomerservice.getEndCustomerDataById({endCustomerId:value,isActive:true}).then((res) => {
      if (res.status) {
        setEndCustomerAddress(res.data.addressInfo);
      } else {
        setEndCustomerAddress(undefined);
      }
    }).catch((err) => {
      AlertMessages.getErrorMessage(err.message);
      setEndCustomerAddress(undefined);
    });
  }

  const getPlantsData = () => {  
      unitService.getAllMainPlants().then((res) => {
        if (res.status) {
          setProcessingFactoriesData(res.data);
        } else {
          setProcessingFactoriesData([]);
        }
      }).catch((err) => {
        AlertMessages.getErrorMessage(err.message);
        setProcessingFactoriesData([]);
      });
  }

  const getManufacturingPlants = () => {
    unitService.getAllManufacturingPlants().then((res) => {
      if (res.status) {
        // setFactoriesData(res.data);
        setFactoriesData(res.data);
      } else {
        // if (res.intlCode) {
        //   AlertMessages.getErrorMessage(res.internalMessage);
        // } else {
        //   AlertMessages.getErrorMessage(res.internalMessage);
        // }
        setFactoriesData([]);
      }
    }).catch((err) => {
      AlertMessages.getErrorMessage(err.message);
      setFactoriesData([]);
    });
  }

  const getFinalDestinationData = (selectedCountry) => {
    destinationservice.getDestinationsByCountry(new CountryRequest(selectedCountry)).then((res) => {
      if (res.status) {
        setdestinationData(res.data);
      } else {
        setdestinationData([]);
      }
    }).catch((err) => {
      AlertMessages.getErrorMessage(err.message);
      setdestinationData([]);
    });
  }

  const getCustomerAddress = (value) => {
    customersService.getCustomerDataById({custId:value}).then((res) => {
      if (res.status) {
        setCustomerAddress(res.data.cusAddressInfo);
      } else {
      
        setCustomerAddress(undefined);
      }
    }).catch((err) => {
      AlertMessages.getErrorMessage(err.message);
      setCustomerAddress(undefined);
    });
  }

  const getAllFinalCountries = () => {
    countriesservice.getAllActiveCountries().then((res) => {
      if (res.status) {
        setcountriesData(res.data);
      } else {
        setcountriesData([]);
      }
    }).catch((err) => {
      AlertMessages.getErrorMessage(err.message);
      setcountriesData([]);
    });
  }

  const agentOnchange = (value) => {
    // setCustomerAddress(undefined);
    getCustomerAddress(value);
  }

  const getCustomersData = () => {
    customersService.getAllActiveCustomers().then((res) => {
      if (res.status) {
        setcustomersData(res.data);
      } else {
        setcustomersData([]);
      }
    }).catch((err) => {
      AlertMessages.getErrorMessage(err.message);
      setcustomersData([]);
    });
  }
  const getEndCustomersData = () => {
    endcustomerservice.getAllActiveEndCustomers().then((res) => {
      if (res.status) {
        setendcustomersData(res.data);
      } else {
        setendcustomersData([]);
      }
    }).catch((err) => {
      AlertMessages.getErrorMessage(err.message);
      setendcustomersData([]);
    });
  }
  const getSalesPersonsData = () => {
    employeeService.getAllActiveEmployees().then((res) => {
      if (res.status) {
        setEmployeeData(res.data);
      } else {
        setEmployeeData([]);
      }
    }).catch((err) => {
      AlertMessages.getErrorMessage(err.message);
      setEmployeeData([]);
    });
  }

  const getAllDeliveryterms = () => {
    deliveryTermsService.getAllDeliveryTermsDropDown().then((res) => {
      if (res.status) {
        setDeliveryTerms(res.data);
      } else {
        setDeliveryTerms([]);
      }
    }).catch((err) => {
      AlertMessages.getErrorMessage(err.message);
      setDeliveryTerms([]);
    });
  }

  const getAllShippingTerms = () => {
    shippingTermsService.getAllShippingTermsDropDown().then((res) => {
      if (res.status) {
        setShippingTerms(res.data);
      } else {
        setShippingTerms([]);
      }
    }).catch((err) => {
      AlertMessages.getErrorMessage(err.message);
      setShippingTerms([]);
    });
  }

  const getAllPaymentTerms = () => {
    paymentTermsService.getAllpaymentTermsDropDown().then((res) => {
      if (res.status) {
        setPaymentTerms(res.data);
      } else {
        setPaymentTerms([]);
      }
    }).catch((err) => {
      AlertMessages.getErrorMessage(err.message);
      setPaymentTerms([]);
    });
  }
 
  const sourceFromOnchange = (value) =>{
    // console.log(value)
    if(value == SourceFromEnum.AGENT){
    setAgentVisible(true)
    }else{
      setAgentVisible(false)
    }
  }
  
  const orderTypeOnchange =(value) =>{
  // console.log(value)
  }

  const hangeProductDetails = (productDetails) =>{
    console.log(productDetails)
    setData((prevData) => ({ ...prevData, productDetails }));
    // setData([...data,productDetails])
  }

  const productContainersHandler = (productContainerInfo) => {
    console.log(productContainerInfo,'productContainerInfo')
    let total = 0
    productContainerInfo.productDetails.map(e => {
      total += e.noOfContainers ? Number(e.noOfContainers) : 0
    })
    setTotalContainers(total)
    setData(productContainerInfo)
  }

  const handlePackBom = (packBomDetails)=>{
    console.log(packBomDetails,',,,,,,,,,,,,,,,,,,,,')
    setPackBomData((prevData)=>({...prevData, packBomDetails }))
  }

const onFinish = (val) =>{
  console.log(val)
  inquiryform.validateFields().then(res =>{
    console.log(val.etd,'etd')
    const etd = val.etd[0] != undefined && val.etd[0] != null ? moment(val.etd[0].startOf('month')).format('YYYY-MM-DD') : null
    const toEtd = val.etd[1] != undefined && val.etd[1]!= null ? moment(val.etd[1].endOf('month')).format('YYYY-MM-DD') : null
    console.log(etd,toEtd,'====')
    // console.log(data.productDetails)
    const req = new EnquirymanagementReq(undefined,val.sourceFrom,val.agentId,val.buyerId,val.salePersonId,moment(val.enquiryDate).format('YYYY-MM-DD'),val.noOfContainers?val.noOfContainers:undefined,val.agentAddressId,val.buyerAddressId,val.countryId,val.destinationId,etd,toEtd,val.eta ? moment(val.eta).format('YYYY-MM-DD') : null,val.deliveryTermsId,val.paymentTermsId,val.shipmentTermsId,val.processingUnitId,val.manufacturingUnitId,val.currencyId,val.remarks,role,'',undefined,Number(localStorage.getItem('unit_id')),undefined,val.salesCommission,val.uomId,data.productDetails,null,val.isFOB)
    console.log(req,'=========================')
    if(req.productDetails.length >0 ){
      if(containersAddedStatus){
        console.log(containersCount)
        console.log(totalContainers)
        if(containersCount == totalContainers){
          enquiryService.createEnquiry(req).then(res =>{
            if(res.status){
              message.success(res.internalMessage)
              history.push('/inquiry-management-view')
            }else{
              message.error(res.internalMessage)
            }
          })
        }else{
          message.info('Containers in grouping should be equal to no of containers')
        }
      }else{
        message.info('Please add conatiner details')
      }
    }else{
      message.info('Please Add remaining details')
    }
    })
  }

  // useEffect(())

  const saveData = (val)=>{
    console.log(val,'testttttttttttttttttttttttttttttttt')
    if(props.isUpdate){
     console.log(val,',,,,',val.enquiryNumber)


     const etd = val.etd[0] != undefined && val.etd[0] != null  ? moment(val.etd[0]?.startOf('month')).format('YYYY-MM-DD') : null
     console.log(val.etd,'elevennn');

     const toEtd = val.etd[1] != undefined && val.etd[1] != null ? moment(val.etd[1]?.endOf('month')).format('YYYY-MM-DD') : null
  
  
    



      const req = new EnquirymanagementReq(val.enquiryNumber,val.sourceFrom,val.agentId,
        val.buyerId,val.salePersonId,moment(val.enquiryDate).format('YYYY-MM-DD'),val.noOfContainers,val.agentAddressId,
        val.buyerAddressId,val.countryId,val.destinationId,
        etd,toEtd,val.eta ? moment(val.eta).format('YYYY-MM-DD') : null,
        val.deliveryTermsId,val.paymentTermsId,val.shipmentTermsId,
        val.processingUnitId,val.manufacturingUnitId,val.currencyId,
        val.remarks,role,role,undefined,undefined,undefined,val.salesCommission,val.uomId,data.productDetails,val.enquiryId,val.isFOB)

      props.updateEnquiryData(req)
    }else{
      console.log('create',val)
      onFinish(val)
    }
  }

  const handleDisabledDate = (current) => {
    // Disable dates before today
    return current && current < moment().startOf('day');
  };

  const containersAddHandler = (val) => {
    if(val){
      setContainersAddedStatus(true)
    }
  }

  const onNoOfContainersChange = (e) => {
    setContainersCount(Number(e.target.value))
  }

  const onshipmenttermchange = (e) => {
    if(e == GlobalVariableValues.FOBShippmenttermId){
      inquiryform.setFieldsValue({isFOB : false})
    }else{
      inquiryform.setFieldsValue({isFOB : true})
    }
  }
  return (
    <Card title={<span style={{ color: 'white' }}>Enquiry Management</span>} style={{ textAlign: 'center' }} headStyle={{ backgroundColor: '#69c0ff', border: 0 }} extra={props.isUpdate ? null : <Link to='/inquiry-management-view'><span style={{ color: 'white' }}><Button className='panel_button'>View</Button></span></Link>}>
      <Form form={inquiryform} layout='vertical' onFinish={saveData}>
        <Form.Item hidden name={'enquiryId'}><Input></Input></Form.Item>
        <Form.Item hidden name={'enquiryNumber'}><Input></Input></Form.Item>
        <Row gutter={24}>
          {/* <Col xs={24} sm={12} md={8} lg={6} xl={4}>
            <Form.Item name={'orderType'} label={'Order Type'}
            rules={[{required:true,message:'Order Type Is Required'}]}
            >
              <Select placeholder='Select Order Type' allowClear showSearch onChange={orderTypeOnchange}
              >
               {Object.values(OrderTypeEnum).map((key,value) =>{
                return <Option key={key} value={key}>{key}</Option>
               })}
              </Select>
            </Form.Item>
          </Col> */}
          <Col xs={24} sm={12} md={8} lg={6} xl={4}>
            <Form.Item name={'sourceFrom'} label={'Source From'}
            rules={[{required:true,message:'Source From Is Required'}]}
            >
              <Select placeholder='Select Source From' 
              allowClear
               showSearch
               onChange={sourceFromOnchange}
              >
                {Object.values(SourceFromEnum).map((key,value) =>{
                  return <Option key={key} value={key}>{key}</Option>
                })}
              </Select>
            </Form.Item>
          </Col>
          {agentVisble ?
            <Col xs={24} sm={12} md={8} lg={6} xl={4}
             >
            <Form.Item name={'agentId'} label={'Agent'}
             rules={[{required:inquiryform.getFieldValue('sourceFrom') == SourceFromEnum.AGENT?true:false}]} 
             >
            <Select
                showSearch
                placeholder="Select Agent"
                optionFilterProp="children"
                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                allowClear
                onChange={agentOnchange}
                >
                {customersData.map(dropData => {
                  return <Option value={dropData.custId}>{dropData.clientName}</Option>
                })}
              </Select>
            </Form.Item>
            </Col>
            :<></>
          }
         
          <Col xs={24} sm={12} md={8} lg={6} xl={4}>
          <Form.Item name="buyerId"  label="Buyer" 
          // rules={[{ required: true, message: 'Missing  Buyer' }]}
          >
              <Select
                showSearch
                optionFilterProp="children"
                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select  Buyer"
                allowClear
                onChange={endCustomerOnchange}
              >
                {endcustomersData.map(dropData => {
                  return <Option value={dropData.endCustomerId}>{dropData.endCustomerName}</Option>
                })}
              </Select>
              </Form.Item>
          </Col> 
          <Col  xs={24} sm={12} md={8} lg={6} xl={4}>
          <Form.Item name="salePersonId"  label="Sale Person Name" 
          // rules={[{ required: true,message: 'Missing sale person' }]}
          >
              <Select
              showSearch
              optionFilterProp="children"
              filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select sale person"
                allowClear
                style={{width:'100%'}}
              >
                {employeeData.map(dropData => {
                  return <Option value={dropData.employeeId}>{`${dropData.employeeName}`}</Option>
                })}
              </Select>
            </Form.Item>
          </Col>
          <Col xs={24} sm={12} md={8} lg={6} xl={4}>
          <Form.Item  name="enquiryDate" label="Enquiry Date"
          //  rules={[{ required: true,message: 'Missing Inquiry date' }]}
           >
              <DatePicker 
                style={{ width: '100%' }}
                 />
            </Form.Item>
          </Col>
          {agentVisble ?
          <Col xs={24} sm={12} md={8} lg={6} xl={4}>
          <Form.Item name="agentAddressId"  label="Agent Address" rules={[{ required: agentVisble,message:'Agent Address Required' }]}>
              <Select
              showSearch
              optionFilterProp="children"
              filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select Agent address"
                allowClear
                dropdownMatchSelectWidth={false}
              >
                {customerAddress===undefined?'': customerAddress.map(dropData => {
                  return <Option key={dropData.addressId} name={dropData.addLineOne+ ',' + dropData.addLineTwo+ ',' +dropData.addLineThree+ ',' +dropData.addLineFour} value={dropData.addressId}>{dropData.addLineOne+ ',' + dropData.addLineTwo+ ',' +dropData.addLineThree+ ',' +dropData.addLineFour}</Option>
                })}
              </Select>
            </Form.Item>
          </Col>:<></>}
          <Col xs={24} sm={12} md={8} lg={6} xl={4}>
          <Form.Item name="buyerAddressId"  label="Buyer Address" 
          // rules={[{ required: true,message:'Buyer address is required' }]}
          >
              <Select
              showSearch
              optionFilterProp="children"
              filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select Buyer address"
                allowClear
                dropdownMatchSelectWidth={false}
              >
                  {endCustomerAddress===undefined?'': endCustomerAddress.map(dropData => {
                  return <Option key ={dropData.addressId} name={dropData.addLineOne+ ',' + dropData.addLineTwo+ ',' +dropData.addLineThree+ ',' +dropData.addLineFour} value={dropData.addressId}>{dropData.addLineOne+ ',' + dropData.addLineTwo+ ',' +dropData.addLineThree+ ',' +dropData.addLineFour}</Option>
                })}
              </Select>
            </Form.Item>
          </Col>
          <Col  xs={24} sm={12} md={8} lg={6} xl={4}>
          <Form.Item name="countryId" label="Country" rules={[{ required: true,message: 'Missing country' }]}>
              <Select
                showSearch
                optionFilterProp="children"
                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select Country"
                onChange={countryOnchange}
                allowClear
              >
                {countriesData.map(dropData => {
                  return <Option value={dropData.countryId}>{dropData.countryName}</Option>
                })}
              </Select>
            </Form.Item>
          </Col>
          <Col xs={24} sm={12} md={8} lg={6} xl={4}>
          <Form.Item name="destinationId"  label="Final Destination" rules={[{ required: true,message: 'Missing destination' }]}>
              <Select
                showSearch
                optionFilterProp="children"
                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select Destination"
                allowClear
              >
                {destinationData.map(dropData => {
                  return <Option value={dropData.destinationId}>{dropData.destinationName}</Option>
                })}
              </Select>
            </Form.Item>
          </Col>
          <Col xs={24} sm={12} md={8} lg={6} xl={5}>
          <Form.Item  name="etd" label="ETD" tooltip="Estimated Time Of Departure">
              <RangePicker picker="month" disabledDate={handleDisabledDate} style={{ width: '100%' }}
               />
            </Form.Item>
          </Col>
          <Col xs={24} sm={12} md={8} lg={6} xl={4}>
          <Form.Item name="eta" label="ETA"  tooltip="Estimated Time Of Arrival">
              <DatePicker style={{width:'100%'}}/>
            </Form.Item>
          </Col>
          <Col xs={24} sm={12} md={8} lg={6} xl={4}>
          <Form.Item name="deliveryTermsId"  label="Delivery Terms" 
          // rules={[{ required: true,message: 'Missing delivery terms' }]}
          >
              <Select
                showSearch
                optionFilterProp="children"
                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select Delivery terms"
                allowClear
              >
                {deliveryTerms.map(dropData => {
                  return <Option value={dropData.deliveryTermsId}>{dropData.deliveryTermsName}</Option>
                })}
              </Select>
            </Form.Item>  
          </Col>
          <Col xs={24} sm={12} md={8} lg={6} xl={4}>
          <Form.Item name="paymentTermsId"  label="Payment Terms" 
          // rules={[{ required: true ,message: 'Missing  payment terms'}]}
          >
              <Select
                showSearch
                optionFilterProp="children"
                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select Payment Terms"
                allowClear
              >
                {paymentTerms.map(dropData => {
                  return <Option value={dropData.paymentTermsId}>{dropData.paymentTermsName}</Option>
                })}
              </Select>
            </Form.Item>
          </Col>
          <Col xs={24} sm={12} md={8} lg={6} xl={4}>
          <Form.Item name="shipmentTermsId"  label="Shipment Terms" rules={[{ required: true,message: 'Missing shipment terms' }]} >
              <Select
                showSearch
                optionFilterProp="children"
                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select Shipment terms"
                allowClear
                onChange={onshipmenttermchange}
              >
                {shippingTerms.map(dropData => {
                  return <Option value={dropData.shiptermId}>{dropData.shipmenttermName}</Option>
                })}
              </Select>
            </Form.Item>
          
          </Col>
          <Col xs={24} sm={12} md={8} lg={6} xl={4}>
          <Form.Item name="processingUnitId"   label="Processing Unit" 
          // rules={[{ required: true,message: 'Missing Processing Unit' }]} 
          >
              <Select
                showSearch
                optionFilterProp="children"
                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select Processing Unit"
                allowClear
              >
                {processingFactoriesData.map(dropData => {
                  return <Option value={dropData.plantId}>{dropData.plantCode}</Option>
                })}
              </Select>
            </Form.Item>
          
         </Col>
         <Col xs={24} sm={12} md={8} lg={6} xl={4}>
         <Form.Item name="manufacturingUnitId"   label="Export Unit" 
        //  rules={[{ required: true,message: 'Missing Export Unit' }]} 
         >
              <Select
                showSearch
                optionFilterProp="children"
                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select Export Unit"
                allowClear
                disabled={isManufacturingUnitDisable}
              >
                {factoriesData.map(dropData => {
                  return <Option value={dropData.plantId}>{dropData.plantName}</Option>
                })}
              </Select>
            </Form.Item>
         </Col>
         <Col xs={24} sm={12} md={8} lg={6} xl={4}>
         <Form.Item name="currencyId"  label="Currency" rules={[{ required: true,message: 'Missing currency' }]} >
              <Select
                showSearch
                optionFilterProp="children"
                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                placeholder="Select Currency"
                allowClear
              >
                {currency.map(currencydropData => {
                  return <Option value={currencydropData.currencyId}>{currencydropData.currencyName}</Option>
                })}
              </Select>
            </Form.Item>
         </Col>
         <Col xs={24} sm={12} md={8} lg={6} xl={4}>
          <Form.Item name={'noOfContainers'} label={'No.Of Containers'} rules={[{required:true,message:'No of containers is mandatory'}]}>
            <Input type='number' placeholder='Enter Containers' onChange={onNoOfContainersChange}/>
          </Form.Item>
          </Col>
          <Form.Item name={'isFOB'} label={'FOB Consideration'} rules={[{required:true,message:'FOB consideration is mandatory'}]} hidden>
              <Radio.Group >
                <Radio value={true}>Yes</Radio>
                <Radio value={false}>No</Radio>
              </Radio.Group>
          </Form.Item>
          {/* <Col xs={24} sm={12} md={8} lg={6} xl={4}>
          <Form.Item name={'salesCommission'} label={'Sales Commission (%) cents/lb'}>
            <Input type='number'/>
          </Form.Item>
          </Col> */}
          <Col xs={24} sm={12} md={6} lg={6} xl={6}>
            <Space>
              <Form.Item name='salesCommission' label={'Sales Commission (cents)'} >
              <Input placeholder="Enter Sales Commission%" allowClear type='number' />
              </Form.Item>
              <Form.Item name='uomId' label={'UOM'}>
                <Select allowClear placeholder="Select UOM">
                  {uomData.map((e) => (
                    <Option key={e.uomId} value={e.uomId}>
                      {e.uomName}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Space>
          </Col>
          <Col xs={24} sm={24} md={24} lg={12} xl={10} style={{ maxWidth: '500px' }}>
          <Form.Item name={'remarks'} label={'Remarks'}>
            <Input.TextArea rows={1} placeholder='Enter Remarks' />
          </Form.Item>
          </Col>
        </Row>
        <Row gutter={24}>
        <Col xs={24} sm={12} md={8} lg={6} xl={24}>
    < InQuiryProductForm endCustomerId={encustomerId} productDetails={hangeProductDetails} 
    // updateDetails={enqUpdateData[0]?.productDetails} 
    enquiryId={props.enquiryId ?props.enquiryId:0} country={countryId}/>
    </Col>
      </Row>
      {/* <Row>
        <EnquiryPackingProductForm packBomDetails={handlePackBom}
        enquiryId={props.enquiryId ?props.enquiryId:0}
        //  updateDetails={enqUpdateData[0]?.enquiryPackBom}
         />
      </Row> */}
      {
        data?.productDetails?.length > 0 ? (<>
         <Row gutter={24}>
        <Col xs={24} sm={12} md={8} lg={6} xl={24}>
        <ContainerCapturingAgainstEnquiry productsInfo={data?.productDetails} productContainersInfo={productContainersHandler} containersAddHandler={containersAddHandler} containersCount={containersCount} pageName='enquiryForm'/>
        </Col>
      </Row>
        </>) : (<></>)
      }
      
      <br></br>
      <Row justify='end'>
        <Button type='primary' htmlType='submit'>Submit</Button>
      </Row>
      </Form>
    
     
    </Card>
  );
}

export default InquiryForm;
