import { NoSsr, styled, Typography, useMediaQuery, useTheme } from "@mui/material";
import { Box } from "@mui/system";
import { useRouter } from "next/router";
import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import useGetLastOrderWithoutReview from "api-manage/hooks/react-query/review/useGetLastOrderWithoutReview";
import useReviewReminderCancel from "api-manage/hooks/react-query/review/useReviewReminderCancel";
import { useWishListGet } from "api-manage/hooks/react-query/wish-list/useWishListGet";

import {
  setFilterData,
  setStoreSelectedItems,
  setStoreSelectedItems2,
} from "redux/slices/categoryIds";
import { setWishList } from "redux/slices/wishList";
import { baseUrl } from "api-manage/MainApi";
import CashBackPopup from "components/cash-back-popup/CashBackPopup";
import { getCurrentModuleType } from "helper-functions/getCurrentModuleType";
import { getToken } from "helper-functions/getToken";
import { ModuleTypes } from "helper-functions/moduleTypes";
import { t } from "i18next";
import { setWelcomeModal } from "redux/slices/utils";
import { CustomStackFullWidth } from "styled-components/CustomStyles.style";
import PushNotificationLayout from "../PushNotificationLayout";
import CustomModal from "../modal";
import LastOrderReview from "./LastOrderReview";
import SearchWithTitle from "./SearchWithTitle";
import Grocery from "./module-wise-components/Grocery";
import Shop from "./module-wise-components/ecommerce";
import FoodModule from "./module-wise-components/food";
import Parcel from "./module-wise-components/parcel/Index";
import Pharmacy from "./module-wise-components/pharmacy/Pharmacy";

import TopBanner from "./top-banner";
import TaxiSearchPanel from "components/home/module-wise-components/rental/components/global/search/TaxiSearchPanel";
import { useGetWishList } from "api-manage/hooks/react-query/rental-wishlist/useGetWishlist";
import Rental from "components/home/module-wise-components/rental/Rental";
import { useGetFailedPayment } from "api-manage/hooks/react-query/useGetFailedPayment";
import IncompleteOrderModal from "components/home/IncompleteOrderModal";
import PaymentMethod from "components/checkout/PaymentMethod";
import useGetOfflinePaymentOptions from "api-manage/hooks/react-query/offlinePayment/useGetOfflinePaymentOptions";
import { getDigitalMethodFromZone, handleFailedOrderPlace } from "utils/CustomFunctions";
import { useQuery } from "react-query";
import { GoogleApi } from "api-manage/hooks/react-query/googleApi";
import { useUpdatePaymentMethod } from "api-manage/hooks/react-query/payment-method/useUpdatePaymentMethod";
import { useUpdatePaymentByWallet } from "api-manage/hooks/react-query/useUpdatePaymentByWallet";
import { onErrorResponse } from "api-manage/api-error-response/ErrorResponses";

export const HomeComponentsWrapper = styled(Box)(({ theme }) => ({
  width: "100%",
  gap: "8px",
}));

