import {
  useState,
  useEffect,
  useRef,
  useCallback,
  lazy,
  Suspense,
} from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { InputField } from '../../Components/Forms/InputField.jsx';
import Buttons from '../../Components/Forms/Buttons.jsx';
import {
  ArrowRightOutlined,
  DeleteFilled,
  EditFilled,
  ReloadOutlined,
} from '@ant-design/icons';
import { Radio, Space, Table, Checkbox } from 'antd';
import { Messages } from '../../Components/Notifications/Messages';
import { Form, Tooltip } from 'antd';
import moment from 'moment';
import { changeBreadCrumb } from '../../Features/AppPage/CenterPage.js';
import FormHeader from '../PageComponents/FormHeader.jsx';
import { getSession, validateSafeInput } from '../../Services/Others';
import { useNavigate, useLocation } from 'react-router-dom';
import { getCustBasedOnCmpIdBrIdAppId } from '../../Features/CustMaster/CustMaster.js';
import { DropDowns } from '../../Components/Forms/DropDown.jsx';
import { DatePicProd } from '../../Components/Forms/DatePickerProduct.jsx';
import { Tables } from '../../Components/Tables/Table.jsx';
import {
  getWholeSaleProducts,
  PostwsPreorder,
  PostwsPreorderMultiple,
  PuttwsPreorder,
} from '../../Features/WholeSale/ProductEntry.js';
import {
  getWholesaleQuantityData,
  getWholesaleUomData,
  WholesaleQuantityData,
  WholesaleUomDataSelector,
} from '../../Features/ProductPage/ProductPage.js';
import './WholesalePreorderForm.scss';
import PozoAddCustomerIcon from '../BookingScreen/Components/UtillComponents/Pozo retail icons/PozoAddCustomerIcon.jsx';
import FeaturesFunctionalities from '../BookingScreen/Components/BookingFunctionality/FeaturesFunctionalities.jsx';
import {
  changeSelectedCustId,
  changeSelectedOption,
  GlobalSelCustId,
} from '../../Features/BookingScreen/BookingData/BookingData.js';
import {
  getWholeSaleAllocatedPreOrders,
  GlobalAllocatedPreOrders,
  GlobalLastEntryDateDtl,
  GlobalWSDate,
} from '../../Features/WholeSale/WholesaleData.js';
import { IoMdAdd, IoMdAddCircle } from 'react-icons/io';
const AddUOMPreorder = lazy(
  () => import('../PurchaseScreen/WholeSaleComponent/AddUomPreorder.jsx')
);
const Search = lazy(() => import('../../Components/Forms/Search.jsx'));

const subDirectory = import.meta.env.BASE_URL;

