import { useDispatch, useSelector } from 'react-redux';
// import { useApplyOfferto_CardDetail } from '../../UtillComponents/BSNavBarOffer/BSNavBarOffer_CustomHooks.jsx';
import { useApplyOfferto_CardDetail } from '../UtillComponents/BSNavBarOffer/BSNavBarOffer_CustomHooks.jsx';
import {
  ChangeTotalAmount,
  globalExtraTotalAmount,
} from '../../../../Features/ExteraCharges/ExtraCharges.js';
import {
  changeOrderCardDetails,
  GlobalOrderCardDetails,
  GlobalBookingType,
  changeReorderHoldDetails,
  changeReorderProductDetails,
  changeUnpaidData,
  ChangeSelectedCustDisable,
  changeSelectedOption,
  changeBookingType,
  changeTokenOnly,
  changeAllProductTokenAvailable,
  ChangeOverAllDiscSales,
  ChangeOverAllDiscEstimate,
  changeSelProdWiseEst,
  GlobalDefaultBookingType,
  PostBlockSlots,
  changeBillEditingMode,
  changePreviousOrderPayment,
  changePreviousOrderOfferDetail,
  GlobalSalesBillEdit,
} from '../../../../Features/BookingScreen/BookingData/BookingData';
import {
  changeholddata,
  gettinghold,
  puttinghold,
} from '../../../../Features/BookingScreen/HoldOption/HoldOption.js';
import {
  getSelectedFavItems,
  getLayoutproductCard,
  getCardDataWithoutSubmodule,
  getCardDataWithoutSub,
} from '../../../../Features/BookingScreen/BookingData/BookingData';
import {
  ChangeFullFreeProductList,
  changeFullOfferAppliedProducts,
  GlobalFreeProdList,
  GlobalOfferAppliedProducts,
} from '../../../../Features/Offer/Offernew/BookingOffernew.js';
import { getCustomerDisplayWindow } from '../../../../Features/customerDisplayWindow/customerDisplayWindow.js';
import {
  StoredSessionData,
  getTemplateData,
} from '../../../../Features/ThemeChange/ThemeChange';
import { PreferenceData } from '../../../../Features/BookingScreen/BookingData/BookingData';
import { ApplicationPreferences } from '../../../../Features/BrachLogin/BranchLogin.js';
import { useDateStore } from '../../../../Features/BookingScreen/BookingData/DateStore.js';

