import { useEffect, useRef, lazy, Suspense, memo } from 'react';
import { useSelector, useDispatch, shallowEqual } from 'react-redux';
import { batch } from 'react-redux';

const BSLayout1 = lazy(
  () => import('../../Pages/BookingScreen/Template/BSLayout1/BSLayout1.jsx')
);
const BSLayout2 = lazy(
  () => import('../../Pages/BookingScreen/Template/BSLayout2/BSLayout2.jsx')
);
const BSLayout3 = lazy(
  () => import('../../Pages/BookingScreen/Template/BSLayout3/BSLayout3.jsx')
);
const BSLayout4 = lazy(
  () => import('../../Pages/BookingScreen/Template/BSLayout4/BSLayout4.jsx')
);
const BSLayout5 = lazy(
  () => import('../../Pages/BookingScreen/Template/BSLayout5/BSLayout5.jsx')
);
const BSLayout6 = lazy(
  () => import('../../Pages/BookingScreen/Template/BSLayout6/BSLayout6.jsx')
);
const BSCombo = lazy(
  () => import('../../Pages/BookingScreen/Template/BSLayout7/BSCombo1.jsx')
);

import {
  getPrintSelectionComponentData,
  getTemplate,
  getTemplateData,
  GlobalPricingAppPricingName,
  changetemplateData,
  changeSessionData,
  GlobalScanTemplate,
  changeScanTemplate,
} from '../../Features/ThemeChange/ThemeChange';
import {
  changeProductSubCategorie,
  ChangeScreenSize,
  getConfigTypeBookingType,
  getLayoutCategories,
  // getLayoutSubCategories,
  getUnpaidData,
  GlobalFeatAddOnData,
  // GlobalProductCategorie,
} from '../../Features/BookingScreen/BookingData/BookingData.js';
import { getSession } from '../../Services/Others';
import { usePaymentOptions } from '../../Pages/BookingScreen/Template/PaymentOptions.js';
import { getCustomerDisplayWindow } from '../../Features/customerDisplayWindow/customerDisplayWindow.js';
import { ChangeRedirectStatus } from '../../Features/AppPage/CenterPage.js';
import {
  changeholddata,
  gettinghold,
} from '../../Features/BookingScreen/HoldOption/HoldOption.js';
import Loader from '../../Components/Loader/Loader.jsx';