const WsPreOrderForm = ({
  formType,
  HigherorderComponents = false,
  Modelclose,
  WholeSalePreOrder = false,
  handleWholeSalePreOrderAndSelectCustomer,
  handleGradeCalculationBypreorder,
}) => {
  const formRef = useRef(null);
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const location = useLocation();
  const state = location?.state;
  const editstate = state?.editstate;

  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const AppId = getSession('AppId');
  const UserId = getSession('UserId');
  const SelCustId = useSelector(GlobalSelCustId);
  const UomData = useSelector(WholesaleQuantityData);
  const WSLastEntryDate = useSelector(GlobalLastEntryDateDtl);
  const WSDate = useSelector(GlobalWSDate);
  const [filteredInfo, setFilteredInfo] = useState({});
  const [sortedInfo, setSortedInfo] = useState({});
  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const [addcustomer, setAddCustomer] = useState(false);
  const [EditStatus, SetEditStatus] = useState(false);
  const CUstomerName = useSelector(GlobalAllocatedPreOrders);
  const [size, setsize] = useState('');
  const [selectedValue, setSelectedValue] = useState(null);
  const [SelectedValueName, setSelectedValueName] = useState({
    selectedProd: null,
    selectedUom: null,
  });
  const [searchedText, setSearchedText] = useState('');
  const [WsPreorderDate, setWsPreorderDate] = useState();
  const [TableData, setTableData] = useState([]);
  const [TableDatawithCustomer, setTableDatawithCustomer] = useState([]);
  const [CommonDataFilter, setCommonDataFilter] = useState([]);
  const [selectedUOM, setSelectedUOM] = useState(null);
  const [customer, setCustomer] = useState();
  const [SelectedCustomer, setSelectedCustomer] = useState();
  const [editTable, setEditTable] = useState([]);
  const [page, setpage] = useState(1);
  const [page1, setpage1] = useState(1);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [Dbselectedkeys, setDbselectedkeys] = useState([]);
  const [hold, setHold] = useState(false);
  const [AddUomModalOpen, setAddUomModalOpen] = useState(false);
  const [Mode, setMode] = useState('N');
  const [Checked, setChecked] = useState(false);
  const handleMobileNumberChange = (e) => {
    setsize(e?.target?.value);
    formRef.current?.setFieldsValue({ Size: e?.target?.value });
  };
  useEffect(() => {
    // if (UomData.length > 0) {
    //     UOMDropDownChange(UomData?.find(item => item.NumFId == 1)?.ConfigId);
    // }
    if (UomData?.filter((item) => item.ActiveStatus === 'A').length > 0) {
      UOMDropDownChange(
        UomData?.filter((item) => item.ActiveStatus === 'A')?.find(
          (item) => item.NumFId == 1
        )?.ConfigId
      );
    } else if (UomData.length == 0) {
      setSelectedUOM(null);
    }
  }, [UomData]);
  useEffect(() => {
    if (Mode?.toLowerCase() === 'y') {
      let data = TableDatawithCustomer.filter((item1) =>
        CUstomerName.some(
          (item) =>
            item.CustId == item1?.CustId &&
            item?.ProductDetails.some((e) => e?.ProdId == selectedValue)
        )
      );

      console.log(data, 'datadatadata');
      setSelectedRowKeys(data?.map((e) => e?.key));
      // setSelectedCustomer(data?.map((e)=>  { custId :e?.CustId} ))
      setSelectedCustomer(
        data?.map((e) => {
          return { CustId: e?.CustId };
        })
      );
      setDbselectedkeys(data?.map((e) => e?.key));
    }
  }, [selectedValue, Mode]);
  const items = [
    {
      name: 'Home',
      link: `${subDirectory}app-page/home`,
    },

    {
      name: 'Preorder',
      link: `${subDirectory}setting/wholesale-preorder`,
    },
    {
      name: editstate ? 'Edit' : 'New',
      link: null,
    },
  ];
  const UOMDropDownChange = (e) => {
    formRef.current?.setFieldsValue({ UOM: e });
    setSelectedUOM(e);
    const selectedOption = UomData?.filter(
      (item) => item.ActiveStatus === 'A'
    ).find((option) => option.ConfigId === e)?.ConfigName;
    // const selectedOption = UomData.find(
    //     (option) => option.ConfigId === e
    // )?.ConfigName;
    setSelectedValueName((prev) => ({
      ...prev,
      selectedUom: selectedOption,
    }));
  };

  useEffect(() => {
    dispatch(changeBreadCrumb({ items: items }));
    fetchWholeSaleProducts();
    if (formType === 'add') {
      const todayDate = moment().format('YYYY-MM-DDTHH:mm:ss');
      formRef.current?.setFieldsValue({ Date: todayDate });
      setWsPreorderDate(todayDate);
    }
    getCustomerDatas();
  }, []);
  useEffect(() => {
    if (Mode == 'Y') {
      getCustomerDatas();
    }
  }, [Mode]);
  useEffect(() => {
    try {
      if (formType === 'edit') {
        if (editstate) {
          setEditTable(editstate?.ProductDetails);
          setTableData(editstate?.ProductDetails);
          setSelectedCustomer(editstate?.CustId);
          setWsPreorderDate(editstate?.DueDate);

          formRef.current?.setFieldsValue({
            Date: moment(editstate?.DueDate + '' + 'T00:00:00'),
          });
          formRef.current?.setFieldsValue({
            Customer: moment(editstate?.CustName + '' + 'T00:00:00'),
          });

          formRef.current?.setFieldsValue(editstate);
        } else {
          navigate(`${subDirectory}setting/employee-master/`);
        }
      }
    } catch (err) {
      console.log(err, 'err');
    }
  }, []);

  useEffect(() => {
    if (HigherorderComponents) {
      formRef?.current?.setFieldsValue({ Customer: SelCustId });
      setSelectedCustomer(SelCustId);
    }
  }, [SelCustId]);
  const getCustomerDatas = async () => {
    if (BranchId) {
      const gettingTableData = await dispatch(
        getCustBasedOnCmpIdBrIdAppId({ CompId, BranchId, AppId })
      ).unwrap();
      if (gettingTableData?.data?.statusCode === 1) {
        setTableDatawithCustomer(
          gettingTableData?.data?.data
            ?.filter?.((item) => item.ActiveStatus == 'A')
            ?.map((e, index) => ({
              key: index + 1, // Use `key` instead of `Key` for consistency
              CustName: e?.CustName,
              CustMobile: e?.CustMobile,
              CustId: e?.CustId,
              CustShortName: e?.CustShortName, // Add the Name property from `CustName`
            }))
        );
      }
    }
  };

  const onFinish = async (values) => {
    if (SelectedCustomer?.length > 0) {
      if (Mode == 'Y') {
        let data = {
          AppId: AppId,
          CompId: CompId,
          BranchId: BranchId,
          Customers: SelectedCustomer,
          DueDate: Checked ? '' : WsPreorderDate.split('T')[0],
          Type: Checked ? 'A' : 'S',
          ProductDetails: [
            {
              ProdId: values?.ProdList,
            },
          ],
          CreatedBy: UserId,
        };

        let response = await dispatch(PostwsPreorderMultiple(data)).unwrap();
        if (response?.data?.statusCode == '1') {
          handleGradeCalculationBypreorder &&
            handleGradeCalculationBypreorder();
          setTableDatawithCustomer();
          setWsPreorderDate();
          setSelectedCustomer();
          formRef?.current?.resetFields();
          if (HigherorderComponents || WholeSalePreOrder) {
            const today = new Date();
            const formattedDate = today.toLocaleDateString('en-CA');
            const Data = {
              appId: AppId,
              compId: CompId,
              branchId: BranchId,
              dueDate: WSDate,
            };

            await dispatch(getWholeSaleAllocatedPreOrders(Data)).unwrap();
            dispatch(changeSelectedCustId());
            if (HigherorderComponents) {
              Modelclose();
            } else if (WholeSalePreOrder) {
              handleWholeSalePreOrderAndSelectCustomer();
            }
          } else {
            const today = new Date();
            const formattedDate = today.toLocaleDateString('en-CA');
            const Data = {
              appId: AppId,
              compId: CompId,
              branchId: BranchId,
              dueDate: WSDate,
            };

            await dispatch(getWholeSaleAllocatedPreOrders(Data)).unwrap();
            navigate(`${subDirectory}setting/wholesale-preorder`);
          }
        }
      } else {
        SetEditStatus(false);
        let data = {
          ProdId: values?.ProdList,
          ProdName: SelectedValueName?.selectedProd,
          RequestedQty: values?.Size,
          UOM: values?.UOM,
          UomName: SelectedValueName?.selectedUom,
          ActiveStatus: 'A',
        };

        // Check if the product already exists in the table
        setTableData((prev) => {
          const existingProductIndex = prev?.findIndex(
            (item) => item.ProdId === data?.ProdId
          );

          if (existingProductIndex !== -1) {
            return prev.map((item, index) =>
              index === existingProductIndex
                ? { ...data, ActiveStatus: item.ActiveStatus }
                : item
            );
          }

          return [...prev, data];
          // const existingProductIndex = prev?.findIndex(
          //     (item) => item.ProdId === data?.ProdId
          // );

          // if (existingProductIndex !== -1) {
          //     // Product exists, replace the existing entry
          //     const updatedData = [...prev];
          //     updatedData[existingProductIndex] = data;
          //     return updatedData;
          // } else {
          //     // Product does not exist, add a new entry
          //     return [...prev, data];
          // }
        });
        // setSelectedValue(null);
        setTimeout(() => {
          const changeUOM = UomData?.filter(
            (item) => item.ActiveStatus === 'A'
          )?.find((item) => item.NumFId == 1)?.ConfigId;
          // const changeUOM = UomData?.find(item => item.NumFId == 1)?.ConfigId;
          setSelectedUOM(changeUOM);
          formRef.current?.setFieldsValue({ UOM: changeUOM });
        }, 10);
        setsize(' ');

        // formRef?.current?.resetFields(["ProdList"]);
        formRef?.current?.resetFields(['UOM']);
        formRef?.current?.resetFields(['Size']);
      }
    } else {
      setMessageType('error');
      setMessageData('please select customer');
    }
  };

  const handleChange = (pagination, filters, sorter) => {
    setFilteredInfo(filters);
    setSortedInfo(sorter);
  };

  const handlePageChange = (current) => {
    setpage(current);
  };
  const handlePageChange1 = (current) => {
    setpage1(current);
  };

  const onSelectChange = (newSelectedRowKeys, selectedRows) => {
    if (newSelectedRowKeys !== selectedRowKeys) {
      setSelectedRowKeys([...newSelectedRowKeys, ...Dbselectedkeys]);
      setSelectedCustomer(getSelectedCustomerData(selectedRows));
      console.log('Selected Row Keys:', newSelectedRowKeys);
      console.log('Selected Rows:', selectedRows);
    }
  };
  const errorMsgFn = () => {
    setMessageData('Have got to Choose Product First');
    setMessageType('warning');
  };

  const getSelectedCustomerData = (selectedRows) => {
    let data = new Map();
    selectedRows.forEach((row) => {
      if (row?.CustId) {
        data?.set(row.CustId, { CustId: row.CustId });
      }
    });
    return [...data?.values()];
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: selectedValue ? onSelectChange : errorMsgFn,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
    ],
  };
  const resetSelection = () => {
    setSelectedValue();
    formRef.current?.setFieldsValue({ ProdList: '' });
    setSelectedValueName({
      selectedProd: null,
      selectedUom: null,
    });
  };

  const onchangeStatus = (e) => {
    setMode(e?.target?.value);
    if (e?.target?.value === 'N') {
      setSelectedCustomer();
      if (CommonDataFilter?.length !== 1) {
        resetSelection();
      }
    } else if (e?.target?.value === 'Y') {
      if (CommonDataFilter?.length === 1) {
        setSelectedValue(CommonDataFilter[0]?.ProdId);
        formRef.current?.setFieldsValue({
          ProdList: CommonDataFilter[0]?.ProdId,
        });
        setSelectedValueName((prev) => ({
          ...prev,
          selectedProd: CommonDataFilter[0]?.ProdName,
        }));
      } else {
        resetSelection();
      }
    }
    setSelectedRowKeys([]);
    setSearchedText('');
    setChecked(false);
  };
  const actionsFormatter = (record) => {
    // formRef.current?.setFieldsValue(record);
    SetEditStatus(true);
    ChangeProduct(record.ProdId);
    UOMDropDownChange(record.UOM);
    formRef.current?.setFieldsValue({
      Size: record?.RequestedQty,
    });
    setsize(record?.RequestedQty);

    // Size
  };
  const columns = [
    {
      title: 'Sl.No',
      key: 'sno',
      align: 'center',
      width: '50px',
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{(page - 1) * 10 + index + 1}</a>
      ),
    },
    {
      title: 'Product Name',
      dataIndex: 'ProdName',
      key: 'ProdName',
      width: '100px',
    },
    {
      title: 'Size',
      dataIndex: 'RequestedQty',
      key: 'RequestedQty',
      width: '100px',
    },
    {
      title: 'Uom',
      dataIndex: 'UomName',
      key: 'UomName',
      width: '100px',
    },
    {
      title: 'Delete',
      dataIndex: 'ActiveStatus',
      key: 'ActiveStatus',
      width: '10px',
      render: (_, record) => (
        <Space size="middle">
          {record?.ActiveStatus === 'A' ? (
            <a>
              <EditFilled
                style={{ color: '#1292EE' }}
                onClick={() => actionsFormatter(record)}
              />
            </a>
          ) : null}

          {record?.ActiveStatus === 'A' ? (
            <DeleteFilled
              className="shape-delete"
              style={{
                color: '#FF4D4F',
              }}
              onClick={() => (!EditStatus ? handleRemove(record.ProdId) : ' ')}
            />
          ) : (
            <ReloadOutlined
              style={{
                color: '#52C41A',
              }}
              onClick={() => handleRemove(record.ProdId)}
            />
          )}
        </Space>
      ),
    },
  ];
  const columnswithCustomer = [
    {
      title: 'Sl.No',
      key: 'sno',
      align: 'center',
      width: '30px',
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{(page - 1) * 10 + index + 1}</a>
      ),
    },
    {
      title: 'Customer Name',
      dataIndex: 'CustShortName',
      key: 'CustShortName',
      width: '50px',
      filteredValue: [searchedText],
      onFilter: (value, record) => {
        return (
          String(record.CustShortName)
            ?.toLowerCase()
            ?.includes(value?.toLowerCase()) ||
          String(record.CustName)
            ?.toLowerCase()
            ?.includes(value?.toLowerCase()) ||
          String(record.CustMobile)
            ?.toLowerCase()
            ?.includes(value?.toLowerCase())
        );
      },
      render: (text, record, row) => (
        <a style={{ color: 'black', width: '200px' }}>
          {record?.CustShortName || record?.CustName || record?.CustMobile}
        </a>
      ),
    },
    {
      title: 'Mobile',
      dataIndex: 'CustMobile',
      key: 'CustMobile',
      width: '50px',
    },
  ];
  const SelectedPreorderCustomer = [
    {
      title: 'Sl.No',
      key: 'sno',
      align: 'center',
      width: '20px',
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{(page1 - 1) * 10 + index + 1}</a>
      ),
    },
    {
      title: 'Customer Name',
      dataIndex: 'CustName',
      key: 'CustName',
      width: '250px',
      render: (text, record, row) => (
        <a style={{ color: 'black', width: '200px' }}>
          {record?.CustShortName || record?.CustName || record?.CustMobile}
        </a>
      ),
    },
    {
      title: 'Mobile',
      dataIndex: 'CustMobile',
      key: 'CustMobile',
      width: '250px',
    },
  ];
  const handleRemove = (prodId) => {
    if (formType === 'add') {
      setTableData((prev) => prev.filter((item) => item.ProdId !== prodId));
    } else {
      // if (editTable?.some((item) => item.ProdId !== prodId)) {
      //     setTableData((prev) => prev.filter((item) => item.ProdId !== prodId));
      // }
      if (editTable?.some((item) => item.ProdId == prodId)) {
        setTableData((prev) =>
          prev.map((item) =>
            item.ProdId === prodId
              ? { ...item, ActiveStatus: item.ActiveStatus === 'A' ? 'D' : 'A' }
              : item
          )
        );
      } else {
        setTableData((prev) => prev.filter((item) => item.ProdId !== prodId));
      }
    }
  };
  const ChangeProduct = (value) => {
    setSelectedValue(value);
    const selectedOption = CommonDataFilter.find(
      (option) => option.ProdId === value
    )?.ProdName;
    setSelectedValueName((prev) => ({
      ...prev,
      selectedProd: selectedOption,
    }));
    formRef.current?.setFieldsValue({ ProdList: value });
  };

  const wsPreOrderDate = async (date, dateString) => {
    if (dateString) {
      const Date1 = moment(dateString, ['DD-MM-YYYY']).format(
        'YYYY-MM-DDTHH:mm:ss'
      );
      formRef.current?.setFieldsValue({ Date: Date1 });
      setWsPreorderDate(Date1);
    } else {
      setWsPreorderDate(null);
      formRef.current?.setFieldsValue({ Date: null });
    }
  };

  const fetchWholeSaleProducts = async () => {
    const getUomResponse = await dispatch(getWholesaleUomData()).unwrap();
    await dispatch(getWholesaleQuantityData());
    const gettingTableData = await dispatch(
      getCustBasedOnCmpIdBrIdAppId({ CompId, BranchId, AppId })
    ).unwrap();
    if (gettingTableData?.data?.statusCode === 1) {
      setCustomer(gettingTableData?.data?.data);
    }
    let response = await dispatch(
      getWholeSaleProducts({ CompId: CompId, AppId: AppId, BranchId: BranchId })
    ).unwrap();
    if (response?.data?.statusCode == 1) {
      let res = response?.data?.data?.filter(
        (item) => item.ActiveStatus === 'A'
      );
      setCommonDataFilter(res);
      if (res?.length == 1) {
        setSelectedValue(res?.[0]?.ProdId);
        formRef.current?.setFieldsValue({ ProdList: res?.[0]?.ProdId });
        setSelectedValueName((prev) => ({
          ...prev,
          selectedProd: res?.[0]?.ProdName,
        }));
      }
    }
  };

  const ChangeCustomer = (e) => {
    formRef?.current?.setFieldsValue({ Customer: e });
    setSelectedCustomer(e);
  };

  const handleFormSubmit = async () => {
    if (formType === 'edit') {
      let data = {
        AppId: AppId,
        CompId: CompId,
        BranchId: BranchId,
        CustId: SelectedCustomer,
        DueDate: WsPreorderDate.split('T')[0],
        ProductDetails: TableData,
        UpdatedBy: UserId,
        PreOrderId: editstate.PreOrderId,
      };
      let response = await dispatch(PuttwsPreorder(data)).unwrap();

      if (response?.data?.statusCode == '1') {
        setTableData();
        setWsPreorderDate();
        setSelectedCustomer();
        formRef?.current?.resetFields();
        navigate(`${subDirectory}setting/wholesale-preorder`);
      }
    } else {
      let data = {
        AppId: AppId,
        CompId: CompId,
        BranchId: BranchId,
        Customers: [
          {
            CustId: SelectedCustomer,
          },
        ],
        DueDate: Checked ? '' : WsPreorderDate.split('T')[0],
        ProductDetails: TableData,
        CreatedBy: UserId,
        Type: Checked ? 'A' : 'S',
      };

      let response = await dispatch(PostwsPreorderMultiple(data)).unwrap();

      if (response?.data?.statusCode == '1') {
        setTableData();
        setWsPreorderDate();
        setSelectedCustomer();
        formRef?.current?.resetFields();
        dispatch(changeSelectedOption(null));
        if (HigherorderComponents || WholeSalePreOrder) {
          const today = new Date();
          const formattedDate = today.toLocaleDateString('en-CA');
          const Data = {
            appId: AppId,
            compId: CompId,
            branchId: BranchId,
            dueDate: WSDate,
          };
          await dispatch(getWholeSaleAllocatedPreOrders(Data)).unwrap();
          dispatch(changeSelectedCustId());
          if (HigherorderComponents) {
            Modelclose();
          } else if (WholeSalePreOrder) {
            handleWholeSalePreOrderAndSelectCustomer();
          }
        } else {
          navigate(`${subDirectory}setting/wholesale-preorder`);
        }
      } else {
        if (response?.data?.response == 'Config Not Added') {
          setMessageType('error');
          setMessageData('This Product is already added');
        } else {
          setMessageType('error');
          setMessageData(response?.data?.response);
        }
      }
    }
    handleGradeCalculationBypreorder && handleGradeCalculationBypreorder();
  };

  const handleAddCustomer = () => {
    setAddCustomer(true);
  };
  const handleAddCustomerCancel = () => {
    fetchWholeSaleProducts();
    setAddCustomer(false);
  };

  const handleHoldCancel = () => {
    setHold(false);
  };
  const onComplete = useCallback(() => {
    setMessageData(null);
    setMessageType(null);
  }, []);
  const AddUomModalFun = async (e) => {
    setAddUomModalOpen(e);
  };
  const Checking = (e) => {
    if (Checked) {
      setChecked(false);
    } else {
      setChecked(true);
    }
  };
  const onSearch = (value) => {
    setSearchedText(value);
  };
  const onSearchChange = (e) => {
    setSearchedText(e?.target?.value);
  };
  return (
    <Suspense fallback={<div>Loading…</div>}>
      <div className="WsPreOrderForm-Master">
        <div className="pageOverAll" style={{ height: Mode == 'Y' && '100%' }}>
          {(addcustomer || hold) && (
            <FeaturesFunctionalities
              handleAddCustomerCancel={handleAddCustomerCancel}
              addcustomer={addcustomer}
              handleHoldCancel={handleHoldCancel}
              modalOpen={hold}
            />
          )}
          <div className="userPage">
            <div className="userPageContent">
              <Messages
                messageType={messageType}
                messageData={messageData}
                onComplete={onComplete}
              />
              <div className="formName">
                <FormHeader title={'Preorder'} />
              </div>

              <div
                className="formDiv"
                style={{
                  height:
                    Mode === 'Y'
                      ? WholeSalePreOrder
                        ? '76vh'
                        : HigherorderComponents
                          ? '67vh'
                          : '80vh'
                      : '65vh',
                }}
              >
                <Form
                  ref={formRef}
                  className="formDivAnt"
                  onFinish={onFinish}
                  initialValues={{ ...editstate }}
                >
                  <div className="HeaderofselectStatus">
                    {formType == 'add' && (
                      <Radio.Group onChange={onchangeStatus} value={Mode}>
                        <Radio value="N">Individual</Radio>
                        <Radio value="Y">Customers</Radio>
                      </Radio.Group>
                    )}

                    {Mode == 'Y' && (
                      <div className="dateandandproductPRE">
                        <Form.Item
                          name="ProdList"
                          rules={[
                            {
                              required: true,
                              message: 'Please Enter Product',
                            },
                          ]}
                        >
                          <DropDowns
                            defaultValue={selectedValue}
                            options={CommonDataFilter?.map((option) => ({
                              value: option?.ProdId,
                              label: option?.ProdName,
                              data: option,
                            }))}
                            label={<label>Product </label>}
                            className="field-DropDown"
                            onChangeFunction={(e) => ChangeProduct(e)}
                            valueData={selectedValue}
                            disabled={EditStatus ? true : false}
                          />
                        </Form.Item>

                        <Form.Item
                          name="Date"
                          rules={[
                            {
                              required: Checked ? false : true,
                              message: 'Please Enter Date',
                            },
                          ]}
                        >
                          <label style={{ fontWeight: '600' }}>Date : </label>
                          <br />
                          <br />
                          <DatePicProd
                            canSelectPast={true}
                            onChange={wsPreOrderDate}
                            valueData={WsPreorderDate}
                            disabled={Checked}
                            minDate={WSLastEntryDate}
                          />
                        </Form.Item>

                        <p>
                          All Days : &nbsp;{' '}
                          <Checkbox onClick={(e) => Checking(e)} />{' '}
                        </p>
                        <div className="AllCustomerAlldays">
                          <div className="searchAddDiv">
                            <Search
                              placeholder="Search"
                              onSearch={onSearch}
                              onSearchChange={onSearchChange}
                            />
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                  {Mode == 'N' && (
                    <div className="formDivS">
                      <div
                        style={{
                          display: 'flex',
                          flexDirection: 'column',
                          flexWrap: 'wrap',
                        }}
                      >
                        <div className="wspreorder-input1">
                          <div className="inputForm">
                            <Form.Item
                              name="Customer"
                              rules={[
                                {
                                  required: true,
                                  message: 'Please Enter Customer',
                                },
                              ]}
                            >
                              <div className="customeraddcustomer">
                                <DropDowns
                                  defaultValue={SelectedCustomer}
                                  options={customer?.map((option) => ({
                                    value: option?.CustId,
                                    label: option?.CustShortName
                                      ? option?.CustShortName
                                      : option?.CustName
                                        ? option?.CustName
                                        : option?.CustMobile,
                                  }))}
                                  label={
                                    <label className="required">Customer</label>
                                  }
                                  className="field-DropDown"
                                  onChangeFunction={(e) => ChangeCustomer(e)}
                                  valueData={SelectedCustomer}
                                  disabled={
                                    formType == 'edit' || HigherorderComponents
                                      ? true
                                      : false
                                  }
                                />
                                {!HigherorderComponents && (
                                  <Tooltip title="Add Customer" placement="top">
                                    <PozoAddCustomerIcon
                                      className="BSBillingNav-icon-table-icon"
                                      onClick={handleAddCustomer}
                                      style={{
                                        fontSize: '25px',
                                        color: '#1292EE',
                                      }}
                                    />
                                  </Tooltip>
                                )}
                              </div>
                            </Form.Item>
                          </div>
                          <div
                            style={{
                              display: 'flex',
                              flexDirection: 'row',
                              alignItems: 'baseline',
                              gap: '1rem',
                              whiteSpace: 'nowrap',
                            }}
                          >
                            <Form.Item
                              name="Date"
                              rules={[
                                {
                                  required: Checked ? false : true,
                                  message: 'Please Enter Date',
                                },
                              ]}
                            >
                              <label style={{ fontWeight: '600' }}>
                                Date :{' '}
                              </label>
                              <br />
                              <br />
                              <DatePicProd
                                canSelectPast={true}
                                onChange={wsPreOrderDate}
                                valueData={WsPreorderDate}
                                disabled={Checked}
                                minDate={WSLastEntryDate}
                              />
                            </Form.Item>
                            <p>All Days : </p>

                            <Checkbox
                              // checked={SelectData?.includes(record.UniqueId) ? true : false}
                              onClick={(e) => Checking(e)}
                              // disabled={(Object.keys(ReorderHoldDetails).length !== 0 && BookingType === "Dine In" && GlobalExtraCharge.some(item => item.ExtraChargeId === record.UniqueId)) ? true : false}
                            />
                          </div>
                        </div>

                        <div className="wspreorder-input1">
                          <div>
                            <Form.Item
                              name="ProdList"
                              rules={[
                                {
                                  required: true,
                                  message: 'Please Enter Product',
                                },
                              ]}
                            >
                              <DropDowns
                                defaultValue={selectedValue}
                                options={CommonDataFilter?.map((option) => ({
                                  value: option?.ProdId,
                                  label: option?.ProdName,
                                  data: option,
                                }))}
                                label={
                                  <label className="required">Product</label>
                                }
                                className="field-DropDown"
                                onChangeFunction={(e) => ChangeProduct(e)}
                                valueData={selectedValue}
                                disabled={EditStatus ? true : false}
                              />
                            </Form.Item>
                          </div>

                          <div className="inputForm1">
                            <Form.Item
                              name="Size"
                              rules={[
                                {
                                  validator: async (_, value) => {
                                    await validateSafeInput(value); // To block HTML tags & SQL keywords
                                    return Promise.resolve();
                                  },
                                },
                              ]}
                            >
                              <InputField
                                field="Size"
                                value={size}
                                label={<label>Requested Qty</label>}
                                fieldState={true}
                                type="number"
                                fieldApi={true}
                                autocomplete="off"
                                onChange={handleMobileNumberChange}
                                isOnChange={
                                  formRef.current?.getFieldsValue()?.Size
                                    ? true
                                    : false
                                }
                              />

                              <Form.Item className="kgsDD" name="UOM">
                                <DropDowns
                                  options={UomData?.filter(
                                    (item) => item.ActiveStatus === 'A'
                                  )?.map((option) => ({
                                    value: option.ConfigId,
                                    label: option.ConfigName,
                                  }))}
                                  onChangeFunction={(e) => UOMDropDownChange(e)}
                                  valueData={selectedUOM}
                                  disabled={editstate?.UOM ? true : false}
                                />
                              </Form.Item>
                              <IoMdAddCircle
                                style={{
                                  fontSize: '1.5rem',
                                  paddingTop: '8px',
                                }}
                                onClick={() => {
                                  AddUomModalFun(true);
                                }}
                              />
                            </Form.Item>
                          </div>
                          <div></div>
                        </div>
                        <div className="submitButton1">
                          <Buttons
                            buttonText="ADD"
                            color="901D77"
                            icon={<IoMdAdd color="#ffffff" size={16} />}
                          />
                        </div>
                      </div>

                      <div className="reportTable">
                        <div
                          style={{
                            color: '#000',
                            fontSize: '14px',
                            fontWeight: '600',
                            overflow: 'hidden',
                          }}
                        >
                          Preorder List
                        </div>
                        <div className="preorder-table">
                          <Tables
                            columns={columns}
                            data={TableData}
                            dataSource={TableData}
                            pagination={handlePageChange}
                            onChange={handleChange}
                          />
                        </div>
                        <div className="PROCEEDTBN1">
                          {TableData?.length > 0 && (
                            <Buttons
                              buttonText="PROCEED"
                              handleSubmit={handleFormSubmit}
                            />
                          )}
                        </div>
                      </div>
                    </div>
                  )}
                  <>
                    {Mode == 'Y' && (
                      <div className="PreOrderFormWithCustomer">
                        <div
                          className="reportTable11"
                          style={{
                            height: WholeSalePreOrder
                              ? '50vh'
                              : HigherorderComponents
                                ? '47vh'
                                : '60vh',
                          }}
                        >
                          <h3 className="headPreorderCustomer-Table">
                            Listed Customers
                          </h3>
                          <Tables
                            columns={columnswithCustomer}
                            data={TableDatawithCustomer}
                            dataSource={TableDatawithCustomer}
                            pagination={handlePageChange}
                            onChange={handleChange}
                            rowSelection={rowSelection}
                          />{' '}
                        </div>
                        {Mode == 'Y' && (
                          <div className="PROCEEDTBN">
                            <Buttons
                              buttonText="PROCEED"
                              color="901D77"
                              icon={<ArrowRightOutlined />}
                              //   handleSubmit={() => { HandleSelectedEst() }}
                            />
                          </div>
                        )}

                        <div className="reportTable112">
                          {Mode == 'Y' && (
                            <>
                              <h3 className="headPreorderCustomer-Table">
                                Today Listed Customers
                              </h3>
                              <Tables
                                columns={SelectedPreorderCustomer}
                                data={CUstomerName}
                                dataSource={CUstomerName}
                                pagination={handlePageChange1}
                                onChange={handleChange}
                              />
                            </>
                          )}
                        </div>
                      </div>
                    )}
                  </>
                  {Mode == 'Y' && (
                    <div className="PROCEEDTBN-RES">
                      <Buttons
                        buttonText="PROCEED"
                        color="901D77"
                        icon={<ArrowRightOutlined />}
                        //   handleSubmit={() => { HandleSelectedEst() }}
                      />
                    </div>
                  )}
                </Form>
                {AddUomModalOpen && (
                  <AddUOMPreorder
                    AddsuppOpen={AddUomModalOpen}
                    HandleModalClose={() => AddUomModalFun(false)}
                  />
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </Suspense>
  );
};

export default WsPreOrderForm;
