"use client";
import { useEffect, useState, useMemo, useCallback } from "react";
import AdBanner from "@/components/AdBanner";
import CategorySlider from "@/components/CategorySlider";
import InfoStrip from "@/components/InfoStrip";
import ProductSection from "@/components/ProductSection";
import ServiceSection from "@/components/ServiceSection";
import HomeBannerSection from "@/components/HomeBannerSection";
import LazyLoadWrapper from "@/components/LazyLoadWrapper";
import Image from "next/image";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";

import {
  getAdvertisements,
  getAllProductCategories,
} from "@/lib/actions/productRecommendationsActions";

import {
  fetchRecentlyViewedProductsThunk,
  selectRecentlyViewedProductIds,
} from "@/app/store/slices/recentlyViewedSlice";

import { fetchRecentlyViewedProductsByIds } from "@/lib/actions/recentlyViewedProductActions";

import { useFormatDateTime } from "@/lib/utils/dateTimeUtils";
import { useAppSelector, useAppDispatch } from "@/app/store/hooks";
import { getStoredLocale } from "@/lib/getLocale";
import { checkAuthErrorGet } from "@/lib/checkAuthError";
import { getOtherAttributeImageUrl } from "@/hooks/useImageUrl";
import {
  AdvertisementsData,
  PlacementKey,
} from "../../../types/advertisements";
import FooterBanner from "@/components/FooterBanner";

