"use client";
import ImageLink from "@/components/widgets/imageLink";
import WrapperComponent from "@/components/widgets/WrapperComponent";
import { horizontalProductSlider } from "@/data/sliderSetting/SliderSetting";
import Loader from "@/layout/loader";
import { Href, ImagePath, resolveImageUrl } from "@/utils/constants";
import Link from "next/link";
import React, { useEffect, useContext } from "react";
import { Container } from "reactstrap";
import HomeProduct from "../../widgets/HomeProduct";
import HomeServices from "../../widgets/HomeService";
import HomeSlider from "../../widgets/HomeSlider";
import HomeTitle from "../../widgets/HomeTitle";
import { useTranslation } from "react-i18next";
import { ServicesData } from "@/data/pages/HomePageData";
import HomePageCategories from "@/components/home/HomePageCategories";
import { useGetHomepage } from "@/utils/api/home/home";
import ThemeOptionContext from "@/context/themeOptionsContext";
import StoryThumbnails from "@/components/stories/StoryThumbnails";

const DEFAULT_HIGHLIGHT_SECTIONS = [
  {
    id: "where-dreams-meet-couture",
    status: true,
    subtitle: "Summer Edit",
    title: "Where dreams meet couture",
    description: "Fresh silhouettes, new fabrics, and exclusive accessories to elevate your summer wardrobe.",
    button_text: "Shop Womens",
    image_url: "/assets/images/theme/fashion_one/banner1.webp",
    redirect_link: {
      link_type: "collection",
      link: "fashion",
    },
  },
  {
    id: "enchanting-styles",
    status: true,
    subtitle: "Limited Drop",
    title: "Enchanting styles for every woman",
    description: "Discover curated outfits that blend elegance with everyday comfort for every occasion.",
    button_text: "Browse Collection",
    image_url: "/assets/images/theme/fashion_one/banner2.webp",
    redirect_link: {
      link_type: "collection",
      link: "new-arrivals",
    },
  },
];

const getSectionLinkProps = (redirect = {}) => {
  const linkType = redirect?.link_type;
  const linkValue = redirect?.link;
  let href = redirect?.href || Href;
  let target;
  let rel;

  switch (linkType) {
    case "external_url":
      href = linkValue || Href;
      target = "_blank";
      rel = "noreferrer noopener";
      break;
    case "product":
      href = linkValue ? `/product/${linkValue}` : Href;
      break;
    case "collection":
    case "category":
      href = linkValue ? `/category/${linkValue}` : Href;
      break;
    case "page":
      href = linkValue ? `/${linkValue.replace(/^\/*/, "")}` : Href;
      break;
    default:
      href = linkValue || Href;
  }

  return { href, target, rel };
};

const resolveSectionImage = (section = {}) => {
  const candidates = [
    section?.image_url,
    section?.image?.original_url,
    section?.image?.asset_url,
    section?.image?.url,
    section?.image?.path,
  ];
  for (const value of candidates) {
    if (value) {
      const resolved = resolveImageUrl(value);
      if (resolved) return resolved;
    }
  }
  return `${ImagePath}/placeholder/two_column_banner.png`;
};

