
import React, { useEffect, useState } from 'react';
import { Form, Input, Button, Select, Card, Row, Col, Space, Upload, UploadProps } from 'antd';
import { Brands, CountryDto, CurrencyDto, CustomerACcountTypes, EndCustomerDto, EndCustomerType, MasterBrandsDropDownDto, PaymentmodesDto, RegistrationType, StatesDto, StockItemCategoryModelDto, TcsApplicable } from '@gtpl/shared-models/masters';
import { MinusCircleOutlined, PlusOutlined, LoadingOutlined } from '@ant-design/icons';
import { AlertMessages } from '@gtpl/shared-utils/alert-messages';
import './end-customer-form.css';
import { CountryService, CurrencyService, EndCustomersService, MasterBrandService, StatesServices, StockItemCategoryServices } from '@gtpl/shared-services/masters';
import { PaymentmodesService } from '@gtpl/shared-services/masters';
import { Link, useHistory } from 'react-router-dom';
import { UploadOutlined } from '@ant-design/icons'
import TextArea from 'antd/lib/input/TextArea';
import appSettings from 'apps/services/config';
import { BrandsInfo } from 'libs/shared-models/masters/src/lib/endCuctomer/brands-model';
import { DocumentsListRequest } from '@gtpl/shared-models/logistics';
const countryService = new CountryService();
const currencyService = new CurrencyService();
const stateServices = new StatesServices()
const categoryServices = new StockItemCategoryServices()



/* eslint-disable-next-line */
const { Option } = Select;
const layout = {
  labelCol: {
    span: 10,
  },
  wrapperCol: {
    span: 8,
  },
};


const tailLayout = {
  wrapperCol: {
    offset: 10,
    span: 10,
  },
};



export interface EndCustomersFormProps {
  endCustomersData: EndCustomerDto;
  updateDetails: (endCustomers: EndCustomerDto, filelist: any) => void;
  isUpdate: boolean;
  closeForm: () => void;
}

