"use client";

import { useState, useRef, useEffect } from "react";

import { Swiper, SwiperSlide } from "swiper/react";
import { Pagination, Autoplay, Navigation } from "swiper/modules";

import "swiper/css";
import "swiper/css/pagination";
import AppHeader from "@/components/app-layout/AppHeader";
import BannerSlider from "@/components/frontend-pages/home/BannerSlider";
import Categories from "@/components/frontend-pages/home/Categories";
import SkeletonLoader from "@/components/frontend-pages/home/SkeletonLoader";

import dynamic from "next/dynamic";
const MiddleBanner = dynamic(
  () => import("@/components/frontend-pages/home/MiddleBanner"),
  {
    loading: () => <SkeletonLoader type="banner" />,
  },
);
const ShopTheOccasion = dynamic(
  () => import("@/components/frontend-pages/home/ShopTheOccasion"),
  {
    loading: () => <SkeletonLoader />,
  },
);
const ProductRow = dynamic(
  () => import("@/components/frontend-pages/home/ProductRow"),
  {
    loading: () => <SkeletonLoader />,
  },
);
const VideoSection = dynamic(
  () => import("@/components/frontend-pages/home/VideoSection"),
  {
    loading: () => <SkeletonLoader type="banner" />,
  },
);
const Reviews = dynamic(
  () => import("@/components/frontend-pages/home/Reviews"),
  {
    loading: () => <SkeletonLoader />,
  },
);
const SmallBanners = dynamic(
  () => import("@/components/frontend-pages/home/SmallBanners"),
  {
    loading: () => <SkeletonLoader />,
  },
);
const Blogs = dynamic(() => import("@/components/frontend-pages/home/Blogs"), {
  loading: () => <SkeletonLoader />,
});
const Newsletter = dynamic(
  () => import("@/components/frontend-pages/home/Newsletter"),
  {
    loading: () => <SkeletonLoader type="banner" />,
  },
);
const AppFooter = dynamic(() => import("@/components/app-layout/AppFooter"), {
  loading: () => <SkeletonLoader type="banner" />,
});

import { apiCall } from "@/utils/callApi";
import LeadGate from "@/components/frontend-pages/home/LeadGate";
import AppLoader from "@/components/ui-elements/AppLoader";

export default function HomePage() {
  const [categories, setCategories] = useState<any[]>([]);
  const [products, setProducts] = useState<any[]>([]);
  const [newProducts, setNewProducts] = useState<any[]>([]);
  const [receptionProducts, setReceptionProducts] = useState<any[]>([]);
  const [reviews, setReviews] = useState<any[]>([]);
  const [blogs, setBlogs] = useState<any[]>([]);
  const [banners, setBanners] = useState<any[]>([]);
  const [topBanner, setTopBanner] = useState<any>([]);
  const [middleBanner, setMiddleBanner] = useState<any>([]);
  const [smallBanners, setSmallBanners] = useState<any[]>([]);
  const [videoData, setVideoData] = useState(null);
  const [slider, setSlider] = useState<any[]>([]);
  const [events, setEvents] = useState<any[]>([]);
  const [settings, setSettings] = useState<any>({});
  const [dataLoading, setDataLoading] = useState<boolean>(true);

  const videoRef = useRef(null);

  useEffect(() => {
    const init = async () => {
      setDataLoading(true);
      try {
        const response = await apiCall<any>("/clientapi/home");
        if (response.status == 200) {
          const data = response.data;
          const {
            Blogs: blogs,
            banners,
            categories,
            events,
            products,
            newProducts,
            receptionproducts,
            reviews,
            slider,
            staticVideo: video,
          } = data || {};

          setBlogs(blogs);
          setBanners(banners);
          setCategories(categories);
          setEvents(events);
          setProducts(products);
          setNewProducts(newProducts);
          setReceptionProducts(receptionproducts);
          setReviews(reviews);
          setSlider(slider);
          videoRef.current = video;
          setVideoData(video);
        }

        const raw_settings = localStorage.getItem("general-settings");
        if (!raw_settings) {
          const settingsRes: any = await apiCall<any>("/api/general-settings");
          if (settingsRes.status == 200) {
            setSettings(settingsRes.data?.data);
          }
        } else {
          setSettings(JSON.parse(raw_settings));
        }
      } catch (error: any) {
        console.error("Error fetching", error);
      } finally {
        setDataLoading(false);
      }
    };

    init();
  }, []);

  useEffect(() => {
    if (!banners) return;
    const topBanner = banners?.find((bn: any) => bn.banner_title === "hometop");
    setTopBanner(topBanner);

    const midBanner = banners?.find(
      (bn: any) => bn.banner_title === "homebottom",
    );
    // console.log('^^^^^^^', topBanner, midBanner)
    setMiddleBanner(midBanner);

    const smallBanners = banners?.filter(
      (bn: any) => bn.banner_title === "homesmall",
    );
    setSmallBanners(smallBanners || []);
  }, [banners]);

  return (
    <div className="font-montserrat">
      <AppHeader />
      <main>
        <AppLoader loading={dataLoading} />
        <LeadGate />
        {dataLoading ? (
          <SkeletonLoader type="banner" bannerHeight="500px" />
        ) : (
          <BannerSlider sliders={slider} />
        )}
        {dataLoading ? (
          <SkeletonLoader />
        ) : (
          <Categories categories={categories} />
        )}
        {dataLoading ? (
          <SkeletonLoader type="banner" />
        ) : (
          <MiddleBanner
            src={topBanner?.banner_image}
            // heading={<>Curabitur <span className="text-amber-300">Vulputate</span> Nullam Quis Condimentum</>}
            heading={topBanner?.banner_description}
            buttonHref="/products"            
          />
        )}
        {dataLoading ? (
          <SkeletonLoader />
        ) : (
          <ShopTheOccasion occasions={events} />
        )}
        {dataLoading ? (
          <SkeletonLoader />
        ) : (
          <ProductRow title="New Arrivals" products={newProducts} />
        )}
        {dataLoading ? (
          <SkeletonLoader type="banner" />
        ) : (
          <MiddleBanner
            src={middleBanner?.banner_image}
            // heading={<><span className="text-amber-300">Embrace Royalty</span> — Modern Maharaja</>}
            // subheading="Unleash Your Inner Royalty"
            heading={middleBanner?.banner_description}
            align="right"
            buttonHref="/products"
          />
        )}
        {dataLoading ? (
          <SkeletonLoader />
        ) : (
          <ProductRow
            title="Reception Collections"
            products={receptionProducts}
          />
        )}
        {dataLoading ? (
          <SkeletonLoader type="banner" />
        ) : (
          <VideoSection videoData={videoData} />
        )}
        {dataLoading ? <SkeletonLoader /> : <Reviews reviews={reviews} />}
        {dataLoading ? (
          <SkeletonLoader />
        ) : (
          <SmallBanners banners={smallBanners} />
        )}
        {dataLoading ? <SkeletonLoader /> : <Blogs blogs={blogs} />}
        {dataLoading ? (
          <SkeletonLoader type="banner" />
        ) : (
          <Newsletter settings={settings} />
        )}
      </main>
      <AppFooter />
    </div>
  );
}