const Fashion1 = () => {
  const { t } = useTranslation();
  const { themeOption } = useContext(ThemeOptionContext);
  const homeBanners = (themeOption?.home_banner?.banners || []).filter((banner) => banner?.status);
  const homeBannerData = { banners: homeBanners };
  const highlightSectionsFromTheme = (themeOption?.home_highlight_sections?.sections || []).filter(
    (section) => section?.status
  );
const rawHighlightSections = themeOption?.home_highlight_sections?.sections;

const highlightSections = (Array.isArray(rawHighlightSections) ? rawHighlightSections : [])
  .filter((section) => section?.status);


  // Single combined API call instead of multiple separate calls
  const { data: homepageData, isLoading } = useGetHomepage();

  // Extract data from combined response
  const productsData = homepageData?.data?.latest_products;
  const bestSellerData = homepageData?.data?.best_seller_products;

  useEffect(() => {
    document.body.classList.add("home");
    return () => {
      document.body.classList.remove("home");
    };
  }, []);

  if (isLoading) return <Loader />;

  return (
    <>
      {/* Home Banner */}
      <WrapperComponent
        classes={{
          sectionClass: "p-0 overflow-hidden position-relative",
          fluidClass: "slide-1 home-slider cuple-home-banner",
        }}
      >
        <HomeSlider bannerData={homeBannerData} height={650} width={1920} />
      </WrapperComponent>

      {/* Highlight sections under hero slider */}
      {highlightSections.length > 0 && (
        <WrapperComponent
          classes={{
            sectionClass: "pt-3 pb-0",
            fluidClass: "container",
          }}
        >
          <div className="row g-3 g-lg-4">
            {highlightSections.map((section, index) => {
              const sectionImage = resolveSectionImage(section);
              const linkProps = getSectionLinkProps(section?.redirect_link);
              const cardKey = section?.id || section?.title || index;

              return (
                <div className="col-lg-6" key={cardKey}>
                  <Link
                    {...linkProps}
                    className="home-highlight-card-link h-100 d-block"
                  >
                    <div className="home-highlight-card">
                      <div
                        className="home-highlight-card__media"
                        style={{ backgroundImage: `url(${sectionImage})` }}
                      />
                      <div className="home-highlight-card__content">
                        {section?.subtitle && (
                          <p className="home-highlight-card__subtitle">
                            {section.subtitle}
                          </p>
                        )}
                        <h3 className="home-highlight-card__title">{section?.title}</h3>
                        <p className="home-highlight-card__description">
                          {section?.description}
                        </p>
                        {section?.button_text && (
                          <span className="home-highlight-card__button">
                            {section.button_text}
                            <i className="ri-arrow-right-s-line"></i>
                          </span>
                        )}
                      </div>
                    </div>
                  </Link>
                </div>
              );
            })}
          </div>
        </WrapperComponent>
      )}

      {/* Stories - Instagram/Facebook style, lazy loaded */}
      <WrapperComponent
        classes={{
          sectionClass: "stories-section py-2",
          fluidClass: "container",
        }}
      >
        <StoryThumbnails />
      </WrapperComponent>

      {/* categories Banners */}
      <WrapperComponent
        classes={{
          sectionClass: "pb-0 ratio2_1 banner-section category-grid",
          fluidClass: "container",
        }}
      >
        {!themeOption?.home_categories?.headline?.trim() && (
          <div className="text-center homepage-categories-headline">
            <h3 className="fw-bold mb-1">{t("Explore Our Categories")}</h3>
            <p className="text-muted m-0">{t("Discover Your Styles")}</p>
          </div>
        )}


        <HomePageCategories />
      </WrapperComponent>

      {/* Products Slider */}
      {productsData && productsData.length > 0 && (
        <>
          <HomeTitle
            title={{
              title: "Latest Products",
              description:
                "Looking for the latest trends in clothing, shoes and accessories? Welcome to our 'Latest Drops' edit, bringing you all the latest styles from all your fave brands.",
              status: true,
              tag: "special offer",
              product_ids: productsData?.map((product) => product.id) || [],
            }}
            type="basic"
          />
          <WrapperComponent
            classes={{
              sectionClass: "section-b-space pt-0 best-seller-section",
              fluidClass: "container",
            }}
          >
            <div className="product-4 no-arrow">
              <HomeProduct
                slider={true}
                style="vertical"
                productIds={productsData?.map((product) => product.id) || []}
                sliderOptions={horizontalProductSlider}
                data={productsData}
              />
            </div>
          </WrapperComponent>
        </>
      )}

      {/* Full Banner */}
      <WrapperComponent
        classes={{ sectionClass: "banner-sale cuple-store-banner overflow-hidden section-b-space" }}
        noRowCol={true}
      >
        <ImageLink
          imgUrl={"/assets/images/theme/fashion_one/cuple store banner.webp"}
          placeholder={`${ImagePath}/cuple store banner.webp`}
          height={587}
          width={1905}
        />
      </WrapperComponent>

      {/* Best Seller Products */}
      {bestSellerData && bestSellerData.length > 0 && (
        <>
          <HomeTitle
            title={{
              title: t("Best Seller"),
              description: t("Our most popular products based on customer orders"),
              status: true,
              tag: t("Top Selling"),
              product_ids: bestSellerData?.map((product) => product.id) || [],
            }}
            type="basic"
          />
          <WrapperComponent
            classes={{
              sectionClass: "section-b-space pt-10",
              fluidClass: "container",
            }}
          >
            <div className="product-4 no-arrow">
              <HomeProduct
                slider={true}
                style="vertical"
                productIds={bestSellerData?.map((product) => product.id) || []}
                sliderOptions={horizontalProductSlider}
                data={bestSellerData}
              />
            </div>
          </WrapperComponent>
        </>
      )}

      {/* Services */}
      {ServicesData?.services && (
        <Container>
          <WrapperComponent
            classes={{ sectionClass: "service border-section small-section" }}
            noRowCol={true}
          >
            <HomeServices services={ServicesData?.services?.banners || []} />
          </WrapperComponent>
        </Container>
      )}
    </>
  );
};

export default Fashion1;
