/* eslint-disable @typescript-eslint/no-explicit-any */
"use client";

import { useState, useEffect } from "react";
import { useSearchParams } from "next/navigation";
import Link from "next/link";
import { Trophy, ArrowRight } from "lucide-react";
import type { Product } from "@/types/product/product";
import { Pagination } from "@/components/ui/pagination";
import ProductCard from "./ProductCard";
import ScrollToFeatured from "./ScrollToFeatured";
import { getFeaturedProductsAction } from "@/actions/products/products.action";
import ProductsSkeleton from "@/components/skeletons/ProductsSkeleton";

interface FeaturedGridProps {
  featuredData: any;
  currentPage: number;
  totalPages: number;
  filterParams?: { page?: string; search?: string; category?: string; sort?: string; blogPage?: string };
}

function buildFeaturedPageUrl(
  page: number,
  filterParams?: FeaturedGridProps["filterParams"]
): string {
  const params = new URLSearchParams();
  params.set("featuredPage", String(page));
  if (filterParams?.page) params.set("page", filterParams.page);
  if (filterParams?.search) params.set("search", filterParams.search);
  if (filterParams?.category) params.set("category", filterParams.category);
  if (filterParams?.sort) params.set("sort", filterParams.sort);
  if (filterParams?.blogPage) params.set("blogPage", filterParams.blogPage);
  return `/?${params.toString()}#featured-products`;
}

export default function FeaturedGrid({
  featuredData: initialFeaturedData,
  currentPage: initialCurrentPage,
  totalPages: initialTotalPages,
  filterParams,
}: FeaturedGridProps) {
  const searchParams = useSearchParams();

  // Extract search params
  const featuredPage = searchParams.get("featuredPage");
  const pPage = searchParams.get("page");
  const pSearch = searchParams.get("search");
  const pCategory = searchParams.get("category");
  const pSort = searchParams.get("sort");
  const pBlogPage = searchParams.get("blogPage");

  const [products, setProducts] = useState<Product[]>(initialFeaturedData?.data || []);
  const [currentPage, setCurrentPage] = useState<number>(initialCurrentPage);
  const [totalPages, setTotalPages] = useState<number>(initialTotalPages);
  const [isLoading, setIsLoading] = useState<boolean>(false);

  // Sync state with URL params on transition
  useEffect(() => {
    let active = true;

    async function loadFilteredFeaturedProducts() {
      setIsLoading(true);
      try {
        const res = await getFeaturedProductsAction(Number(featuredPage) || 1, 9);

        if (active && res.success && res.data) {
          setProducts(res.data.data || []);
          setCurrentPage(res.data.page || 1);
          setTotalPages(Math.ceil(res.data.total / res.data.limit));
        }
      } catch (error) {
        console.error("Failed to load featured products client-side:", error);
      } finally {
        if (active) setIsLoading(false);
      }
    }

    if (featuredPage) {
      loadFilteredFeaturedProducts();
    } else {
      setProducts(initialFeaturedData?.data || []);
      setCurrentPage(initialCurrentPage);
      setTotalPages(initialTotalPages);
    }

    return () => {
      active = false;
    };
  }, [featuredPage, initialFeaturedData, initialCurrentPage, initialTotalPages]);

  const activeFilterParams = {
    page: pPage || filterParams?.page || "",
    search: pSearch || filterParams?.search || "",
    category: pCategory || filterParams?.category || "",
    sort: pSort || filterParams?.sort || "",
    blogPage: pBlogPage || filterParams?.blogPage || "",
  };

  if (!products || products.length === 0) return null;

  return (
    <section id="featured-products" className="scroll-mt-24 py-20 bg-slate-50/50 text-slate-900 relative">
      <div className="container mx-auto px-6">
        {/* HEADER SECTION */}
        <ScrollToFeatured />
        <div className="mb-16 text-center max-w-6xl mx-auto px-6">
          <span className="text-xs uppercase tracking-widest font-black text-brand-accent mb-3 block">
            Editor&apos;s Choice
          </span>
          <h2 className="text-3xl md:text-5xl font-black text-zinc-900 uppercase tracking-tight mb-4">
            Featured Products
          </h2>
          <p className="text-zinc-650 text-sm md:text-base font-medium max-w-lg mx-auto">
            Handpicked electronics & appliances featured by our experts
          </p>
        </div>

        {/* Dynamic Card Area */}
        <div className={`transition-opacity duration-300 ${isLoading ? "opacity-80" : "opacity-100"}`}>
          {isLoading ? (
            <ProductsSkeleton gridOnly />
          ) : (
            <div className="grid gap-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 transition-all duration-300">
              {products.map((product) => (
                <ProductCard key={product.id} product={product} />
              ))}
              {products.length > 0 && (
                <Link
                  href="/products?featured=true"
                  className="group/card relative aspect-[4/5] overflow-hidden rounded-2xl border border-zinc-800 bg-zinc-950 p-6 md:p-8 flex flex-col justify-between text-white shadow-md transition-all duration-500 ease-out hover:-translate-y-1.5 hover:shadow-2xl hover:shadow-[0_20px_40px_-15px_rgba(0,0,0,0.5)]"
                >
                  <div className="flex flex-col h-full justify-between">
                    <div>
                      <div className="bg-amber-500/10 text-amber-500 w-12 h-12 rounded-full flex items-center justify-center mb-6 border border-amber-500/25">
                        <Trophy className="w-6 h-6" />
                      </div>
                      <span className="text-zinc-500 text-xs font-bold uppercase tracking-widest block mb-2">
                        991+ MORE
                      </span>
                      <h3 className="text-xl md:text-2xl font-black uppercase tracking-tight mb-3 text-white">
                        See every bestseller
                      </h3>
                      <p className="text-zinc-400 text-sm leading-relaxed">
                        Full collection, sorted, filtered, ready to shop.
                      </p>
                    </div>
                    <div className="text-brand-accent-light hover:underline flex items-center gap-2 mt-auto font-bold uppercase tracking-wider text-xs">
                      View all <ArrowRight className="w-4 h-4 transition-transform duration-300 group-hover/card:translate-x-1" />
                    </div>
                  </div>
                </Link>
              )}
            </div>
          )}
        </div>

        {/* Pagination Container */}
        <div className={`mt-12 transition-opacity duration-300 ${isLoading ? "opacity-50 pointer-events-none" : "opacity-100"}`}>
          <Pagination
            currentPage={currentPage}
            totalPages={totalPages}
            buildPageUrl={(page) => buildFeaturedPageUrl(page, activeFilterParams)}
          />
        </div>
      </div>
    </section>
  );
}
