import React, {
  useEffect,
  useRef,
  useState,
  useCallback,
  forwardRef,
  useImperativeHandle,
} from 'react';
import { useDispatch } from 'react-redux';
import {
  Form,
  Checkbox,
  Row,
  Space,
  Radio,
  Switch,
  Tooltip,
  Button,
  Input,
  Typography,
  Upload,
  message,
  Modal,
  Segmented,
} from 'antd';
import {
  DeleteFilled,
  EditFilled,
  ArrowRightOutlined,
  InfoCircleOutlined,
  PlusOutlined,
  MinusCircleOutlined,
  UploadOutlined,
} from '@ant-design/icons';
import { DropDowns } from '../../../../Components/Forms/DropDown';
import { Messages } from '../../../../Components/Notifications/Messages';
import Buttons from '../../../../Components/Forms/Buttons';
import { Tables } from '../../../../Components/Tables/Table';
import { getSession } from '../../../../Services/Others';
import {
  changeBreadCrumb,
  getEmpAccess,
} from '../../../../Features/AppPage/CenterPage';
import { getConfigType } from '../../../../Features/BookingScreen/BookingData/BookingData.js';
import {
  getPrintOptions,
  postPrintSelectionComponentData,
  getPrintSelectionComponentData,
  putPrintSelectionComponentData,
  changeSelectedprintSize,
  changeSelectedprintStyle,
  changeSelectedSlNo,
  changeSelectedItem,
  changeSelectedMRP,
  changeSelectedDiscount,
  changeSelectedQuantity,
  changeSelectedRate,
  changeSelectedAmount,
  changeSelectedHsnCode,
  changeSelectedQrcode,
  changeSelectedSignature,
  changeSelectedtermsAndConditions,
  changethemeFormat,
  changeNotes,
  changeSignatureImage,
  changeBillName,
  changeSelectedCashierName,
  changeSelectedLogo,
  changeSelectedCredit,
  changeSelectedTax,
} from '../../../../Features/ThemeChange/ThemeChange';
import '../../../../Styles/BookingScreen/Components/SelectionComponent/SelectionComponent.scss';
import { useAuth } from '../../../../AuthContext.jsx';
import { InputField } from '../../../../Components/Forms/InputField.jsx';
import ColorPicker from '../../../../Components/Forms/ColorPicker.jsx';
import { FaChevronDown, FaChevronUp } from 'react-icons/fa';

const subDirectory = import.meta.env.BASE_URL;