// Custom hook for remove from cart functionality
export const useRemoveFromCart = () => {
  const dispatch = useDispatch();
  const applyOffer = useApplyOfferto_CardDetail();

  // Selectors
  const OrderCardDetail = useSelector(GlobalOrderCardDetails);
  const BookingType = useSelector(GlobalBookingType);
  const OrderType = useSelector((state) => state.BookingData.OrderType);
  const GlobalExtraCharge = useSelector(globalExtraTotalAmount);
  const OfferFreeProduct = useSelector(GlobalFreeProdList);
  const GlobalOfferAppliedProductsData = useSelector(
    GlobalOfferAppliedProducts
  );
  const defaultBookingType = useSelector(GlobalDefaultBookingType);
  const salesBillEdit = useSelector(GlobalSalesBillEdit);
  const ReportholdData = useSelector(
    (state) => state.BookingData.ReorderHoldDetails
  );
  const templateData = useSelector(getTemplateData);
  const preferenceDatas = useSelector(PreferenceData);
  const SessionData = useSelector(StoredSessionData);
  const appPreferences = useSelector(ApplicationPreferences);
  const { selectedDate } = useDateStore();

  // Computed values
  const preferenceDetails = preferenceDatas?.[0]?.SettingDtlDetails;
  const preferenceOffer =
    preferenceDetails?.find((item) => item.SettingIdName === 'Offer')
      ?.SettingValue === 'Y';
  const OfferCheckedInSetup = templateData?.BookingNavbar?.[1]?.some(
    (item) => item?.OptionName == 'Offer'
  );

  const salespagefields = appPreferences?.find(
    (pref) => pref?.PreferredCatName === 'Sales Page Fields'
  )?.PreferenceCatDetails;
  const AvailableDate = salespagefields?.find(
    (type) =>
      type?.PreferredSubCatName?.toLowerCase() === 'available date' &&
      type?.PreferredStatus === 'Y'
  );

  // Constants from session
  const BranchId = SessionData?.BranchId;
  const AppId = SessionData?.AppId;
  const CompId = SessionData?.CompId;
  const UserId = SessionData?.UserId;

  // Helper function to unblock slots
  const UnblockSlots = async (newCartItem) => {
    console.log('Unblocking slots for item:', newCartItem);
    let BlockPostdata = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      ProductList: [
        {
          ProdId: newCartItem?.ProdId,
          InwardDtlId: newCartItem?.InwardDtlId,
          SinglePc: newCartItem?.SinglePc,
          Qty: newCartItem?.OrderQty,
          Date: newCartItem?.BookedDate,
        },
      ],
      Status: 'UnBlock',
      CreatedBy: UserId,
    };
    await dispatch(PostBlockSlots(BlockPostdata)).unwrap();
  };

  // Helper function to check if item is a free product
  const isFreeProduct = (item) => {
    return OfferFreeProduct?.some(
      (exp) => exp?.InwardDtlId == item?.InwardDtlId
    );
  };

  // Helper function to check if two items are the same
  const isSameItem = (cartItem, item, orderType) => {
    console.log('Comparing items:', cartItem, item, orderType);
    const baseCondition =
      //     cartItem?.ProdId === item?.ProdId &&
      //   cartItem?.InwardDtlId === item?.InwardDtlId &&
      //   cartItem?.VariantAvailableFrom === item?.VariantAvailableFrom &&
      //   cartItem?.VariantAvailableTo === item?.VariantAvailableTo &&
      //   cartItem?.BookedDate === item?.BookedDate
      cartItem?.ProdId === item?.ProdId &&
      cartItem?.InwardDtlId === item?.InwardDtlId &&
      cartItem?.OrderRate === item?.OrderRate &&
      cartItem?.BookingTypeName === item?.BookingTypeName &&
      cartItem?.BookedDate === item?.BookedDate;

    if (orderType === 'Hold') {
      return baseCondition;
    } else {
      return baseCondition && !cartItem?.SalesId;
    }
  };

  // Helper function to update extra charges after removal
  const updateExtraCharges = async (item) => {
    const filteredCharges = GlobalExtraCharge?.filter((extra) => {
      if (BookingType === 'Dine In') {
        return !(extra.ProdId === item?.ProdId && !extra.SalesId);
      } else if (BookingType === 'TakeAway') {
        return extra.ProdId !== item?.ProdId;
      }
      return true;
    });

    await dispatch(ChangeTotalAmount(filteredCharges));
  };

  // Helper function to clean up when cart becomes empty
  const resetCartState = async () => {
    await dispatch(changeReorderHoldDetails({}));
    await dispatch(changeReorderProductDetails([]));
    await dispatch(changeUnpaidData(false));
    await dispatch(ChangeSelectedCustDisable(false));
    await dispatch(changeSelectedOption(false));
    await dispatch(changeBookingType(defaultBookingType || 'TakeAway'));
    await dispatch(changeTokenOnly(false));
    await dispatch(changeAllProductTokenAvailable(false));
    await dispatch(ChangeOverAllDiscSales(null));
    await dispatch(ChangeOverAllDiscEstimate(null));
    await dispatch(changeSelProdWiseEst([]));
    await dispatch(ChangeTotalAmount([]));
    dispatch(changeBillEditingMode(false));
    await dispatch(changePreviousOrderPayment([]));
    await dispatch(changePreviousOrderOfferDetail([]));

    const customerDisplayWindow = getCustomerDisplayWindow();
    if (customerDisplayWindow && !customerDisplayWindow.closed) {
      const updatedData = {
        type: 'remove',
        keyValue: 'customer',
      };
      customerDisplayWindow.postMessage(updatedData, '*');
    }
  };

  // Helper function to remove simple non-offer items
  const removeSimpleItem = async (item) => {
    console.log('Removing simple item:', item);
    const UpdatedData = OrderCardDetail?.filter(
      (cartItem) => !isSameItem(cartItem, item, OrderType)
    );

    if (OfferCheckedInSetup && preferenceOffer) {
      await applyOffer(UpdatedData);
    } else {
      dispatch(changeOrderCardDetails(UpdatedData));
    }

    await updateExtraCharges(item);

    if (OrderCardDetail?.length <= 1) {
      await resetCartState();
    }
  };

  // Helper function to get stock badge data
  const getstockbadge = async () => {
    const data = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      ...(AvailableDate && selectedDate
        ? {
            fromDate: selectedDate?.[0],
            toDate: selectedDate?.[1],
          }
        : {}),
    };
    await dispatch(getSelectedFavItems(data)).unwrap();

    const data1 = {
      CompId: CompId,
      BranchId: BranchId,
      AppId: AppId,
      ProdSubCat: useSelector((state) => state.BookingData.ProductSubCategorie),
      ...(AvailableDate && selectedDate
        ? {
            fromDate: selectedDate?.[0],
            toDate: selectedDate?.[1],
          }
        : {}),
    };

    const data2 = {
      compId: CompId,
      branchId: BranchId,
      appId: AppId,
      prodCat: useSelector((state) => state.BookingData.ProductCategorie),
      ...(AvailableDate && selectedDate
        ? {
            fromDate: selectedDate?.[0],
            toDate: selectedDate?.[1],
          }
        : {}),
    };

    if (
      templateData?.BookingLayout?.[1]?.some(
        (item) => item?.OptionName === 'SubCategory'
      ) &&
      useSelector((state) => state.BookingData.ProductSubCategorie)
    ) {
      await dispatch(getLayoutproductCard(data1)).unwrap();
    } else if (
      !templateData?.BookingLayout?.[1]?.some(
        (item) => item?.OptionName === 'SubCategory'
      )
    ) {
      await dispatch(getCardDataWithoutSubmodule(data2)).unwrap();
    } else {
      await dispatch(getCardDataWithoutSub(data2)).unwrap();
    }
  };

  // Main removeFromCart function
  const removeFromCart = async (item, setPreviousdataLength = null) => {
    if (setPreviousdataLength) {
      setPreviousdataLength(OrderCardDetail?.length);
    }

    AvailableDate && (await UnblockSlots(item));

    // Early return for simple cases (non-offer items that are not free products)
    if (item?.Offer <= 0 && !isFreeProduct(item)) {
      return await removeSimpleItem(item);
    }

    // For complex offer cases, use the original complex logic or simplified approach
    // For now, using a simplified approach that removes the item directly
    const UpdatedData = OrderCardDetail?.filter(
      (cartItem) => !isSameItem(cartItem, item, OrderType)
    );

    if (OfferCheckedInSetup && preferenceOffer) {
      await applyOffer(UpdatedData);
    } else {
      dispatch(changeOrderCardDetails(UpdatedData));
    }

    await updateExtraCharges(item);

    if (OrderCardDetail?.length <= 1) {
      await resetCartState();
    }

    // For Hold orders, additional cleanup
    if (OrderType === 'Hold' && OrderCardDetail?.length <= 1) {
      if (salesBillEdit) {
        getstockbadge();
        dispatch(changeBillEditingMode(false));
        await dispatch(changePreviousOrderPayment([]));
        await dispatch(changePreviousOrderOfferDetail([]));
      } else {
        let putData = { OrderId: [ReportholdData?.OrderId] };
        let response = await dispatch(puttinghold(putData)).unwrap();
        if (response?.data?.statusCode == 1) {
          await getstockbadge();
          let holdingData = await dispatch(
            gettinghold({ CompId: CompId, BranchId: BranchId, AppId: AppId })
          ).unwrap();
          if (holdingData?.data?.statusCode === 1) {
            dispatch(changeholddata(holdingData?.data?.data));
          } else {
            dispatch(changeholddata([]));
          }
        }
      }
      await dispatch(changeOrderType(null));
      await dispatch(changeReorderHoldDetails({}));
    }
  };
  const decline = async (item, setPreviousdataLength = null) => {
    if (setPreviousdataLength) {
      setPreviousdataLength(OrderCardDetail?.length);
    }
    AvailableDate && (await UnblockSlots(item));
    const UpdatedData = OrderCardDetail?.filter(
      (cartItem) => !isSameItem(cartItem, item, OrderType)
    );
    const isItemInCart = OrderCardDetail?.find((cartItem) =>
      isSameItem(cartItem, item, OrderType)
    );
    console.log('isItemInCart', isItemInCart);
    if (isItemInCart?.OrderQty > 1) {
      const UpdatedCartItem =
        // if the item is already in the cart, increase the quantity of the item
        {
          ...isItemInCart,
          OrderQty: isItemInCart?.OrderQty - 1,
          TotalAmt: (isItemInCart?.OrderQty - 1) * isItemInCart?.OrderRate,
          TaxAmt: (
            ((isItemInCart?.OrderQty - 1) *
              isItemInCart?.OrderRate *
              isItemInCart?.TaxPercentage) /
            (100 + isItemInCart?.TaxPercentage)
          ).toFixed(2),
          WithoutTaxRate:
            (isItemInCart?.OrderQty - 1) * isItemInCart?.OrderRate -
            (
              ((isItemInCart?.OrderQty - 1) *
                isItemInCart?.OrderRate *
                isItemInCart?.TaxPercentage) /
              (100 + isItemInCart?.TaxPercentage)
            ).toFixed(2),
        };
      const UpdatedcardData = [UpdatedCartItem, ...UpdatedData];

      if (OfferCheckedInSetup && preferenceOffer) {
        await applyOffer(UpdatedcardData);
      } else {
        dispatch(changeOrderCardDetails(UpdatedcardData));
      }
    } else {
      dispatch(changeOrderCardDetails(UpdatedData));
    }
  };
  // Clear all items function
  const clearAllItems = async () => {
    if (OrderType === 'Hold') {
      AvailableDate && (await UnblockSlotsAll(OrderCardDetail));
      if (OfferCheckedInSetup && preferenceOffer) {
        await applyOffer([]);
      } else {
        dispatch(changeOrderCardDetails([]));
      }
      if (salesBillEdit) {
        getstockbadge();
        dispatch(changeBillEditingMode(false));
        await dispatch(changePreviousOrderPayment([]));
        await dispatch(changePreviousOrderOfferDetail([]));
      } else {
        let putData = { OrderId: [ReportholdData?.OrderId] };
        let response = await dispatch(puttinghold(putData)).unwrap();
        if (response?.data?.statusCode == 1) {
          await getstockbadge();
          let holdingData = await dispatch(
            gettinghold({ CompId: CompId, BranchId: BranchId, AppId: AppId })
          ).unwrap();
          if (holdingData?.data?.statusCode === 1) {
            dispatch(changeholddata(holdingData?.data?.data));
          } else {
            dispatch(changeholddata([]));
          }
        }
      }
      await dispatch(ChangeTotalAmount([]));
      await dispatch(changeOrderType(null));
      await dispatch(changeReorderHoldDetails({}));
    } else if (OrderType === 'Reorder') {
      const UpdatedData = OrderCardDetail?.filter(
        (cartItem) => cartItem?.SalesId
      );
      const UnOrderData = OrderCardDetail?.filter(
        (cartItem) => !cartItem?.SalesId
      );
      AvailableDate && (await UnblockSlotsAll(UnOrderData));

      if (OfferCheckedInSetup && preferenceOffer) {
        await applyOffer(UpdatedData);
      } else {
        dispatch(changeOrderCardDetails(UpdatedData));
      }
      await dispatch(changeBookingType('Dine In'));
    } else {
      AvailableDate && (await UnblockSlotsAll(OrderCardDetail));
      if (OfferCheckedInSetup && preferenceOffer) {
        await applyOffer([]);
      } else {
        dispatch(changeOrderCardDetails([]));
      }
      await dispatch(ChangeTotalAmount([]));
      await dispatch(changeUnpaidData(false));
      await dispatch(changeReorderHoldDetails({}));
      await dispatch(changeReorderProductDetails([]));
      await dispatch(ChangeSelectedCustDisable(false));
      await dispatch(changeSelectedOption(false));
      await dispatch(changeBookingType(defaultBookingType || 'TakeAway'));
      await dispatch(changeOrderType());
    }
    await dispatch(ChangeOverAllDiscSales(null));
    await dispatch(ChangeOverAllDiscEstimate(null));
    await dispatch(changeTokenOnly(false));
    await dispatch(changeAllProductTokenAvailable(false));
    await dispatch(changeSelProdWiseEst([]));
  };

  // Helper function to unblock all slots
  const UnblockSlotsAll = async (data) => {
    if (!data?.length) return;

    const ProductList = data.map((item) => ({
      ProdId: item?.ProdId,
      InwardDtlId: item?.InwardDtlId,
      SinglePc: item?.SinglePc,
      Qty: item?.OrderQty,
      Date: item?.BookedDate,
    }));

    const BlockPostdata = {
      CompId,
      BranchId,
      AppId,
      ProductList,
      Status: 'UnBlock',
      CreatedBy: UserId,
    };
    try {
      await dispatch(PostBlockSlots(BlockPostdata)).unwrap();
    } catch (err) {
      console.error('Failed to unblock slots:', err);
    }
  };

  return {
    removeFromCart,
    clearAllItems,
    UnblockSlots,
    UnblockSlotsAll,
    decline,
  };
};

export default useRemoveFromCart;