const BookingPage = () => {
  const dispatch = useDispatch();
  const templateData = useSelector(getTemplateData, shallowEqual);
  const BookingLayout = templateData?.BookingLayout?.[0];

  const templateLoadedRef = useRef(
    Object.keys(templateData)?.length > 0 ? true : false
  );
  console.log(templateData, 'templateDatatemplateData');
  const PricingAppPricingName = useSelector(
    GlobalPricingAppPricingName,
    shallowEqual
  );

  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const AppId = getSession('AppId');
  const UserId = getSession('UserId');
  const AppName = getSession('AppName');
  const UserType = getSession('UserType');
  const AuthToken = sessionStorage.getItem('auth');
  const SessionMobileNo = getSession('MobileNo');
  const FeatureAddonData = useSelector(GlobalFeatAddOnData, shallowEqual);
  const Scantemplatedata = useSelector(GlobalScanTemplate, shallowEqual);

  useEffect(() => {
    if (BranchId) {
      unpaidandHoldFun();
    }
  }, [BranchId]);
  const updateScreenSize = () => {
    dispatch(ChangeScreenSize(window.innerWidth));
  };
  useEffect(() => {
    // Set initial screen size
    updateScreenSize();

    // Add event listener to track changes in screen size
    window.addEventListener('resize', updateScreenSize);

    // Clean up the event listener on component unmount
    return () => {
      window.removeEventListener('resize', updateScreenSize);
    };
  }, []);
  const unpaidandHoldFun = async () => {
    let data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
    };
    try {
      await dispatch(getUnpaidData(data)).unwrap();
      let response = await dispatch(gettinghold(data)).unwrap();
      if (response?.data?.statusCode === 1) {
        // handleHold();
        dispatch(changeholddata(response?.data?.data));
      } else {
        dispatch(changeholddata([]));
      }
    } catch (err) {
      console.log(err);
    }
  };

  useEffect(() => {
    const SessionData = {
      CompId,
      BranchId,
      AppId,
      UserId,
      AppName,
      UserType,
      AuthToken,
      SessionMobileNo,
      FeatureAddonData,
    };
    dispatch(changeSessionData(SessionData));
  }, [BranchId, FeatureAddonData]);

  usePaymentOptions({
    CompId: CompId,
    BranchId: BranchId,
    AppId: AppId,
    UserId: UserId,
  });

  const initializeBookingPage = () => {
    batch(() => {
      dispatch(getConfigTypeBookingType({ TypeName: 'Booking Type' }));
      dispatch(ChangeRedirectStatus(true));
      dispatch(changeProductSubCategorie('NaN'));
      dispatch(getLayoutCategories({ CompId, BranchId, AppId }));
    });
  };

  useEffect(() => {
    initializeBookingPage();
  }, [CompId, BranchId, AppId]);
  useEffect(() => {
    const handleUnload = () => {
      const customerDisplayWindow = getCustomerDisplayWindow();

      if (customerDisplayWindow && !customerDisplayWindow.closed) {
        customerDisplayWindow.postMessage({ type: 'refresh' }, '*');
      }
    };

    window.addEventListener('beforeunload', handleUnload);

    return () => {
      window.removeEventListener('beforeunload', handleUnload);
    };
  }, []);

  useEffect(() => {
    const Advance = PricingAppPricingName?.some(
      (item) => item.PricingName === 'Premium'
    );
    const Pro = PricingAppPricingName?.some(
      (item) => item.PricingName === 'Pro'
    );
    const hasCustomizedTemplate = FeatureAddonData?.FeatureDtls?.some(
      (item) => item?.FeatureAddonName?.toLowerCase() === 'customized template'
    );
    if (PricingAppPricingName?.length === 0) return;

    if (PricingAppPricingName?.length > 0) {
      if (Advance) {
        fetchData('Advance');
        // Professional('Advance');
      } else if (Pro) {
        if (hasCustomizedTemplate) {
          fetchData();
        } else {
          Professional('Pro');
          // setIsmounted(false)
        }
      } else {
        fetchData('Standard');
      }
    }
  }, [PricingAppPricingName]);
  const fetchData = async (Plan) => {
    if (templateLoadedRef.current) return; // STOP duplicate calls

    const Data = { AppId, CompId, BranchId };
    if (
      Scantemplatedata?.Scantemplate &&
      Scantemplatedata?.changetemp == 'Combo'
    ) {
      console.log('dont want any changes');
    } else if (
      Scantemplatedata?.changetemp == 'Layout' &&
      (Scantemplatedata?.OldTemp == 'Combo1' ||
        Scantemplatedata?.OldTemp == 'Combo2')
    ) {
      let tempdata = {
        BookingLayout: [
          'Layout2',
          [
            {
              TemplateOptionsId: 71805,
              OptionId: 45,
              OptionName: 'Category',
            },
            {
              TemplateOptionsId: 71807,
              OptionId: 47,
              OptionName: 'Card',
            },
            {
              TemplateOptionsId: 71808,
              OptionId: 48,
              OptionName: 'Billing',
            },
            {
              TemplateOptionsId: 71809,
              OptionId: 166,
              OptionName: 'Navbar',
            },
          ],
        ],
        BookingNavbar: [
          'Navbar3',
          [
            {
              TemplateOptionsId: 71811,
              OptionId: 74,
              OptionName: 'Search',
            },
            {
              TemplateOptionsId: 71812,
              OptionId: 75,
              OptionName: 'RePrint',
            },
            {
              TemplateOptionsId: 71813,
              OptionId: 77,
              OptionName: 'QuickAdd',
            },
            {
              TemplateOptionsId: 71814,
              OptionId: 76,
              OptionName: 'DineIn',
            },
            {
              TemplateOptionsId: 71815,
              OptionId: 79,
              OptionName: 'TakeAway',
            },
            {
              TemplateOptionsId: 71816,
              OptionId: 80,
              OptionName: 'Offer',
            },
            {
              TemplateOptionsId: 71817,
              OptionId: 82,
              OptionName: 'ExtraCharge',
            },
            {
              TemplateOptionsId: 71825,
              OptionId: 130,
              OptionName: 'Hold',
            },
            {
              TemplateOptionsId: 71826,
              OptionId: 172,
              OptionName: 'AddCustomer',
            },
          ],
        ],
        BookingCategory: [
          'Category5',
          [
            {
              TemplateOptionsId: 71818,
              OptionId: 95,
              OptionName: 'Image',
            },
            {
              TemplateOptionsId: 71819,
              OptionId: 96,
              OptionName: 'Background',
            },
          ],
        ],
        BookingCard: [
          'Card4',
          [
            {
              TemplateOptionsId: 71821,
              OptionId: 117,
              OptionName: 'Background',
            },
            {
              TemplateOptionsId: 71822,
              OptionId: 119,
              OptionName: 'Price',
            },
            {
              TemplateOptionsId: 71823,
              OptionId: 120,
              OptionName: 'SmallImage',
            },
            {
              TemplateOptionsId: 71824,
              OptionId: 121,
              OptionName: 'ImageLeft',
            },
          ],
        ],
        BookingBilling: [
          'StandardBilling',
          [
            {
              TemplateOptionsId: 71825,
              OptionId: 130,
              OptionName: 'Hold',
            },
            {
              TemplateOptionsId: 71825,
              OptionId: 130,
              OptionName: 'DineIn',
            },
            {
              TemplateOptionsId: 71826,
              OptionId: 171,
              OptionName: 'Background',
            },
            {
              TemplateOptionsId: 71826,
              OptionId: 172,
              OptionName: 'AddCustomer',
            },

            {
              TemplateOptionsId: 71828,
              OptionId: 210,
              OptionName: 'Sl.No',
            },
            {
              TemplateOptionsId: 71829,
              OptionId: 211,
              OptionName: 'Item',
            },
            {
              TemplateOptionsId: 71830,
              OptionId: 214,
              OptionName: 'Quantity',
            },
            {
              TemplateOptionsId: 71831,
              OptionId: 216,
              OptionName: 'Amount',
            },
            {
              TemplateOptionsId: 71832,
              OptionId: 217,
              OptionName: 'Edit',
            },
            {
              TemplateOptionsId: 71833,
              OptionId: 218,
              OptionName: 'Delete',
            },
          ],
        ],
      };
      await dispatch(
        changeScanTemplate({
          Scantemplate: false,
          changetemp: Scantemplatedata?.changetemp,
          Template: tempdata,
          OldTemp: Scantemplatedata?.OldTemp,
        })
      );
      // setIsmounted(false)
    } else {
      const templateResponse = await dispatch(
        getTemplate({ CompId, BranchId, AppId })
      ).unwrap();
      dispatch(getPrintSelectionComponentData(Data)).unwrap();
      templateLoadedRef.current = true;
      if (
        !templateResponse?.data?.data ||
        templateResponse.data.data.length === 0
      ) {
        Professional(Plan);
      }
    }
    // Check if template data is empty or not
  };
  const Professional = async (data) => {
    const tempData = {
      SelectedApplication: AppId,
      AppName: AppName,
      Type: data,
    };

    dispatch(changetemplateData(tempData));
  };

  return (
    <div style={{ backgroundColor: '#fff !important' }}>
      {Object.keys(templateData)?.length > 0 ? (
        <>
          <Suspense
            fallback={
              <div
                style={{
                  fontSize: '14px',
                  fontFamily: 'Poppins',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  gap: '0',
                  height: '99vh',
                  overflow: 'hidden',
                  flexDirection: 'column',
                  fontWeight: '500',
                  bottom: '3rem',
                }}
              >
                Loading Layout...
                <span style={{ fontSize: '16px', fontWeight: '500' }}>
                  PozoApp
                </span>
              </div>
            }
          >
            {BookingLayout === 'Layout1' && <BSLayout1 />}
            {BookingLayout === 'Layout2' && <BSLayout2 />}
            {BookingLayout === 'Layout3' && <BSLayout3 />}
            {BookingLayout === 'Layout4' && <BSLayout4 />}
            {BookingLayout === 'Layout5' && <BSLayout5 />}
            {BookingLayout === 'Layout6' && <BSLayout6 />}
            {BookingLayout?.includes('Combo') && <BSCombo />}
          </Suspense>
        </>
      ) : (
        <Loader />
      )}
    </div>
  );
};

export default memo(BookingPage);