export default function Home() {
  const { user } = useAppSelector((state) => state?.auth);
  const recentlyViewedProducts = useAppSelector(selectRecentlyViewedProductIds);

  const t = useTranslations();
  const locale = getStoredLocale();
  const dispatch = useAppDispatch();
  const router = useRouter();
  const { formatDateTime } = useFormatDateTime();

  const [sections, setSections] = useState<any[]>([]);
  const [recentlyViewedProductsData, setRecentlyViewedProductsData] = useState<
    any[]
  >([]);
  const [isLoading, setIsLoading] = useState(true);
  const [adsLoading, setAdsLoading] = useState<boolean>(false);

  const [advertisements, setAdvertisements] =
    useState<AdvertisementsData | null>(null);

  useEffect(() => {
    if (user?.token) {
      dispatch(
        fetchRecentlyViewedProductsThunk({
          token: user.token,
          limit: 20,
          locale,
        })
      );
    } else {
      const localIds = JSON.parse(
        localStorage.getItem("recentlyViewedProductIds") || "[]"
      );
      const limitedIds = localIds.slice(0, 20);
      if (limitedIds.length)
        dispatch(
          fetchRecentlyViewedProductsThunk({
            token: null,
            limit: 20,
            productIds: limitedIds,
            locale,
          })
        );
    }
  }, [dispatch, user?.token]);

  useEffect(() => {
    const fetchFullData = async () => {
      if (!recentlyViewedProducts.length) return;

      try {
        const response = await fetchRecentlyViewedProductsByIds(
          recentlyViewedProducts,
          user?.token || null,
          locale
        );

        if (response.status && response.data) {
          const serverProducts = response.data.data || [];
          const map = new Map(serverProducts.map((p: any) => [p.productId, p]));

          setRecentlyViewedProductsData(
            recentlyViewedProducts.map((id) => map.get(id)).filter(Boolean)
          );
        }
      } catch (e) {
        if (user?.token && checkAuthErrorGet(e, dispatch, router)) return;
      }
    };

    fetchFullData();
  }, [recentlyViewedProducts, user?.token, locale]);

  useEffect(() => {
    const load = async () => {
      try {
        setIsLoading(true);

        setAdsLoading(true);
        const [categoriesResult, adsResult] = await Promise.allSettled([
          getAllProductCategories(user?.token ?? "", locale),
          getAdvertisements(user?.token ?? ""),
        ]);

        let sections: any[] = [];
        let featuredSection: any = null;

        if (categoriesResult.status === "fulfilled") {
          const result = categoriesResult.value;

          sections = result.sections ?? [];
          featuredSection = result.featuredSection ?? null;
        } else {
          // console.error(
          //   "Failed to load product categories",
          //   categoriesResult.reason
          // );
        }

        if (adsResult.status === "fulfilled") {
          if (!adsResult.value.status) {
            // existing failure logic (if any)
          } else {
            setAdvertisements(adsResult.value.data);
          }
        } else {
          // console.error("Failed to load advertisements", adsResult.reason);
        }
        setAdsLoading(false);

        const processSections = (sections: any[]) => {
          return sections.map((section) => ({
            ...section,
            viewMoreUrl: "/filters/products",
            category: section.slug || "",
            items: (section.items || []).map((item: any) => ({
              ...item,
              id: item.id || "",
              title: item.title || t("home_page.untitled_product"),
              description: item.description || "",
              price: item.price || "0",
              time: item.time,
              location: item.location || t("home_page.location_not_specified"),
              imageUrl: item.imageUrl || "",
              slug: item.slug || "",
              distance: item.distance,
              createdAt: item.createdAt,
              creator: item.creator,
              isWishlisted: item.isWishlisted || false,
              totalNumberOfViews: item.totalNumberOfViews || 0,
            })),
          }));
        };

        const processedSections = processSections(sections);
        const processedFeatured = featuredSection
          ? processSections([featuredSection])[0]
          : null;
          
        const allSections = processedFeatured
          ? [processedFeatured, ...processedSections]
          : processedSections;

        setSections(allSections);
      } finally {
        setIsLoading(false);
      }
    };

    load();
  }, [locale]);

  const homeAdvertisements = useMemo(() => {
    return {
      mainBanner: advertisements?.placements?.["home.mainBanner"]?.ads ?? [],
      middleBanners: {
        large: advertisements?.placements["home.mediumPageLarge"]?.ads ?? [],
        bottom: advertisements?.placements["home.mediumPageBottom"]?.ads ?? [],
        top: advertisements?.placements["home.mediumPageTop"]?.ads ?? [],
      },
      footer: advertisements?.placements["home.footer"]?.ads ?? [],
    };
  }, [advertisements]);

  const transformedRecentlyViewed = useMemo(() => {
    return recentlyViewedProductsData.map((item) => ({
      id: item.productId,
      title: item.title || "",
      description: item.description || "",
      price: item.price || "0",
      time: item.createdAt,
      imageUrl: getOtherAttributeImageUrl(item),
      slug: item.productId,
      isWishlisted: item.isWishlisted || false,
      isOtherAttribute: item.otherAttribute ? true : false,
      location: item.location || t("home_page.location_not_specified"),
      otherAttribute: item.otherAttribute,
      productType: item?.otherAttribute ? item?.otherAttribute?.valueType : "product",
      distance: item.distance,
      totalNumberOfViews: item?.totalNumberOfViews
    }));
  }, [recentlyViewedProductsData]);

  return (
    <div className="dark:bg-background">
      {/* This component also use in single product page */}
      <div className="pt-5 pb-7.5 px-6 max-md:pb-4">
        <AdBanner ads={homeAdvertisements.mainBanner ?? null} />
      </div>
      <CategorySlider />

      <LazyLoadWrapper>
        <section className="pb-10 px-6 max-md:pb-6 max-lg:pb-7">
          <div className="max-w-w1660 mx-auto">
            <ServiceSection />
          </div>
        </section>
      </LazyLoadWrapper>

      <LazyLoadWrapper>
        <HomeBannerSection middleBanners={homeAdvertisements.middleBanners} />
      </LazyLoadWrapper>

      <LazyLoadWrapper>
        <section className="py-7.5 px-6 max-md:mb-5 max-md:py-6">
          <div className="max-w-w1660 mx-auto">
            <InfoStrip />
          </div>
        </section>
      </LazyLoadWrapper>

      {!isLoading &&
        sections.length > 0 &&
        sections.map((section) => (
          <LazyLoadWrapper key={section.slug}>
            <div className="px-6">
              <ProductSection
                title={section.title}
                viewMoreUrl={section.viewMoreUrl}
                items={section.items}
                category={section.slug}
              />
            </div>
          </LazyLoadWrapper>
        ))}

      {/* Frame Image (keep without lazy load) */}
      <section className="footer-banner-section">
        <FooterBanner ads={homeAdvertisements.footer ?? null} />
      </section>

      {recentlyViewedProductsData.length > 0 && (
        <LazyLoadWrapper>
          <div className="px-6">
            <ProductSection
              key="recently-viewed"
              title={t("home_page.recently_viewed")}
              viewMoreUrl="/recently-viewed"
              items={transformedRecentlyViewed}
              is_view_more={true}
            />
          </div>
        </LazyLoadWrapper>
      )}
    </div>
  );
}