const HomePageComponents = ({ configData, landingPageData }) => {
  const [wishListsData, setWishListsData] = useState();
  const [orderId, setOrderId] = useState(null);
  const [open, setOpen] = useState(false);
  const [openIncompleteOrder, setOpenIncompleteOrder] = useState(false);
  const [paymentMethod, setPaymentMethod] = useState(null);
  const [openPaymentModal, setOpenPaymentModal] = useState(false);
  const [dontShowAgain, setDontShowAgain] = useState(false);


  const { profileInfo } = useSelector((state) => state.profileInfo);
  const router = useRouter();
  const dispatch = useDispatch();
  const token = getToken();
  const { welcomeModal } = useSelector((state) => state.utilsData);
  const moduleType = getCurrentModuleType();
  const { refetch: refetchFailedPayment, data: failPayment } =
    useGetFailedPayment("", (res) => {
      if (res) {
        const orderId = res?.order_id;
        const isHidden = localStorage.getItem(`incomplete_order_hidden_${orderId}`);
        if (!isHidden) {
          setOpenIncompleteOrder?.(true);
        }
      }
    });
  const [currentLatLng, setCurrentLatLng] = useState(null);

  useEffect(() => {
    if (typeof window !== "undefined") {
      const storedLatLng = JSON.parse(window.localStorage.getItem("currentLatLng"));
      setCurrentLatLng(storedLatLng);
    }
  }, []);

  const { data: zoneData } = useQuery(
    ["zoneId", currentLatLng],
    async () => GoogleApi.getZoneId(currentLatLng),
    {
      retry: 1,
      enabled: !!currentLatLng,
    }
  );
  const { mutate: paymentMethodUpdateMutation, isLoading: repayOrderLoading } =
    useUpdatePaymentMethod();
  const { mutate: walletPaymentMutation } = useUpdatePaymentByWallet()
  const {
    data: offlinePaymentOptions,
    refetch: refetchOfflinePaymentOptions,
    isLoading: offlineIsLoading,
  } = useGetOfflinePaymentOptions();
  const isZoneDigital = getDigitalMethodFromZone(
    failPayment?.zone_id,
    zoneData?.data
  );
  console.log({ failPayment });
  useEffect(() => {
    refetchFailedPayment();
    refetchOfflinePaymentOptions()
  }, []);
  console.log({ openIncompleteOrder });
  const zoneid =
    typeof window !== "undefined" ? localStorage.getItem("zoneid") : undefined;

  useEffect(() => {
    window.scrollTo(0, 0);
  }, [router.query.search]);

  const onSuccessHandler = (response) => {
    setWishListsData(response);
    dispatch(setWishList(response));
  };
  const { refetch } = useWishListGet(onSuccessHandler);
  const { refetch: rentalWishlistRefetch } = useGetWishList(onSuccessHandler);

  useEffect(() => {
    if (token) {
      if (moduleType === "rental") {
        rentalWishlistRefetch();
      } else {
        refetch();
      }
    }
  }, [token]);

  const { refetch: lastReviewRefetch, data } = useGetLastOrderWithoutReview(
    (res) => {
      if (res?.order_id) {
        setOrderId(res.order_id);
        setOpen(true);
      }
    }
  );

  useEffect(() => {
    if (token) lastReviewRefetch();
  }, [token]);

  const { refetch: cancelReviewRefetch } = useReviewReminderCancel(
    () => setOpen(false),
    orderId
  );

  useEffect(() => {
    if (!router.query.data_type) {
      dispatch(setStoreSelectedItems([]));
      dispatch(setStoreSelectedItems2([]));
      dispatch(setFilterData([]));
    }
  }, [router.query.data_type]);

  const getModuleWiseComponents = () => {
    switch (getCurrentModuleType()) {
      case ModuleTypes.GROCERY:
        return <Grocery configData={configData} />;
      case ModuleTypes.PHARMACY:
        return <Pharmacy configData={configData} />;
      case ModuleTypes.ECOMMERCE:
        return <Shop configData={configData} />;
      case ModuleTypes.FOOD:
        return <FoodModule configData={configData} />;
      case ModuleTypes.PARCEL:
        return <Parcel configData={configData} />;
      case ModuleTypes.RENTAL:
        return (
          <Rental configData={configData} landingPageData={landingPageData} />
        );
      default:
        return null;
    }
  };

  const handleClose = () => {
    if (orderId) {
      cancelReviewRefetch();
    }
  };

  const handleRateButtonClick = () => {
    router.push(
      {
        pathname: "/profile",
        query: { orderId, page: "my-orders" },
      },
      undefined,
      { shallow: true }
    );
  };
  const handleCloseWelcomeModal = () => {
    dispatch(setWelcomeModal(false));
  };
  const handlePayment = (mutation) => {
    const handleSuccess = (response) => {
      toast.success(response.message);
    };

    const formData = {
      order_id: failPayment?.order_id,
      _method: "put",
    };

    mutation(formData, {
      onSuccess: handleSuccess,
      onError: onErrorResponse,
    });
  };
  const failedOrderPlace = () => {
    handleFailedOrderPlace({
      paymentMethod,
      failPayment,
      handlePayment,
      paymentMethodUpdateMutation,
      walletPaymentMutation,
      profileInfo,
      orderId: failPayment?.order_id,
      baseUrl,
      router
    });
  }

  return (
    <PushNotificationLayout>
      <NoSsr>
        <CustomStackFullWidth>
          <CustomStackFullWidth sx={{ position: "relative" }}>
            <TopBanner />
            <CustomStackFullWidth
              alignItems="center"
              justifyContent="center"
              sx={{
                position: "absolute",
                top: { xs: -4, sm: 50 },
                left: 0,
                right: 0,
              }}
            >
              <SearchWithTitle
                currentTab={0}
                zoneid={zoneid}
                token={token}
                searchQuery={
                  router.query?.data_type === "searched"
                    ? router.query.search
                    : ""
                }
                name={router.query.name}
                query={router.query}
              />
            </CustomStackFullWidth>
          </CustomStackFullWidth>
          {moduleType === "rental" && (
            <Box>
              <TaxiSearchPanel position="relative" />
            </Box>
          )}
          <Box width="100%">{getModuleWiseComponents()}</Box>
        </CustomStackFullWidth>

        {open && (
          <CustomModal openModal={open} handleClose={handleClose}>
            <LastOrderReview
              handleClose={handleClose}
              handleRateButtonClick={handleRateButtonClick}
              productImage={data?.images}
            />
          </CustomModal>
        )}
        <CustomModal
          handleClose={handleCloseWelcomeModal}
          openModal={welcomeModal}
          closeButton
        >
          <Box
            sx={{
              maxWidth: "382px",
              width: "95vw",
              px: 1.3,
              pb: 4,
              textAlign: "center",
              img: {
                height: "unset",
              },
            }}
          >
            <img
              src={"/static/sign-up-welcome.svg"}
              alt="welcome"
              width={183}
              height={183}
            />
            <Box maxWidth={"308px"} mx={"auto"} mt={2}>
              <Typography variant="h6" color="primary" mb={2}>
                {t(`Welcome to ! ${configData?.business_name}`)}
              </Typography>
              <Typography variant="body2" lineHeight={"1.5"}>
                {profileInfo?.is_valid_for_discount
                  ? t(
                    `Get ready for a special welcome gift, enjoy a special discount on your first order within`
                  ) +
                  " " +
                  profileInfo?.validity +
                  "."
                  : " "}
                {"  "}
                {t(`Start exploring the best services around you.`)}
              </Typography>
            </Box>
          </Box>
        </CustomModal>
        {token && getCurrentModuleType() !== "parcel" && <CashBackPopup />}
        {token && failPayment && !(Array.isArray(failPayment) && failPayment.length === 0) && (
          <CustomModal
            handleClose={() => {
              setOpenIncompleteOrder(false);
              // localStorage.setItem("incompleteOrderModalClosedAt", Date.now().toString());
            }}
            openModal={openIncompleteOrder}
            closeButton
          >
            <IncompleteOrderModal
              dontShowAgain={dontShowAgain}
              setDontShowAgain={setDontShowAgain}
              setOpenPaymentModal={setOpenPaymentModal} setOpenIncompleteOrder={setOpenIncompleteOrder} failPaymentOrderData={failPayment} />
          </CustomModal>
        )}
        <CustomModal
          openModal={openPaymentModal}
          handleClose={() => setOpenPaymentModal(false)}
        >
          <PaymentMethod
            setPaymentMethod={setPaymentMethod}
            paymentMethod={paymentMethod}
            zoneData={zoneData}
            configData={configData}
            orderType={failPayment?.order_type}
            usePartialPayment={false}
            setOpenModel={setOpenPaymentModal}
            forprescription={failPayment?.prescription_order}
            offlinePaymentOptions={offlinePaymentOptions}
            paymentMethodImage={null}
            setPaymentMethodImage={null}
            setSwitchToWallet={null}
            isZoneDigital={isZoneDigital}
            handlePartialPayment={() => setPaymentMethod("wallet")}
            walletBalance={profileInfo?.wallet_balance}
            removePartialPayment={null}
            switchToWallet={null}
            customerData={{ data: profileInfo }}
            failed
            payableAmount={failPayment?.order_amount}
            failedOrderPlace={failedOrderPlace}

          />
        </CustomModal>
      </NoSsr>
    </PushNotificationLayout>
  );
};

export default React.memo(HomePageComponents);
