import { useEffect, useState, lazy, Suspense } from 'react';
import { useSelector, useDispatch } 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,
  PricingAppPricingNameData,
  changeSessionData,
  GlobalScanTemplate,
  changeScanTemplate,
} from '../../Features/ThemeChange/ThemeChange';
import {
  changeProductSubCategorie,
  ChangeScreenSize,
  getConfigType,
  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);
  const ProdCat = useSelector(GlobalProductCategorie);
  console.log(templateData, 'templateData');
  const BookingLayout = templateData?.BookingLayout?.[0];
  const [ismounted, setIsmounted] = useState(false);
  const [templateLoaded, setTemplateLoaded] = useState(false);
  const PricingAppPricingName = useSelector(GlobalPricingAppPricingName);

  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 UserName = getSession("UserName");
  const SessionId =getSession("SessionId")
  const FeatureAddonData = useSelector(GlobalFeatAddOnData);
  const Scantemplatedata = useSelector(GlobalScanTemplate);

  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,
      UserName,
      SessionId
    };
    dispatch(changeSessionData(SessionData));
  }, [BranchId, FeatureAddonData]);

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

  useEffect(() => {
    ProdCat &&
      dispatch(
        getLayoutSubCategories({
          CompId: CompId,
          BranchId: BranchId,
          AppId: AppId,
          ProdCat: ProdCat,
        })
      ).unwrap();
  }, [ProdCat]);

  useEffect(() => {
    dispatch(getConfigType({ TypeName: 'Booking Type' })).unwrap();
    dispatch(ChangeRedirectStatus(true));
    dispatch(changeProductSubCategorie('NaN'));
    dispatch(
      getLayoutCategories({ CompId: CompId, BranchId: BranchId, AppId: AppId })
    ).unwrap();
    let data;
    if (UserType === 'Super Admin' || UserType === 'Super Admin User') {
      data = {
        appId: AppId,
        compId: CompId,
        branchId: BranchId,
      };
    } else {
      data = {
        appId: AppId,
        userId: UserId,
      };
    }

    dispatch(PricingAppPricingNameData(data)).unwrap();
  }, []);

  useEffect(() => {
    const fetchData = async (Plan) => {
      if (templateLoaded) 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();
        setTemplateLoaded(true);
        if (
          !templateResponse?.data?.data ||
          templateResponse.data.data.length === 0
        ) {
          Professional(Plan);
        }
      }
      // Check if template data is empty or not
    };
    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;
    console.log(
      PricingAppPricingName,
      FeatureAddonData,
      'FeatureAddonDataFeatureAddonData'
    );
    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]);
  useEffect(() => {
    const handleUnload = () => {
      const customerDisplayWindow = getCustomerDisplayWindow(); // Retrieve from your state/redux
      if (customerDisplayWindow && !customerDisplayWindow.closed) {
        customerDisplayWindow.postMessage({ type: 'refresh' }, '*');
      }
    };

    // Add beforeunload listener when the component mounts
    window.addEventListener('beforeunload', handleUnload);

    // Clean up the event listener when the component unmounts
    return () => {
      window.removeEventListener('beforeunload', handleUnload);
    };
  }, []);

  const Professional = async (data) => {
    const tempData = {
      SelectedApplication: AppId,
      AppName: AppName,
      Type: data,
    };

    dispatch(changetemplateData(tempData));
  };

  if (ismounted)
    return (
      <div
        style={{
          position: 'fixed',
          top: '0',
          left: '0',
          right: '0',
          bottom: '0',
          height: '100vh',
          width: '100vw',
          backgroundColor: '#fff',
        }}
      >
        <Loader />
      </div>
    );
  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',
                }}
              >
                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>
        </>
      ) : (
        <>{/* {Advance ? <div>Loading...</div> : null} */}</>
      )}
    </div>
  );
};

export default BookingPage;
