import React, { useEffect, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import BSLayout1 from '../../Pages/BookingScreen/Template/BSLayout1/BSLayout1.jsx';
import BSLayout2 from '../../Pages/BookingScreen/Template/BSLayout2/BSLayout2.jsx';
import BSLayout3 from '../../Pages/BookingScreen/Template/BSLayout3/BSLayout3.jsx';
import BSLayout4 from '../../Pages/BookingScreen/Template/BSLayout4/BSLayout4.jsx';
import BSLayout5 from '../../Pages/BookingScreen/Template/BSLayout5/BSLayout5.jsx';
import BSLayout6 from '../../Pages/BookingScreen/Template/BSLayout6/BSLayout6.jsx';
import BSCombo from '../../Pages/BookingScreen/Template/BSLayout7/BSCombo1.jsx';
import {
  getPrintSelectionComponentData,
  getTemplate,
  getTemplateData,
  GlobalPricingAppPricingName,
  changetemplateData,
  PricingAppPricingNameData,
  changeSessionData,
  GlobalScanTemplate,
  changeScanTemplate,
} from '../../Features/ThemeChange/ThemeChange';
import {
  ChangeBranchFinancialStatus,
  changeProductSubCategorie,
  ChangeScreenSize,
  FeatureAddon,
  getConfigType,
  getLayoutCategories,
  getLayoutSubCategories,
  getPreferenceData,
  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 { WithoutSalesSetup } from './WithoutSalesSetup.jsx';
import {
  changeholddata,
  gettinghold,
} from '../../Features/BookingScreen/HoldOption/HoldOption.js';
import { getBranchDetail } from '../../Features/BrachLogin/BranchLogin.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 Advance = PricingAppPricingName?.some(item => item.PricingName === "Advance");
  const Pro = PricingAppPricingName?.some((item) => item.PricingName === 'Customized');
  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, setFeatureAddonData] = useState([]);
  const FeatureAddonData = useSelector(GlobalFeatAddOnData)
  const Scantemplatedata = useSelector(GlobalScanTemplate)
  // useEffect(() => {
  //   dispatch(
  //     getPreferenceData({ CompId: CompId, AppId: AppId, BranchId: BranchId })
  //   );
  //   financialYear();
  //   // dispatch(getTemplate({ CompId, BranchId, AppId })).unwrap();
  // }, []);

  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);
      };
    }
  };
  // const financialYear = async () => {
  //   const response = await dispatch(
  //     getBranchDetail({ BrId: BranchId })
  //   ).unwrap();
  //   if (response?.data?.statusCode === 1) {
  //     const data = response?.data?.data?.[0];
  //     const FYStatus = data?.FYStatus;
  //     const FYStartsFrom = data?.FYStartsFrom
  //       ? new Date(data.FYStartsFrom)
  //       : null;
  //     const today = new Date();
  //     today.setHours(0, 0, 0, 0);
  //     if (FYStartsFrom) FYStartsFrom.setHours(0, 0, 0, 0);

  //     let statusToDispatch = 'N';

  //     if (FYStatus === 'N') {
  //       statusToDispatch = 'Y';
  //     } else if (FYStatus === 'Y') {
  //       if (FYStartsFrom && FYStartsFrom <= today) {
  //         statusToDispatch = 'Y';
  //       } else {
  //         statusToDispatch = 'N';
  //       }
  //     }

  //     dispatch(ChangeBranchFinancialStatus(statusToDispatch));
  //   }
  // };

  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,
  });


  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,
      };
      // getFeatureAddonData();
    }
    // dispatch(getConfigType({ TypeName: 'Booking Type' })).unwrap();
   
    dispatch(PricingAppPricingNameData(data)).unwrap();
  }, []);

  // useEffect(() => {
  //     if (Advance) {

  //         Professional('Advance');
  //     }
  // }, [Advance]);

  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
        ) {
          // If no template data, call Professional('Advance')
          Professional(Plan);
          // setIsmounted(false)
        }
        // else {
        //   setIsmounted(false)
        // }
      }
      // 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 {
        // if (hasCustomizedTemplate) {
        //   fetchData('Standard');
        // } else {
          fetchData('Standard');
          // Professional('Standard');
        // }
      }
      //  setIsmounted(false)
    }
  }, [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,
      // === 'Standard' ? 'Standard' : 'Pro'
    };

    dispatch(changetemplateData(tempData));
  };

  // const getFeatureAddonData = async () => {
  //   let featureAddon = await dispatch(
  //     FeatureAddon({ AppId: AppId, UserId: UserId })
  //   ).unwrap();

  //   if (featureAddon?.data?.statusCode === 1) {
  //     setFeatureAddonData(featureAddon?.data?.data?.[0]?.FeatAddonHdr?.[0]);
  //   } else {
  //     setFeatureAddonData([]);
  //   }
  // };
  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 ? (
        <>
          {BookingLayout === 'Layout1' && <BSLayout1 />}
          {BookingLayout === 'Layout2' && <BSLayout2 />}
          {BookingLayout === 'Layout3' && <BSLayout3 />}
          {BookingLayout === 'Layout4' && <BSLayout4 />}
          {BookingLayout === 'Layout5' && <BSLayout5 />}
          {BookingLayout === 'Layout6' && <BSLayout6 />}
          {BookingLayout?.includes('Combo') && <BSCombo />}
        </>
      ) : (
        <>{/* {Advance ? <div>Loading...</div> : null} */}</>
      )}
    </div>
  );
};

export default BookingPage;