export function EndCustomersForm(props: EndCustomersFormProps) {
  let accountTypes = CustomerACcountTypes;
  let history = useHistory();

  const [form] = Form.useForm();
  const service = new EndCustomersService;
  const paymentModeService = new PaymentmodesService;
  const [selectedpaymentmode, setSelectedPaymentModes] = useState<number>(null);
  const [paymentModeData, setPaymentModeData] = useState<PaymentmodesDto[]>([]);
  const [countries, setCountries] = useState<CountryDto[]>([]);
  const [currencies, setCurrencies] = useState<CurrencyDto[]>([]);
  const [selectedCurrency, setSelectedCurrency] = useState<number>(null);
  const [selectedCountries, setSelectedCountries] = useState<number>(null);
  const [brandsDropDown, setBrandsDropDown] = useState<MasterBrandsDropDownDto[]>([]);
  const [brandsInfo, setBrandsInfo] = useState<Brands[]>([]);
  const [brandsData, setBrandsData] = useState<BrandsInfo[]>([]);
  const [keyValues, setKeyValues] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(false);
  const [imageUrl, setImageUrl] = useState('');
  const [disable, setDisable] = useState<boolean>(false)
  const brandsService = new MasterBrandService()
  const [fieldsData, setFieldsData] = useState<DocumentsListRequest>(undefined);
  const [states, setStates] = useState<StatesDto[]>([]);
  const [selectedStates, setSelectedStates] = useState<number>(null)
  const [inputVisible, setInputVisible] = useState<boolean>(false)
  const [selectedCategory, setSelectedCategory] = useState<number>(null)
  const [category, setCategory] = useState<StockItemCategoryModelDto[]>([]);


  const [selectedType, setSelectedType] = useState<RegistrationType>(
    RegistrationType.composition
  );

  const [selectedEndCustomerType, setSelectedEndCustomerType] = useState<EndCustomerType>(
    EndCustomerType.domestic
  );

  const [selectedTcsApplicable, setSelectedTcsApplicable] = useState<TcsApplicable>(
    TcsApplicable.Yes
  );



  const [filelist, setfilelist] = useState<any>(props.isUpdate ? [{
    name: props.endCustomersData.fileName,
    status: 'done',
    url: appSettings.brand_file_path + props.endCustomersData.filePath,
  }] : []);
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload Logo</div>
    </div>
  );

  useEffect(() => {
    getBrandData();
    getCurrenciesData()
    getCountriesData()
    getStatesData()
    getEndCustomerCategories()
    console.log(props.endCustomersData);

  }, [])

  const uploadFieldProps: UploadProps = {
    multiple: false,
    onRemove: file => {
      setfilelist([]);
      setImageUrl('');
    },
    beforeUpload: (file: any) => {
      if (!file.name.match(/\.(png|jpeg|PNG|jpg|JPG)$/)) {
        AlertMessages.getErrorMessage("Only png,jpeg,jpg files are allowed!");
        return true;
      }
      var reader = new FileReader();
      reader.readAsArrayBuffer(file);
      reader.onload = data => {
        if (filelist.length == 1) {
          AlertMessages.getErrorMessage("You Cannot Upload More Than One File At A Time");
          return true;
        } else {
          setfilelist([file]);
          getBase64(file, imageUrl =>
            setImageUrl(imageUrl)
          );
          return false;
        }
      }
    },
    progress: {
      strokeColor: {
        '0%': '#108ee9',
        '100%': '#87d068',
      },
      strokeWidth: 3,
      format: percent => `${parseFloat(percent.toFixed(2))}%`,
    },
    fileList: filelist,
  };

  const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  }

  const getBrandData = () => {
    brandsService.getAllMasterBrandsDropDown().then(res => {
      if (res.status) {
        setBrandsDropDown(res.data);
      } else {
        if (res.intlCode) {
          AlertMessages.getErrorMessage(res.internalMessage);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
      }
    }).catch(err => {
      AlertMessages.getErrorMessage(err.message);
    })
  }

  const getEndCustomerCategories = () => {
    categoryServices.getEndCustomerCategories().then((res) => {
      if (res.status) {
        setCategory(res.data);
      } else {
        if (res.intlCode) {
          AlertMessages.getErrorMessage(res.internalMessage);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
        setCategory([]);
      }
    })
      .catch((err) => {
        AlertMessages.getErrorMessage(err.message);
        setCategory([]);
      });
  }

  const getCurrenciesData = () => {
    currencyService.getAllActiveCurrencys().then((res) => {
      if (res.status) {
        setCurrencies(res.data);
      } else {
        if (res.intlCode) {
          AlertMessages.getErrorMessage(res.internalMessage);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
        setCurrencies([]);
      }
    })
      .catch((err) => {
        AlertMessages.getErrorMessage(err.message);
        setCurrencies([]);
      });
  }


  const getCountriesData = () => {
    countryService.getAllCountries().then((res) => {
      if (res.status) {
        setCountries(res.data);
      } else {
        if (res.intlCode) {
          AlertMessages.getErrorMessage(res.internalMessage);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
        setCountries([]);
      }
    })
      .catch((err) => {
        AlertMessages.getErrorMessage(err.message);
        setCountries([]);
      });
  }


  const getStatesData = () => {
    stateServices.getAllStates().then((res) => {
      if (res.status) {
        setStates(res.data);
      } else {
        if (res.intlCode) {
          AlertMessages.getErrorMessage(res.internalMessage);
        } else {
          AlertMessages.getErrorMessage(res.internalMessage);
        }
        setStates([]);
      }
    })
      .catch((err) => {
        AlertMessages.getErrorMessage(err.message);
        setStates([]);
      });
  }


  // const uploadLogoDetails = () => {
  //   form.validateFields().then(formDetails => {
  //     console.log(formDetails);
  //     if (filelist.length > 0) {
  //       const formData = new FormData();
  //       filelist.forEach((file: any) => {
  //         formData.append('file', file);
  //       });
  //        formData.append('endCustomerId',(formDetails.endCustomerId)?formDetails.endCustomerId:"")
  //         formData.append('endCustomerCode',formDetails.endCustomerCode)
  //         formData.append('endCustomerName',formDetails.endCustomerName)
  //         formData.append('currencyId',formDetails.currencyId)
  //         formData.append('isActive',formDetails.isActive)
  //         formData.append('addressInfo',formDetails.addressInfo)
  //         formData.append('brandsInfo',formDetails.brandsInfo)
  //         formData.append('currenciesInfo',formDetails.currenciesInfo)
  //       formData.append('filePath', formDetails.filePath)
  //       formData.append('fileName', formDetails.fileName)
  //       // formData.append('createdUser',localStorage.getItem("createdUser"))
  //       service.logoUpload(formData).then(res => {
  //         if (res.status) {
  //           form.resetFields();
  //           setfilelist([]);
  //           if (!props.isUpdate) {
  //             AlertMessages.getSuccessMessage('Created Successfully');
  //             history.push('/EndCustomerview');
  //           } else {
  //             props.closeForm();
  //             window.location.reload();
  //             AlertMessages.getSuccessMessage('Updated Successfully');

  //           }
  //         }
  //       })
  //     }

  //   })
  // }
  console.log(states, 'statessss')
  const saveEndCustomer = (endCustomersData: EndCustomerDto) => {
    setDisable(true)

    const bransDetails = form.getFieldValue('brandsInfo') ? form.getFieldValue('brandsInfo') : [];
    // console.log(bransDetails),
    endCustomersData.brandsInfo = null;
    for (const brand of bransDetails) {
      let added = false;
      for (const brandInfo of brandsInfo) {
        if (!added) {
          if (brand.masterBrandId == brandInfo.brandId) {
            added = true;
            const brands: BrandsInfo = {
              brandId: null,
              brandName: brandInfo.brandName,
              masterBrandId: brandInfo.brandId
            }
            console.log(brands);
            brandsData.push(brands);
            setBrandsData(brandsData);
          }
        }
      }
    }
    endCustomersData.brandsInfo = brandsData;

    form.validateFields().then(req => {
      const formData = new FormData();
      console.log(req);
      req.fileName = req.file?.fileList[0]?.name;
      formData.append('file', req.file?.fileList[0]);
      console.log(formData);
      console.log(req);
      service.createEndCustomers(endCustomersData).then(res => {
        if (res.status) {
          if (filelist.length > 0) {
            const formData = new FormData();
            filelist.forEach((file: any) => {
              formData.append('file', file);
            });
            formData.append('endCustomerId', `${res.data.endCustomerId}`)
            service.logoUpload(formData).then(fileres => {
              res.data.filePath = fileres.data;
              AlertMessages.getSuccessMessage(res.internalMessage)
              history.push("/EndCustomerview");
              onReset();
            })
          }
          history.push("/EndCustomerview");
          onReset();
        } else {
          if (res.intlCode) {
            AlertMessages.getErrorMessage(res.internalMessage);
          } else {
            AlertMessages.getErrorMessage(res.internalMessage);
          }
        }
      }).catch(err => {
        setDisable(false)
        AlertMessages.getErrorMessage(err.message);
      })
      setBrandsData([]);
    })
  }



  const saveData = (values: EndCustomerDto) => {
    setDisable(false)
    // AlertMessages.getSuccessMessage('Created Successfully');
    // form.validateFields().then(formDetails => {
    //   console.log(formDetails);
    //   if (filelist.length > 0) {
    //     const formData = new FormData();
    //     filelist.forEach((file: any) => {
    //       formData.append('file', file);
    //     });
    // Object.keys(formDetails).forEach(key => {
    //   formData.append(key, (formDetails[key]) ? formDetails[key] : "");
    //   if (key == 'createdUser') {
    //     formData.append(key, localStorage.getItem("createdUser"))
    //   }
    // })
    // service.logoUpload(formData).then(res => {
    //   if (res.status) {
    //     form.resetFields();
    //     setfilelist([]);
    //     if (!props.isUpdate) {
    //       AlertMessages.getSuccessMessage('Created Successfully');
    //       history.push('/EndCustomerview');
    //     } else {
    //       props.closeForm();
    //       window.location.reload();
    //       AlertMessages.getSuccessMessage('Updated Successfully');
    //     }
    //   }
    // })
    //   }

    // })
    if (props.isUpdate) {
      //s  setfilelist([]);
      //props.updateDetails(values,filelist);
      const bransDetails = form.getFieldValue('brandsInfo');
      values.brandsInfo = [];
      for (const brand of bransDetails) {
        if (!brand.brandId) {
          let added = false;
          for (const brandInfo of brandsInfo) {
            if (!added) {
              if (brand.masterBrandId == brandInfo.brandId) {
                added = true;
                const brands: BrandsInfo = {
                  brandId: null,
                  brandName: brandInfo.brandName,
                  masterBrandId: brandInfo.brandId
                }
                values.brandsInfo.push(brands);
              }
            }
          }
        } else {
          values.brandsInfo.push(brand);
        }
      }
      props.updateDetails(values, filelist);
    } else {
      setDisable(false)
      saveEndCustomer(values);
    }

  };
  let createdUser = "";
  if (!props.isUpdate) {
    createdUser = localStorage.getItem("createdUser");
  }
  const onReset = () => {
    form.resetFields();
  };
  const handleCurrency = (value) => {
    setSelectedCurrency(value);
  }

  const handleCountries = (value, option) => {
    console.log(option)
    setSelectedCountries(value);
    if (option?.name === "INDIA") {
      setInputVisible(true)
    }
    else {
      setInputVisible(false)
    }
  }

  const handleStates = (value) => {
    setSelectedStates(value);
  }


  const onFocus = () => {
    console.log('focus');
  }

  const onSearch = (val) => {
    console.log('search:', val);
  }
  const onBlur = () => {
    console.log('blur');
  }

  const setBrandName = (values, brandData) => {
    const brands = new Brands(values, brandData.children);
    brandsInfo.push(brands);
    setBrandsInfo(brandsInfo);
  }

  const appendInputData = (val, label) => {
    console.log(val);
    console.log(label);
    setFieldsData({ ...fieldsData, [label]: val });
  }

  const handleTypeChange = (value: RegistrationType) => {
    setSelectedType(value);
  };

  const handleEndCustomerTypeChange = (value: EndCustomerType) => {
    setSelectedEndCustomerType(value);
  };

  const handleTcsApplicableChange = (value: TcsApplicable) => {
    setSelectedTcsApplicable(value);
  };

  const handleCategory = (value) => {
    setSelectedCategory(value);
  }


  return (
    <>
      <Card size="small" title={<span style={{ color: 'white' }}>End Customer</span>} style={{ textAlign: 'center' }} headStyle={{ backgroundColor: '#69c0ff', border: 0 }} extra={props.isUpdate == true ? "" : <Link to="/EndCustomerview"  ><span style={{ color: 'white' }} ><Button className='panel_button' >View </Button> </span></Link>} >
        <Form form={form} onFinish={saveData} initialValues={props.endCustomersData} layout="vertical" >
          <Form.Item name="endCustomerId" style={{ display: "none" }} >
            <Input hidden />
          </Form.Item>
          <Form.Item style={{ display: "none" }} name="createdUser" initialValue={createdUser}>
            <Input hidden />
          </Form.Item>
          <Row gutter={24}>
            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 6 }} lg={{ span: 6 }} xl={{ span: 6 }}>
              <Form.Item
                name="endCustomerCode"
                label="End Customer Code"
                
                rules={[
                  {
                    required: true, message: 'Missing End Customer Code'
                  },
                  // {
                  //   pattern: /^[^-\s\\[\]()*!@#$^&_\-+/%=`~{}:";'<>,.?|][a-zA-Z&\\0-9\[\]()@#$_\-+/`~{}:";'<>,.?|\s-]*$/,
                  //   message: `Invalid End Customer Code`
                  // }
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 6 }} lg={{ span: 6 }} xl={{ span: 6 }}>
              <Form.Item
                name="endCustomerName"
                label="End Customer Name"
                rules={[
                  {
                    required: true, message: 'Missing End Customer name'
                  },
                  // {
                  //   pattern: /^[^-\s\\0-9\[\]()*!@#$^&_\-+/%=~{}:";<>,.?|][a-zA-Z&'. ]*$/,
                  //   message: `Should contain only alphabets`
                  // }
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 6 }} lg={{ span: 6 }} xl={{ span: 6 }}>
              <Form.Item
                name="consignee"
                label="Consignee Name"
                rules={[
                  {
                    required: true, message: 'Missing Consignee name'
                  },
                  // {
                  //   pattern: /^[^-\s\\0-9\[\]()*!@#$^&_\-+/%=~{}:";<>,.?|][a-zA-Z&'. ]*$/,
                  //   message: `Should contain only alphabets`
                  // }
                ]}
              >
                <Input />
              </Form.Item>
            </Col>


            <Col span={4}>
              <Form.Item
                name="currencyId"
                label="Currency"
                rules={[
                  {
                    required: true, message: 'Missing currency',
                  },
                ]}
              >
                <Select
                  placeholder="Select Currency"
                  onChange={handleCurrency}
                  allowClear
                >
                  {currencies.map(curencyDropData => {
                    return <Option value={curencyDropData.currencyId}>{curencyDropData.currencyName}</Option>
                  })}
                </Select>
                {/* <Input /> */}
              </Form.Item>
            </Col>

            <Col span={4}>
              <Form.Item
                name="countryId"
                label="Country"
                rules={[
                  {
                    required: true, message: 'Missing Country',
                  },
                ]}
              >
                <Select
                  placeholder="Select Country"
                  onChange={(val, option) => handleCountries(val, option)}
                  allowClear
                  showSearch  // Add this line to enable search functionality
                  optionFilterProp="children"  // Specify which prop of option will be used for filtering
                  filterOption={(input, option) =>
                    option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }  // Define custom filtering logic
                >
                  {countries.map(countryDropData => {
                    return <Option key={countryDropData.countryId} value={countryDropData.countryId} name={countryDropData.countryName}>{countryDropData.countryName}</Option>
                  })}
                </Select>
                {/* <Input /> */}
              </Form.Item>
            </Col>




            <Col span={4}>
              <Form.Item
                name="stateName"
                label="State"
                // rules={[
                //   {
                //     required: true, message: 'Missing State',
                //   },
                // ]}
              >
                {inputVisible == true ?
                  <Select
                    placeholder="Select State"
                    onChange={handleStates}
                    allowClear
                    showSearch  // Add this line to enable search functionality
                    optionFilterProp="children"  // Specify which prop of option will be used for filtering
                    filterOption={(input, option) =>
                      option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }  // Define custom filtering logic
                  >
                    {states.map(stateDropData => {
                      return <Option key={stateDropData.stateName} value={stateDropData.stateName}>{stateDropData.stateName}</Option>
                    })}
                  </Select> : <Input />

                }

                {/* <Input /> */}
              </Form.Item>
            </Col>

            <Col span={4}>
              <Form.Item name="registrationType" label="Registration Type"
                rules={[
                  {
                    required: true, message: 'Missing Registration Type',
                  },
                ]}>
                <Select
                  id="registrationType"
                  placeholder='Select Registration Type'
                  value={selectedType}
                  onChange={handleTypeChange}
                >
                  <Option value={RegistrationType.composition}>Composition</Option>
                  <Option value={RegistrationType.regular}>Regular</Option>
                  <Option value={RegistrationType.unregisteredConsumer}>
                    Unregistered/Consumer
                  </Option>
                </Select>
              </Form.Item>
            </Col>

            <Col span={4}>
              <Form.Item name="tcsApplicable" label="TCS Applicable"
                rules={[
                  {
                    required: true, message: 'Missing TCS Applicable',
                  },
                ]}>
                <Select
                  id="tcsApplicable"
                  placeholder='Select TCS Applicable'
                  value={selectedTcsApplicable}
                  onChange={handleTcsApplicableChange}
                >
                  <Option value={TcsApplicable.Yes}>Yes</Option>
                  <Option value={TcsApplicable.No}>No</Option>
                </Select>
              </Form.Item>
            </Col>


            <Col span={4}>
              <Form.Item name="endCustomerType" label="End Customer Type"
                rules={[
                  {
                    required: true, message: 'Missing End Customer Type',
                  },
                ]}>
                <Select
                  id="endCustomerType"
                  placeholder='Select End Customer Type'
                  value={selectedEndCustomerType}
                  onChange={handleEndCustomerTypeChange}
                >
                  <Option value={EndCustomerType.domestic}>Domestic</Option>
                  <Option value={EndCustomerType.Export}>Export</Option>
                </Select>
              </Form.Item>
            </Col>


            <Col span={4}>
              <Form.Item
                name="category"
                label="Category"
                rules={[
                  {
                    required: true, message: 'Missing Vendor Category',
                  },
                ]}
              >

                <Select
                  placeholder="Select Vendor Category"
                  onChange={handleCategory}
                  allowClear
                >
                  {category.map(categoryDropData => {
                    return <Option value={categoryDropData.id}>{categoryDropData.category}</Option>
                  })}
                </Select>



                {/* <Input /> */}
              </Form.Item>

            </Col>

            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 6 }} lg={{ span: 6 }} xl={{ span: 6 }}>
              <Form.Item
                name="faxNo"
                label="Fax Number"
                // rules={[
                  
                //   {
                //     pattern: /^(\+\d{1,3}[- ]?)?\d{1,14}$/,
                //     message: 'Invalid Fax Number'
                //   }
                // ]}
              >
                <Input />
              </Form.Item>
            </Col>



            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 6 }} lg={{ span: 6 }} xl={{ span: 6 }}>
              <Form.Item
                name="phoneNo"
                label="Phone Number"
                // rules={[
                 
                //   {
                //     // pattern: /^(\+\d{1,3}[- ]?)?\d{1,14}$/,
                //     pattern:/^[a-zA-Z]+$/,
                //     message: 'Invalid Phone Number'
                //   }
                // ]}
              >
                <Input />
              </Form.Item>
            </Col>
            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 6 }} lg={{ span: 6 }} xl={{ span: 6 }}>
              <Form.Item
                name="email"
                label="Email Id"
              >
                <Input />
              </Form.Item>
            </Col>

            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 6 }} lg={{ span: 6 }} xl={{ span: 6 }}>
              <Form.Item
                name="htsCode"
                label="HTS Code"
              >
                <Input />
              </Form.Item>
            </Col>



            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 6 }} lg={{ span: 6 }} xl={{ span: 6 }}>
              <Form.Item
                name="consigneeAddress"
                label="Consignee Address"
              >
                <TextArea />
              </Form.Item>
            </Col>




          </Row>
          <Row gutter={24}>

            <Form.List name="addressInfo">
              {(fields, { add, remove }) => (
                <>
                  <Card>
                    <Form.Item>
                      {/* <br /> */}
                      {/* <br/> */}
                      <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                        Add Address
                      </Button>
                    </Form.Item>
                    {fields.map(field => (
                      <Space key={field.key} style={{ display: 'flex', marginBottom: 8 }}>
                        {/* <Row gutter={24}> */}

                        {/* </Row> */}
                        <Row gutter={24}>
                          <Col span={6}>
                            <Form.Item
                              {...field}
                              label="Address1"
                              name={[field.name, 'addLineOne']}
                              fieldKey={[field.fieldKey, 'addressLineOne']}
                              rules={[{ required: true, message: 'Missing address1' }]}
                            >
                              <TextArea />

                            </Form.Item>
                          </Col>
                          <Col span={6}>
                            <Form.Item
                              {...field}
                              label="Address2"
                              name={[field.name, 'addLineTwo']}
                              fieldKey={[field.fieldKey, 'addressLineTwo']}
                              rules={[{ required: true, message: 'Missing address2' }]}
                            >
                              <TextArea />

                            </Form.Item>
                          </Col>
                          <Col span={6}>
                            <Form.Item
                              {...field}
                              label="State"
                              name={[field.name, 'addLineThree']}
                              fieldKey={[field.fieldKey, 'addressLineThree']}
                              // rules={[{ required: true, message: 'Missing state name' },
                              //   // {
                              //   //   pattern: /^[^-\s\\0-9\[\]()*!@#$^&_\-+/%=`~{}:";'<>,.?|][a-zA-Z ]*$/,
                              //   //   message: `Should contain only alphabets.`
                              //   // }
                              // ]}
                            >
                              <TextArea />

                            </Form.Item>
                          </Col>
                          <Col span={6}>
                            <Form.Item
                              {...field}
                              label="Postal Code"
                              name={[field.name, 'addLineFour']}
                              fieldKey={[field.fieldKey, 'addressLineFour']}
                              // rules={[{ required: true, message: 'Missing Postal Code' }]}
                            >
                              <Input />

                            </Form.Item>
                          </Col>
                        </Row>
                        {
                          props.isUpdate ? <></> :
                            <MinusCircleOutlined onClick={() => remove(field.name)} />
                        }
                      </Space>
                    ))}
                  </Card>

                </>
              )}
            </Form.List>
            <Col xs={{ span: 24 }} sm={{ span: 24 }} md={{ span: 10 }} lg={{ span: 10 }} xl={{ span: 10 }}>
              <Form.Item name="file" rules={[{ required: false, message: 'Please Upload File' },]}>
                <Upload {...uploadFieldProps} style={{ width: '100%' }} listType="picture-card" onChange={e => appendInputData(e.file.name, 'file')}>
                  {imageUrl ? <img src={imageUrl} style={{ width: '100%' }} /> : uploadButton}
                </Upload>
              </Form.Item>
            </Col>          </Row>

          <Row gutter={24}>

            <Form.List name="brandsInfo">
              {(fields, { add, remove }) => (
                <>
                  <Card>
                    <Form.Item>

                      <Button type="dashed" onClick={() => add()} block icon={<PlusOutlined />}>
                        Add Brand
                      </Button>
                    </Form.Item>
                    {fields.map(field => (
                      <Space key={field.key} style={{ display: 'flex', marginBottom: 8 }}>

                        <Row gutter={24}>
                          <Col span={24}>
                            <Form.Item
                              {...field}
                              label="Brand Name"
                              name={[field.name, 'masterBrandId']}
                              // fieldKey={[field.fieldKey, 'brandId']}
                              rules={[{ required: true, message: 'Missing brand name' }, { pattern: /^(?!\s*$).+/, message: `Enter Brand Name` }]}
                            >
                              <Select
                                showSearch
                                placeholder="Please Select Brand"
                                optionFilterProp="children"
                                onChange={setBrandName}
                                onSearch={onSearch}
                                filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                                style={{ width: 250 }}
                              >
                                <Option key={0} value={null}>Please select brand</Option>
                                {brandsDropDown.map(branddropData => {
                                  return <Option label={'brandId'} key={branddropData.masterBrandId} value={branddropData.masterBrandId}>{branddropData.masterBrandName}</Option>
                                })}
                                |
                              </Select>
                            </Form.Item>
                          </Col>

                        </Row>
                        {
                          props.isUpdate ? <></> :
                            <MinusCircleOutlined onClick={() => remove(field.name)} />
                        }
                      </Space>
                    ))}
                  </Card>

                </>
              )}
            </Form.List>
          </Row>

          <Row>
            <Col span={24} style={{ textAlign: 'right' }}>
              <Button type="primary" disabled={disable} htmlType="submit" >
                Submit
              </Button>
              {(props.isUpdate === false) &&
                <Button htmlType="button" style={{ margin: '0 14px' }} onClick={onReset}>
                  Reset
                </Button>
              }
            </Col>
          </Row>
        </Form>
      </Card>
    </>
  );

}



export default EndCustomersForm;

