// AuthContext.jsx
import React, { createContext, useContext, useState, useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { getSession } from './Services/Others';
import {
  getEmpAccesData,
  getSAdminUserAccesData,
  PricingAppPricingName,
} from './Features/BrachLogin/BranchLogin.js';
import { changePricingAppPricingName } from './Features/ThemeChange/ThemeChange.js';
import { FeatureAddon } from './Features/BookingScreen/BookingData/BookingData.js';

export const AuthContext = createContext();

export const useAuth = () => useContext(AuthContext);

export const AuthProvider = ({ children }) => {
  const AppId = getSession('AppId');
  const CompId = getSession('CompId');
  const BranchId = getSession('BranchId');
  const UserId = getSession('UserId');
  const UserType = getSession('UserType');
  const dispatch = useDispatch();

  const [Access, setAccess] = useState([]);
  const [SadminuserAccess, setSadminuserAccess] = useState([]);
  const [FeatureAddonData, setFeatureAddonData] = useState([]);
  const [ProORAdvance, setProORAdvance] = useState(false);
  const [Advance, setAdvance] = useState(false);
  const [freeProductsCount, setFreeProductsCount] = useState(0);

  let featureaddDetails = FeatureAddonData?.FeatureDtls || [];

  useEffect(() => {
    getPricingName();
    if (UserType !== 'Super Admin' && UserType !== 'Super Admin User') {
      getFeatureAddonData();
    }
  }, []);

  useEffect(() => {
    if (UserType === 'Employee') {
      getEmpAccess();
    }
    if (UserType === 'Super Admin User') {
      getSadminUserAccess();
    }
  }, [UserType]);

  const getPricingName = async () => {
    if (!AppId || !UserId) return;
    const data = {
      appId: AppId,
      userId: UserId,
    };
    try {
      const response = await dispatch(PricingAppPricingName(data)).unwrap();
      const responseData = response?.data;
      if (responseData?.statusCode !== 1) return setAdvance(false);
      const pricingData = responseData?.data;
      await dispatch(changePricingAppPricingName(pricingData));
      const hasAdvance = pricingData.some(
        (item) => item.PricingName === 'Premium'
      );
      setAdvance(hasAdvance);
      const hasProOrAdvance =
        hasAdvance || pricingData.some((item) => item.PricingName === 'Customized');
      setProORAdvance(hasProOrAdvance);
    } catch (error) {
      console.error('Error fetching pricing name:', error);
    }
  };

  const getEmpAccess = async () => {
    let data = {
      UserId: UserId,
      AppId: AppId,
      CompId: CompId,
      BranchId: BranchId,
    };
    const response = await dispatch(getEmpAccesData(data)).unwrap();
    if (response?.data?.statusCode === 1) {
      setAccess(response?.data?.data?.[0]?.EmpAccessDetails);
    }
  };
  const getSadminUserAccess = async () => {
    let data = {
      UserId: UserId,
      AppId: AppId,
    };
    const response = await dispatch(getSAdminUserAccesData(data)).unwrap();
    if (response?.data?.statusCode === 1) {
      setSadminuserAccess(response?.data?.data?.[0]?.AppMenuAccessDetails);
    }
  };
  const getFeatureAddonData = async () => {
    let featureAddon = await dispatch(
      FeatureAddon({ AppId: AppId, UserId: UserId })
    ).unwrap();
    if (featureAddon?.data?.statusCode === 1) {
      await setFeatureAddonData(
        featureAddon?.data?.data?.[0]?.FeatAddonHdr?.[0]
      );
    } else {
      await setFeatureAddonData([]);
    }
  };

  return (
    <AuthContext.Provider
      value={{
        UserType,
        Access,
        SadminuserAccess,
        Advance,
        ProORAdvance,
        featureaddDetails,
        freeProductsCount,
        setFreeProductsCount,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};