const SelectionComponent = forwardRef((props, ref) => {
  const dispatch = useDispatch();
  const { SadminuserAccess } = useAuth();
  const doSomething = (message, index) => {
    handleStyle(message);
    dispatch(changeSignatureImage(''));
    setEdit(false);
    if (index >= 4) {
      setShowMore(true);
    } else if (index <= 4) {
      setShowMore(false);
    }
  };

  useImperativeHandle(ref, () => ({
    doSomething,
  }));

  let SAAccessCommonMaster = SadminuserAccess?.find(
    (e) => e?.MenuName === 'Print Forms'
  );

  const formRef = useRef(null);
  const { Title } = Typography;

  const AppId = getSession('AppId');
  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const UserId = getSession('UserId');
  const UserType = getSession('UserType');
  const [segmentData, setSegmentData] = useState([]);
  const [segmentValue, setSegmentValue] = useState();
  const [edit, setEdit] = useState(false);
  const [templateEdit, setTemplateEdit] = useState(false);
  const [messageType, setMessageType] = useState(null);
  const [messageData, setMessageData] = useState(null);
  const [selectedStyleId, setSelectedStyleId] = useState(null);
  const [SelectedStyleName, setSelectedStyleName] = useState(null);
  const [sizeCheckList, setSizeCheckList] = useState([]);
  const [selectedSizeCheckedValues, setSelectedSizeCheckedValues] = useState(
    []
  );
  const [selectedSizeCheckList, setSelectedSizeCheckList] = useState([]);
  const [sizeOptionData, setSizeOptionData] = useState([]);

  const [styleData, setStyleData] = useState([]);

  const [checkedList, setCheckedList] = useState([]);
  const checkAll = sizeCheckList?.length === checkedList?.length;
  const [empData, setEmpData] = useState();
  const selecetedConfigName = styleData?.filter(
    (item) => item?.ConfigId == selectedStyleId
  )?.[0]?.ConfigName;
  const [PrintType, setPrintType] = useState(true);
  const [PageSize, setPageSize] = useState('3inch');
  const [isFooterChecking, setisFooterChecking] = useState(false);
  const [isBillName, setisBillName] = useState(false);
  const [isTermscondChecking, setisTermscondChecking] = useState(false);
  const [isSignatureChecking, setisSignatureChecking] = useState(false);
  const [isheadercolour, setisheadercolour] = useState(false);
  const [showMore, setShowMore] = useState(false);
  const visibleConfigs = showMore ? styleData : styleData.slice(0, 4);
  const defaultImage =
    'https://5.imimg.com/data5/SELLER/Default/2024/2/382660974/CB/FZ/CS/139657382/bill-book-printing-services.jpeg';
  const [terms, setTerms] = useState(['']);
  const [selectedColour, setSelectedColour] = useState('#000000');
  const [fileList, setFileList] = useState([]);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');
  const [Notes, setNote] = useState('');
  const [BillName, setBillName] = useState('');

  const items = [
    {
      name: 'Home',
      link: `${subDirectory}app-page/home`,
    },

    // {
    //     name: "PrintSetup",
    //     link: `${subDirectory}saleslayouts/print-selection`,
    // },
  ];
  useEffect(() => {
    configFooterfun(sizeCheckList, checkedList);
  }, [checkedList, checkedList]);

  const columns = [
    {
      title: 'Sl.No',
      align: 'center',
      key: 'sno',
      width: '50px',
      render: (text, object, index) => (
        <a style={{ color: 'black' }}>{index + 1}</a>
      ),
    },
    {
      title: 'Style',
      dataIndex: 'StyleName',
      key: 'StyleName',
      width: '50px',
      align: 'left',
      render: (text, record) => (
        <a
          style={{ color: 'black' }}
        >{`${text} (${segmentData?.find(({ value }) => value === record?.PrintTypeId)?.label})`}</a>
      ),
    },
    {
      title: 'Options',
      dataIndex: 'OptionDetails',
      key: 'OptionDetails',
      width: '100px',
      align: 'left',
      render: (OptionDetails) => (
        <a style={{ color: 'black' }}>
          {OptionDetails?.map((item) => item.ConfigName).join(',')}
        </a>
      ),
      ellipsis: true,
    },
    {
      title: 'Default Print',
      dataIndex: 'SetasDefault',
      key: 'SetasDefault',
      width: '100px',
      align: 'center',
      render: (_, record, index) => (
        <Checkbox
          checked={record.SetasDefault == 'Y'}
          onClick={() => onCheckdefault(record, index)}
        />
      ),
      ellipsis: true,
    },
    {
      title: 'Action',
      dataIndex: 'Action',
      width: '50px',
      key: 'Action',
      render: (_, record, index) =>
        sizeOptionData?.length >= 1 ? (
          <Space size="middle">
            <a>
              <EditFilled
                style={{ color: '#1292EE' }}
                onClick={() =>
                  UserType === 'Super Admin' ||
                  (UserType === 'Super Admin User' &&
                    SAAccessCommonMaster?.UpdateAccess === 'Y') ||
                  (UserType === 'Employee' && empData?.UpdateAccess === 'Y') ||
                  UserType === 'Admin'
                    ? actionsFormatter(record, index)
                    : null
                }
              />
            </a>
            <a
              onClick={() =>
                !edit &&
                (UserType === 'Super Admin' ||
                  (UserType === 'Super Admin User' &&
                    SAAccessCommonMaster?.DeleteAccess === 'Y') ||
                  (UserType === 'Employee' && empData?.DeleteAccess === 'Y') ||
                  UserType === 'Admin')
                  ? statusFormatter(index)
                  : ''
              }
            >
              <DeleteFilled
                style={{
                  color: '#FF4D4F',
                  pointerEvents: edit ? 'none' : 'auto',
                }}
              />
            </a>
          </Space>
        ) : null,
    },
  ];

  const onCheckdefault = (record, index) => {
    const { SetasDefault: currentValue, PrintTypeId } = record;
    const isSamePrintTypeExist = sizeOptionData
      ?.filter((_, idx) => index !== idx)
      ?.some((some) => some.PrintTypeId === PrintTypeId);

    if (isSamePrintTypeExist) {
      if (currentValue === 'N') {
        setSizeOptionData((prev) => {
          const samePrintTypeIdAllUnchecked = prev.map((item) => {
            if (item.PrintTypeId === PrintTypeId)
              return {
                ...item,
                SetasDefault: 'N',
              };
            return item;
          });

          return samePrintTypeIdAllUnchecked.map((item, i) => {
            if (i === index)
              return {
                ...item,
                SetasDefault: 'Y',
              };
            return item;
          });
        });
      } else {
        setSizeOptionData((prev) =>
          prev.map((item, i) => {
            if (i === index)
              return {
                ...item,
                SetasDefault: 'N',
              };
            return item;
          })
        );
      }
    } else {
      // setSizeOptionData(prev => prev.map((item, i) => ({
      //   ...item,
      //   SetasDefault: i === index ? (currentValue == 'Y' ? 'N' : 'Y') : 'N',
      // })));
      setSizeOptionData((prev) =>
        prev.map((item, i) => {
          if (i === index)
            return {
              ...item,
              SetasDefault:
                i === index ? (currentValue == 'Y' ? 'N' : 'Y') : 'N',
            };
          return item;
        })
      );
    }
  };

  useEffect(() => {
    dispatch(changeBreadCrumb({ items: items }));
    GetEditData();
    getStyles();
    fetchInitialData();
    // if (UserType === "Employee") {
    //     fetchApi()
    // }
  }, []);

  useEffect(() => {
    if (UserType === 'Employee') {
      fetchApi();
    }
  }, [UserType]);

  let configFooterfun = async (sizeCheckList, checkedList) => {
    let Checkfootername = sizeCheckList?.find(
      (item) => item.ConfigName?.toLowerCase() == 'notes'
    );
    let CheckBillnamename = sizeCheckList?.find(
      (item) => item.ConfigName?.toLowerCase() == 'billname'
    );
    let Checktermdcondition = sizeCheckList?.find(
      (item) => item.ConfigName?.toLowerCase() == 'terms&conditions'
    );
    let CheckSignature = sizeCheckList?.find(
      (item) => item.ConfigName?.toLowerCase() == 'signature'
    );
    let headerColour = sizeCheckList?.find(
      (item) => item.ConfigName?.toLowerCase() == 'header colour'
    );
    setisFooterChecking(checkedList?.includes(Checkfootername?.ConfigId));
    setisBillName(checkedList?.includes(CheckBillnamename?.ConfigId));
    setisTermscondChecking(
      checkedList?.includes(Checktermdcondition?.ConfigId)
    );
    setisSignatureChecking(checkedList?.includes(CheckSignature?.ConfigId));
    setisheadercolour(checkedList?.includes(headerColour?.ConfigId));
  };

  const fetchInitialData = async () => {
    const GettingOptions = await dispatch(
      getPrintOptions({ Data: 'printer options' })
    ).unwrap();
    if (GettingOptions?.data?.statusCode === 1) {
      setSizeCheckList(GettingOptions?.data?.data);
      let Data = GettingOptions?.data?.data?.map((item) => item.ConfigId);
      setCheckedList(Data?.length);
      SizeSelectlistonChange(Data);
    }
    const response = await dispatch(
      getPrintOptions({ Data: 'Bill Print Type' })
    ).unwrap();
    if (response?.data?.statusCode === 1) {
      setSegmentData(
        response?.data?.data?.map(({ ConfigName, ConfigId, ActiveStatus }) => {
          if (ActiveStatus === 'A')
            return { label: ConfigName, value: ConfigId };
        })
      );
      setSegmentValue(
        response?.data?.data?.find(({ ConfigName }) => ConfigName === 'Sales')
          ?.ConfigId
      );
    }
  };

  const fetchApi = async () => {
    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      EmpId: UserId,
    };
    let response = await dispatch(getEmpAccess(data)).unwrap();
    let datas = response?.data?.data?.[0]?.EmpAccessDetails?.filter(
      (item) => item.ConfigName === 'Print Forms'
    );
    setEmpData(datas?.[0]);
  };

  const GetEditData = async () => {
    let Data = {
      AppId: AppId,
      CompId: CompId,
      BranchId: BranchId,
    };
    const response = await dispatch(
      getPrintSelectionComponentData(Data)
    ).unwrap();
    if (response?.data?.statusCode == 1) {
      let TableData = response?.data?.data?.[0]?.ComponentDetails.map(
        (item) => ({
          ActiveStatus: 'A',
          OptionDetails: item.FieldDetails,
          StyleId: item.StyleId,
          SetasDefault: item.SetasDefault,
          SetasDefaultInvoice: item.SetasDefaultInvoice,
          StyleName: item.StyleName,
          Signature: item.Signature,
          PrintType: item.PrintType,
          PrintHdrName: item.PrintHdrName,
          PrintHdrColor: item.PrintHdrColor,
          Notes: item?.Notes,
          PageSize: item?.PageSize?.trim() || '3inch',
          PrintTypeId: item?.PrintTypeId,
          TermsandConditions: (item?.TermsandConditions
            ? item?.TermsandConditions
            : []
          )?.map((tc) => tc?.TermsandConditions),
        })
      )?.sort((a, b) => {
        if ((a.StyleName || '') === 'A4Standard') return 1;
        if ((b.StyleName || '') === 'A4Standard') return -1;
        const isA4orA5 = (name) => /A4|A5/i.test(name);
        const nameA = a.StyleName || '';
        const nameB = b.StyleName || '';

        // Push A4/A5 to the bottom
        if (isA4orA5(nameA) && !isA4orA5(nameB)) return 1;
        if (!isA4orA5(nameA) && isA4orA5(nameB)) return -1;

        // If both are A4/A5 or neither are, sort by natural number in name
        const numA = parseInt(nameA.match(/\d+/)?.[0]) || 0;
        const numB = parseInt(nameB.match(/\d+/)?.[0]) || 0;
        return numA - numB;
      });

      response?.data?.data?.[0]?.ComponentDetails?.length > 0
        ? setTemplateEdit(true)
        : setTemplateEdit(false);
      setSizeOptionData(TableData);
    }
  };

  const onComplete = useCallback(() => {
    setMessageData(null);
    setMessageType(null);
  }, []);

  const actionsFormatter = async (row, index) => {
    // StyleName
    setSelectedStyleName(row?.StyleName);
    const {
      StyleId,
      PrintType,
      PageSize,
      Notes,
      PrintHdrName,
      Signature,
      TermsandConditions,
      OptionDetails,
      PrintTypeId,
      PrintHdrColor,
    } = row;
    if (index >= 4) setShowMore(true);
    if (index <= 4) setShowMore(false);
    formRef.current?.setFieldsValue({ StyleId: StyleId });
    setSegmentValue(PrintTypeId);
    setCheckedList([]);
    setFileList([]);
    setTerms(['']);
    setPrintType(PrintType === 'S' ? true : false);
    setPageSize(PageSize);
    setNote(Notes);
    setBillName(PrintHdrName);
    setEdit(true);
    setSelectedColour(PrintHdrColor);
    setSelectedStyleId(StyleId);

    if (Signature) {
      const existingFile = {
        uid: '-1',
        name: 'existing-image.png',
        status: 'done',
        url: Signature,
      };

      setFileList([existingFile]);
    }

    if (TermsandConditions?.length) {
      setTerms(TermsandConditions || '');
    }

    const GettingOptions = await dispatch(
      getPrintOptions({ Data: 'printer options' })
    ).unwrap();
    if (GettingOptions?.data?.statusCode === 1) {
      setSizeCheckList(GettingOptions?.data?.data);
    }

    const helperFunction = (param) => {
      return OptionDetails.some((item) => item.ConfigName === param);
    };

    setSelectedSizeCheckedValues(OptionDetails?.map((item) => item.ConfigId));
    setSelectedSizeCheckList(
      OptionDetails?.map(({ ConfigId }) => ({ ConfigId }))
    );
    SizeSelectlistonChange(OptionDetails?.map((item) => item.ConfigId));
    dispatch(changeSelectedSlNo(helperFunction('Sl.No')));
    dispatch(changeSelectedItem(helperFunction('Item')));
    dispatch(changeSelectedMRP(helperFunction('MRP')));
    dispatch(changeSelectedDiscount(helperFunction('Discount')));
    dispatch(changeSelectedTax(helperFunction('Tax')));
    dispatch(changeSelectedQuantity(helperFunction('Quantity')));
    dispatch(changeSelectedRate(helperFunction('Rate')));
    dispatch(changeSelectedAmount(helperFunction('Amount')));
    dispatch(changeSelectedHsnCode(helperFunction('HsnCode')));
    dispatch(changeSelectedQrcode(helperFunction('Qrcode')));
    dispatch(changeSelectedSignature(helperFunction('Signature')));
    dispatch(
      changeSelectedtermsAndConditions(helperFunction('TermsandConditions'))
    );
    dispatch(changeNotes(helperFunction('Notes')));
    dispatch(changeSignatureImage(Signature));
    dispatch(changeBillName(PrintHdrName));
    dispatch(
      changeSelectedprintStyle({
        ConfigId: StyleId,
        ConfigName: styleData.find((item) => item.ConfigId === StyleId)
          ?.ConfigName,
      })
    );
  };

  const statusFormatter = async (record) => {
    await setSizeOptionData(
      sizeOptionData.filter((_, index) => index !== record)
    );
    setEdit(false);
    const GettingOptions = await dispatch(
      getPrintOptions({ Data: 'printer options' })
    ).unwrap();
    if (GettingOptions?.data?.statusCode === 1) {
      const selecetedName = styleData?.filter(
        (item) => item?.ConfigId == e
      )?.[0]?.ConfigName;
      setSizeCheckList(GettingOptions?.data?.data);
      let Data = sizeCheckList
        ?.filter((item) => item.ConfigName)
        ?.map((item) => item.ConfigId);
      setCheckedList(sizeCheckList?.length);
      SizeSelectlistonChange(Data);
    }
  };

  const getStyles = async () => {
    let Styles = await dispatch(
      getConfigType({ TypeName: 'Print Style' })
    ).unwrap();
    if (Styles?.data?.statusCode === 1) {
      setStyleData(Styles?.data?.data);
      let configId = Styles?.data?.data?.[0].ConfigId;
      let configData = Styles?.data?.data;
      handleStyle(configId);
      dispatch(
        changeSelectedprintStyle({
          ConfigId: configId,
          ConfigName: configData.find((item) => item.ConfigId === configId)
            ?.ConfigName,
        })
      );
      formRef.current?.setFieldsValue({
        StyleId: Styles?.data?.data?.[0].ConfigId,
      });

      let Data = sizeCheckList
        ?.filter((item) => item.ConfigName)
        ?.map((item) => item.ConfigId);

      SizeSelectlistonChange(Data);
    } else {
      setStyleData([]);
    }
  };

  const handleStyle = async (e, index) => {
    index && onCheckdefault('N', index);
    dispatch(changeSignatureImage(null));
    setCheckedList([]);
    setFileList([]);
    setTerms(['']);
    setNote('');
    setBillName('');
    dispatch(changeBillName(''));
    setEdit(false);
    formRef.current?.setFieldsValue({ StyleId: e });
    setSelectedStyleId(e);
    setSelectedStyleName(
      styleData.find((item) => item.ConfigId === e)?.ConfigName
    );
    dispatch(
      changeSelectedprintStyle({
        ConfigId: e,
        ConfigName: styleData.find((item) => item.ConfigId === e)?.ConfigName,
      })
    );
    const GettingOptions = await dispatch(
      getPrintOptions({ Data: 'printer options' })
    ).unwrap();
    if (GettingOptions?.data?.statusCode === 1) {
      const selecetedName = styleData?.filter(
        (item) => item?.ConfigId == e
      )?.[0]?.ConfigName;
      let filteredData = GettingOptions?.data?.data;
      setSizeCheckList(filteredData);
      let Data = filteredData
        ?.filter((item) => item.ConfigName)
        ?.map((item) => item.ConfigId);
      SizeSelectlistonChange(Data);
    }
  };

  const SizeSelectlistonChange = async (checkedValues) => {
    setCheckedList(checkedValues);
    setSelectedSizeCheckedValues(checkedValues);
    const obj = checkedValues?.map((d) => ({ ConfigId: d }));
    setSelectedSizeCheckList(obj);
    let sizeCheckList = [];
    const GettingOptions = await dispatch(
      getPrintOptions({ Data: 'printer options' })
    ).unwrap();
    if (GettingOptions?.data?.statusCode === 1) {
      let filteredData = GettingOptions?.data?.data?.filter(
        (item) => item.ConfigName
      );
      sizeCheckList = filteredData;
    }

    checkedValues?.includes(
      sizeCheckList.find((item) => item.ConfigName === 'Sl.No')?.ConfigId
    )
      ? dispatch(changeSelectedSlNo(true))
      : dispatch(changeSelectedSlNo(false));
    checkedValues?.includes(
      sizeCheckList.find((item) => item.ConfigName === 'Item')?.ConfigId
    )
      ? dispatch(changeSelectedItem(true))
      : dispatch(changeSelectedItem(false));
    checkedValues?.includes(
      sizeCheckList.find((item) => item.ConfigName === 'MRP')?.ConfigId
    )
      ? dispatch(changeSelectedMRP(true))
      : dispatch(changeSelectedMRP(false));
    checkedValues?.includes(
      sizeCheckList.find((item) => item.ConfigName === 'Discount')?.ConfigId
    )
      ? dispatch(changeSelectedDiscount(true))
      : dispatch(changeSelectedDiscount(false));
    checkedValues?.includes(
      sizeCheckList.find((item) => item.ConfigName === 'Tax')?.ConfigId
    )
      ? dispatch(changeSelectedTax(true))
      : dispatch(changeSelectedTax(false));
    checkedValues?.includes(
      sizeCheckList.find((item) => item.ConfigName === 'Quantity')?.ConfigId
    )
      ? dispatch(changeSelectedQuantity(true))
      : dispatch(changeSelectedQuantity(false));
    checkedValues?.includes(
      sizeCheckList.find((item) => item.ConfigName === 'Rate')?.ConfigId
    )
      ? dispatch(changeSelectedRate(true))
      : dispatch(changeSelectedRate(false));
    checkedValues?.includes(
      sizeCheckList.find((item) => item.ConfigName === 'Amount')?.ConfigId
    )
      ? dispatch(changeSelectedAmount(true))
      : dispatch(changeSelectedAmount(false));
    checkedValues?.includes(
      sizeCheckList.find((item) => item.ConfigName === 'HsnCode')?.ConfigId
    )
      ? dispatch(changeSelectedHsnCode(true))
      : dispatch(changeSelectedHsnCode(false));
    checkedValues?.includes(
      sizeCheckList.find((item) => item.ConfigName === 'Qrcode')?.ConfigId
    )
      ? dispatch(changeSelectedQrcode(true))
      : dispatch(changeSelectedQrcode(false));
    checkedValues?.includes(
      sizeCheckList.find((item) => item.ConfigName === 'signature')?.ConfigId
    )
      ? dispatch(changeSelectedSignature(true))
      : dispatch(changeSelectedSignature(false));
    checkedValues?.includes(
      sizeCheckList.find((item) => item.ConfigName === 'CashierName')?.ConfigId
    )
      ? dispatch(changeSelectedCashierName(true))
      : dispatch(changeSelectedCashierName(false));
    checkedValues?.includes(
      sizeCheckList.find((item) => item.ConfigName === 'Logo')?.ConfigId
    )
      ? dispatch(changeSelectedLogo(true))
      : dispatch(changeSelectedLogo(false));
    checkedValues?.includes(
      sizeCheckList.find((item) => item.ConfigName === 'Credit details')
        ?.ConfigId
    )
      ? dispatch(changeSelectedCredit(true))
      : dispatch(changeSelectedCredit(false));
    checkedValues?.includes(
      sizeCheckList.find((item) => item.ConfigName === 'terms&conditions')
        ?.ConfigId
    )
      ? dispatch(changeSelectedtermsAndConditions(true))
      : dispatch(changeSelectedtermsAndConditions(false));
    checkedValues?.includes(
      sizeCheckList.find((item) => item.ConfigName === 'Notes')?.ConfigId
    )
      ? dispatch(changeNotes(true))
      : dispatch(changeNotes(false));
  };

  const handleOptions = async () => {
    const { StyleId } = formRef.current?.getFieldsValue() ?? {};

    const showError = (msg) => {
      setMessageType('error');
      setMessageData(msg);
    };

    const showSuccess = (msg) => {
      setMessageType('success');
      setMessageData(msg);
    };

    const getConcatenatedArray = () => {
      return selectedSizeCheckList
        .map((obj1) => {
          const obj2 = sizeCheckList.find(
            (item) => item.ConfigId === obj1.ConfigId
          );
          return obj2
            ? { ConfigId: obj1.ConfigId, ConfigName: obj2.ConfigName }
            : null;
        })
        .filter(Boolean);
    };

    const buildOptionObject = () => ({
      StyleId,
      StyleName: styleData?.find(
        (item) => parseInt(item?.ConfigId) === parseInt(StyleId)
      )?.ConfigName,
      SetasDefault: sizeOptionData?.find(
        (item) => parseInt(item?.PrintTypeId) === parseInt(segmentValue)
      )?.SetasDefault,
      SetasDefaultInvoice: sizeOptionData?.find(
        (item) => parseInt(item?.PrintTypeId) === parseInt(segmentValue)
      )?.SetasDefaultInvoice,
      OptionDetails: getConcatenatedArray(),
      ActiveStatus: 'A',
      Signature: fileList?.[0]?.url,
      TermsandConditions: terms
        ?.filter((item) => item.trim() !== '')
        .map((item) => item.trim()),
      Notes: Notes,
      PageSize: PageSize,
      PrintHdrName: BillName,
      PrintType: PrintType ? 'S' : 'C',
      PrintTypeId: segmentValue,
      PrintHdrColor: getConcatenatedArray().some(
        (e) => e?.ConfigName?.toLowerCase() == 'header colour'
      )
        ? selectedColour
        : null,
    });

    // Validation
    if (isSignatureChecking && fileList?.length === 0)
      return message.warning('Please upload Signature');
    if (isTermscondChecking && (!terms?.length || terms?.[0] === ''))
      return message.warning('Please add at least 1 term');
    if (!StyleId || !selectedSizeCheckList?.length)
      return showError('Please Give Option Data');

    const isStyleIdMatching = sizeOptionData?.some(
      (item) => item.StyleId === StyleId
    );
    const allSameStyles = sizeOptionData?.filter(
      (item) => item.StyleId === StyleId
    );
    const isPrintTypeIdMatches = allSameStyles?.some(
      (item) => item.PrintTypeId === segmentValue
    );

    if (edit && isStyleIdMatching) {
      // EDIT MODE
      const updatedArray = sizeOptionData.map((item) => {
        if (item.StyleId === StyleId && item.PrintTypeId === segmentValue) {
          return {
            ...buildOptionObject(),
          };
        }
        return item;
      });

      setSizeOptionData(updatedArray);
      setEdit(false);
      showSuccess('Data Edited Successfully');
      setSelectedColour('#00000');
      return;
    }

    // ADD MODE
    if (isStyleIdMatching && isPrintTypeIdMatches) {
      return showError('Data Already Exists');
    }

    setSizeOptionData([...sizeOptionData, buildOptionObject()]);
    setEdit(false);
    showSuccess('Data Added Successfully');
    setSelectedColour('#000000');
  };

  const handleCancel = () => {
    // formRef?.current?.resetFields()
    // setSelectedStyleId(null)
    // setSelectedSizeCheckedValues([])
    setEdit(false);
    // dispatch(changeSelectedprintStyle({ 'ConfigId': null, 'ConfigName': null }));
  };

  const onfinish = async (values) => {
    if (!templateEdit && sizeOptionData?.length == 0) {
      setMessageType('error');
      setMessageData('Please Setup the Screen');
    } else {
      let TemplateDetails = [];
      if (sizeOptionData?.length > 0) {
        sizeOptionData?.map((item) =>
          TemplateDetails.push({
            SizeId: null,
            StyleId: item.StyleId,
            SetasDefault: item.SetasDefault,
            SetasDefaultInvoice: item.SetasDefaultInvoice,
            PrintHdrColor: item.PrintHdrColor,
            PrintTypeId: item?.PrintTypeId,
            SizeDetails: item.OptionDetails.map((item) => ({
              OptionId: item.ConfigId,
            })),
            ...(item?.TermsandConditions?.length > 0
              ? {
                  PrintTermsandConditions: (item?.TermsandConditions
                    ? item?.TermsandConditions
                    : []
                  )?.map((item) => {
                    return {
                      TermsandConditions: item,
                    };
                  }),
                }
              : {}),
            ...(item?.Notes ? { Notes: item.Notes } : {}),
            ...(item?.PageSize ? { PageSize: item.PageSize } : {}),
            ...(item?.PrintHdrName ? { PrintHdrName: item.PrintHdrName } : {}),
            ...(item?.Signature ? { Signature: item?.Signature } : {}),
            PrintType: item?.PrintType,
          })
        );
      }

      const Data = {
        CompId: CompId,
        BranchId: BranchId,
        AppId: AppId,
        TemplateDetails: TemplateDetails,
        CreatedBy: UserId,
      };
      const response = await dispatch(
        templateEdit
          ? putPrintSelectionComponentData(Data)
          : postPrintSelectionComponentData(Data)
      ).unwrap();

      if (response?.data?.statusCode == 1) {
        GetEditData();
        setMessageType('success');
        setMessageData(response?.data?.response);
      }
    }
  };

  const onCheckAllChange = (e) => {
    let Data = sizeCheckList
      ?.filter((item) => item.ConfigName)
      ?.map((item) => item.ConfigId);
    setCheckedList(e.target.checked ? sizeCheckList?.length : []);
    e.target.checked
      ? SizeSelectlistonChange(Data)
      : SizeSelectlistonChange([]);
  };

  const onChangeToggle = async (e) => {
    if (e) {
      setPrintType(true);
      await dispatch(changethemeFormat(true));
    } else {
      setPrintType(false);
      await dispatch(changethemeFormat(false));
    }
  };

  const onChangepageSize = async (e) => {
    console.log(e, 'pagesize');
    // if (e) {
    setPageSize(e);
    //   // await dispatch(changethemeFormat(true))
    // } else {
    //   setPageSize(false);
    //   // await dispatch(changethemeFormat(false))
    // }
  };

  const showmoreFun = (e) => {
    if (showMore) {
      setShowMore(!showMore);
    } else {
      setShowMore(!showMore);
    }
  };

  const handleCancelimg = () => setPreviewOpen(false);

  const handleUploadChange = ({ fileList: newFileList }) => {
    const updatedList = newFileList.map((file) => {
      if (file.response?.image) {
        file.url = file.response.image; // Set the returned URL for preview
        dispatch(changeSignatureImage(file.response.image));
      }
      return file;
    });
    if (updatedList?.length == 0) {
      dispatch(changeSignatureImage(null));
    }
    setFileList(updatedList);
  };
  const handlePreview = async (file) => {
    setPreviewImage(file.url || file.thumbUrl);
    setPreviewOpen(true);
    setPreviewTitle(file.name || '');
  };

  const handleChange = (index, value) => {
    const newTerms = [...terms];
    newTerms[index] = value;
    setTerms(newTerms);
  };

  const handleAdd = () => {
    const lastTerm = terms[terms.length - 1];

    if (!lastTerm || typeof lastTerm !== 'string' || !lastTerm.trim()) {
      message.warning('Please fill in the current term before adding another.');
      return;
    }

    setTerms([...terms, '']);
  };

  const handleRemove = (index) => {
    const newTerms = [...terms];
    newTerms.splice(index, 1);
    setTerms(newTerms);
  };

  const beforeUpload = (file) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      message.error('You can only upload image files!');
    }
    return isImage || Upload.LIST_IGNORE;
  };

  const handleOnChangeSegment = (params) => {
    setSegmentValue(params);
  };

  // const filterCheckListBasedOnSegmentValue = (params) => {
  //   const checkList = params?.filter((item) => item.ConfigName);
  //   // Sl.No
  //   // Item
  //   // MRP
  //   // Discount
  //   // Quantity
  //   // Rate
  //   // Amount
  //   // HsnCode
  //   // Qrcode
  //   // signature
  //   // Notes
  //   // terms&conditions

  //   let filteredCheckList = checkList;
  //   // if (segmentValue === 'Sales Quotation') {
  //   //  Sl.No
  //   // Item
  //   // MRP
  //   // Discount
  //   // Quantity
  //   // Rate
  //   // Amount
  //   // Qrcode
  //   // signature
  //   // Notes
  //   // terms&conditions
  //   //   filteredCheckList = checkList.filter(item => );
  //   // } else if (segmentValue === 'Purchase Order') {
  //   //   filteredCheckList = checkList.filter(item => );
  //   // } else if (segmentValue === 'Delevery Challan') {
  //   //   filteredCheckList = checkList.filter(item => );
  //   // }
  //   return filteredCheckList;

  // }

  return (
    <>
      <Messages
        messageType={messageType}
        messageData={messageData}
        onComplete={onComplete}
      />
      <div>
        <Form ref={formRef}>
          <div
            style={{
              display: 'flex',
              flexDirection: 'row',
              flexWrap: 'wrap',
              columnGap: '1rem',
              alignItems: 'center',
            }}
          >
            <div className="printSelectDefaultDIvs">
              <br />
              <Form.Item
                name="StyleId"
                rules={[
                  {
                    required: true,
                    message: 'Please Select Style',
                  },
                ]}
              >
                <div
                  style={{
                    display: 'flex',
                    flexWrap: 'wrap',
                    gap: '1rem',
                    marginTop: '1rem',
                    alignItems: 'center',
                  }}
                >
                  {visibleConfigs?.map((item, index) => (
                    <div style={{ display: 'flex', flexDirection: 'column' }}>
                      <div
                        key={item.ConfigId}
                        style={{
                          width: '70px',
                          borderRadius: '8px',
                          textAlign: 'center',
                          boxShadow:
                            item.ConfigId == selectedStyleId
                              ? '0 2px 6px rgba(0,0,0,0.1)'
                              : '',
                          border:
                            item.ConfigId == selectedStyleId
                              ? '2px solid #0072c4ff'
                              : '1px solid #a7a7a7',
                        }}
                        onClick={() => handleStyle(item.ConfigId, index)}
                      >
                        <img
                          src={defaultImage}
                          alt={defaultImage}
                          style={{
                            height: '80px',
                            objectFit: 'cover',
                            borderRadius: '4px',
                          }}
                        />
                      </div>
                      <div
                        style={{
                          fontSize: '0.85rem',
                          color: '#333',
                          textAlign: 'center',
                        }}
                      >
                        {item.ConfigName}
                      </div>
                    </div>
                  ))}
                  {styleData.length > 4 && (
                    <div
                      onClick={showmoreFun}
                      style={{
                        marginBottom: '0.75rem',
                        color: showMore ? '#ee0000ff' : '#1890ff',
                        fontSize: '0.8rem',
                        cursor: 'pointer',
                        fontWeight: '500',
                        display: 'flex',
                        alignItems: 'center',
                        gap: '0.3rem',
                        textDecoration: 'underline',
                      }}
                    >
                      {showMore ? 'View Less' : 'View All...'}{' '}
                      <span>
                        {showMore ? (
                          <FaChevronUp size={12} />
                        ) : (
                          <FaChevronDown size={12} />
                        )}
                      </span>
                    </div>
                  )}
                </div>
              </Form.Item>
            </div>

            <div className="customisedStandardA4A5">
              {
                <div
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    gap: '1rem',
                    backgroundColor: '#ffffffff',
                    padding: '0.65rem 0.6rem',
                    borderRadius: '10px',
                    // boxShadow: '0 2px 8px #0000001a',
                    border: '1px solid #bdbdbdff',
                    maxWidth: 'fit-content',
                    margin: '10px 0 0 0',
                  }}
                >
                  <span
                    style={{
                      fontWeight: '500',
                      color: '#555',
                      fontSize: '12px',
                    }}
                  >
                    Customized
                    <Tooltip title="Print will stop when the content finishes. It won’t waste paper.">
                      <InfoCircleOutlined
                        style={{
                          color: '#1890ff',
                          cursor: 'pointer',
                          marginLeft: '5px',
                        }}
                      />
                    </Tooltip>
                  </span>

                  <Switch checked={PrintType} onChange={onChangeToggle} />
                  <span
                    style={{
                      fontWeight: '500',
                      color: '#555',
                      fontSize: '12px',
                    }}
                  >
                    Standard
                    <Tooltip title=" Print will take full paper, even if there's less content.">
                      <InfoCircleOutlined
                        style={{
                          color: '#1890ff',
                          cursor: 'pointer',
                          marginLeft: '5px',
                        }}
                      />
                    </Tooltip>
                  </span>
                </div>
              }
              <div
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: '1rem',
                  backgroundColor: '#f5f5f5',
                  padding: '0.75rem 1rem',
                  borderRadius: '12px',
                  boxShadow: '0 2px 8px rgba(0, 0, 0, 0.1)',
                  maxWidth: 'fit-content',
                  margin: '1rem 0 0 0',
                }}
              >
                {['3inch', '2inch', 'A4', 'A5'].map((size) => (
                  <span
                    key={size}
                    onClick={() => onChangepageSize(size)}
                    style={{
                      fontWeight: '500',
                      color: PageSize === size ? '#1890ff' : '#555',
                      cursor: 'pointer',
                      padding: '4px 10px',
                      borderRadius: '8px',
                      backgroundColor:
                        PageSize === size ? '#e6f4ff' : 'transparent',
                      transition: 'all 0.2s ease',
                    }}
                  >
                    {size}
                  </span>
                ))}
              </div>

              <div style={{ margin: '1rem 0', width: '100%' }}>
                <Segmented
                  options={segmentData}
                  value={segmentValue}
                  onChange={handleOnChangeSegment}
                  block
                  className="segmentData-style"
                  disabled={edit}
                />
              </div>
            </div>
          </div>

          <div className="selectBillFiledPrint">
            <div
              style={{
                display: 'flex',
                width: '305px',
                justifyContent: 'center',
                alignItems: 'center',
                gap: '1rem',
                justifyContent: 'flex-start',
              }}
            >
              {selectedStyleId ? (
                <Checkbox
                  // indeterminate={indeterminate}
                  onChange={onCheckAllChange}
                  checked={checkAll}
                >
                  Select All
                </Checkbox>
              ) : (
                ''
              )}
            </div>
            <Checkbox.Group
              style={{
                width: '100%',
              }}
              onChange={SizeSelectlistonChange}
              value={selectedSizeCheckedValues}
            >
              <Row>
                {sizeCheckList
                  ?.filter(
                    (item) =>
                      item.ConfigName &&
                      (SelectedStyleName == 'TaxInvoice' ||
                        item.ConfigName != 'Header Colour')
                  )
                  ?.map((value, key) => (
                    <Checkbox
                      style={{ padding: '12px' }}
                      value={value?.ConfigId}
                      key={value?.ConfigId}
                    >
                      {value.ConfigName}
                    </Checkbox>
                  ))}
              </Row>
            </Checkbox.Group>
          </div>

          <div className="selectBillFiledInput">
            {isFooterChecking && (
              <div style={{ marginTop: '1rem' }}>
                <Title level={5} style={{ marginBottom: 12 }}>
                  Notes
                </Title>
                <InputField
                  isOnChange={Notes}
                  label={<label>notes Description</label>}
                  value={Notes}
                  onChange={(e) => {
                    setNote(e.target.value);
                  }}
                />
              </div>
            )}

            {
              <div style={{ marginTop: '1rem' }}>
                <Title level={5} style={{ marginBottom: 12 }}>
                  BillName
                </Title>
                <InputField
                  isOnChange={BillName}
                  label={<label>Bill Name</label>}
                  value={BillName}
                  onChange={(e) => {
                    setBillName(e.target.value);
                    dispatch(changeBillName(e.target.value));
                  }}
                />
              </div>
            }

            {isSignatureChecking && (
              <div
                style={{
                  marginTop: '1rem',
                  display: 'flex',
                  flexWrap: 'wrap',
                  gap: '10px',
                }}
              >
                <Title level={5} style={{ marginBottom: 12 }}>
                  Upload Signature:
                </Title>
                <Upload
                  name="file"
                  action="https://api.pozo.app/pozo-common-image-api//upload"
                  listType="picture-card"
                  fileList={fileList}
                  onChange={handleUploadChange}
                  onPreview={handlePreview}
                  showUploadList={{ showRemoveIcon: true }}
                  maxCount={1}
                  accept="image/*"
                  beforeUpload={beforeUpload}
                >
                  {fileList.length < 1 && (
                    <div>
                      <UploadOutlined
                        style={{
                          fontSize: 20,
                          marginBottom: 0,
                          marginRight: 5,
                        }}
                      />
                      Click to Upload
                    </div>
                  )}
                </Upload>

                <Modal
                  visible={previewOpen}
                  title={previewTitle}
                  footer={null}
                  onCancel={handleCancelimg}
                >
                  <img
                    alt="Preview"
                    style={{ width: '100%' }}
                    src={previewImage}
                  />
                </Modal>
              </div>
            )}
            {isheadercolour && SelectedStyleName == 'TaxInvoice' && (
              <div style={{ marginTop: '1rem' }}>
                <Title level={5} style={{ marginBottom: 12 }}>
                  Header Color
                </Title>
                <ColorPicker
                  value={selectedColour}
                  onChange={setSelectedColour}
                  placeholder="Select color"
                />
              </div>
            )}
            {isTermscondChecking && (
              <div style={{ marginTop: '1rem' }}>
                <Title level={5} style={{ marginBottom: 12 }}>
                  Terms and Conditions
                </Title>
                {terms.map((term, index) => (
                  <Space
                    key={index}
                    style={{ display: 'flex', marginBottom: 4 }}
                    align="center"
                  >
                    <Input.TextArea
                      placeholder={`eg:- Amount not Refunded #${index + 1}`}
                      value={term}
                      onChange={(e) => handleChange(index, e.target.value)}
                      autoSize={{ minRows: 1, maxRows: 3 }}
                      style={{ width: 290 }}
                    />
                    {terms.length > 1 && (
                      <MinusCircleOutlined
                        onClick={() => handleRemove(index)}
                        style={{ color: 'red', cursor: 'pointer' }}
                      />
                    )}
                  </Space>
                ))}

                {/* <Button
                  type="dashed"
                  onClick={handleAdd}
                  icon={<PlusOutlined />}
                  size="small"
                  style={{ marginTop: 8 }}
                >
                  Add Term
                </Button> */}
                <button onClick={handleAdd} className="handleAddBTN">
                  <PlusOutlined /> Add Term
                </button>
              </div>
            )}
            <div
              style={{
                width: '100%',
                display: 'flex',
                justifyContent: 'right',
                gap: '1rem',
                margin: '0.5rem 0rem',
              }}
            >
              <div
                className="size-save-button"
                style={{ color: '#fff' }}
                onClick={handleOptions}
              >
                {edit ? 'Add' : 'Save'}
              </div>
              {edit && (
                <div
                  className="size-Cancel-button"
                  style={{ color: '#fff' }}
                  onClick={handleCancel}
                >
                  {' '}
                  Cancel{' '}
                </div>
              )}
            </div>
          </div>

          {sizeOptionData?.length > 0 && (
            <div className="component-table">
              <Tables
                columns={columns}
                data={sizeOptionData}
                dataSource={sizeOptionData}
              />{' '}
            </div>
          )}
        </Form>
        <div className="SelectComp-SubmitButton">
          <Buttons
            buttonText="Submit"
            color="901D77"
            icon={<ArrowRightOutlined />}
            htmlType={true}
            handleSubmit={onfinish}
            disabled={
              UserType === 'Super Admin' || UserType === 'Admin'
                ? false
                : !(
                    empData?.AddAccess === 'Y' ||
                    SAAccessCommonMaster?.AddAccess === 'Y' ||
                    ((empData?.UpdateAccess === 'Y' ||
                      SAAccessCommonMaster?.UpdateAccess === 'Y') &&
                      templateEdit)
                  )
            }
          />
        </div>
      </div>
    </>
  );
});

export default SelectionComponent;
