"use client";

import { useEffect, useState } from "react";
import api from "@/lib/api";
import ProductCard from "@/components/ProductCard";
import { ChevronRight } from "lucide-react";

interface Category {
  id: number;
  name: string;
  slug: string;
}

interface Product {
  id: number;
  name: string;
  slug: string;
  price: string;
  sale_price?: string | null;
  image?: string | null;
  stock_quantity?: number;
  stock_status?: string;
  is_featured?: boolean;
  category?: {
    id: number;
    name: string;
    slug: string;
  } | null;
}

export default function CategoryProductShowcase() {
  const [categories, setCategories] = useState<Category[]>([]);
  const [activeCategory, setActiveCategory] = useState("");
  const [products, setProducts] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchCategories();
  }, []);

  useEffect(() => {
    if (activeCategory) {
      fetchProducts(activeCategory);
    }
  }, [activeCategory]);

  const fetchCategories = async () => {
    try {
      const res = await api.get("/categories");

      const cats = res.data.data || [];

      setCategories(cats);

      if (cats.length > 0) {
        setActiveCategory(cats[0].slug);
      }
    } catch (error) {
      console.error(error);
    }
  };

  const fetchProducts = async (slug: string) => {
    try {
      setLoading(true);

      const res = await api.get(`/products?category=${slug}`);

      setProducts(res.data.data || []);
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  if (categories.length === 0) return null;

  return (
    <section className="py-14 bg-white overflow-hidden">
      <div className="max-w-7xl mx-auto px-4">

        {/* Header */}
        <div className="flex flex-col lg:flex-row lg:items-end lg:justify-between gap-6 mb-8">

          <div>
            <p className="text-green-600 text-sm font-bold uppercase tracking-widest mb-2">
              Discover Products
            </p>

            <h2 className="text-3xl lg:text-4xl font-black text-slate-900">
              Loved By Us, Picked For You
            </h2>
          </div>

        </div>

        {/* Category Tabs */}
        <div className="border-b border-slate-200 mb-8">
          <div className="flex gap-8 overflow-x-auto scrollbar-hide">

            {categories.map((category) => (
              <button
                key={category.id}
                onClick={() => setActiveCategory(category.slug)}
                className={`pb-4 text-sm lg:text-base font-semibold whitespace-nowrap transition-all
                  ${
                    activeCategory === category.slug
                      ? "border-b-2 border-green-600 text-green-600"
                      : "text-slate-500 hover:text-slate-900"
                  }
                `}
              >
                {category.name}
              </button>
            ))}

          </div>
        </div>

        {/* Products */}
        {loading ? (
          <div className="flex gap-4 overflow-hidden">
            {[...Array(4)].map((_, i) => (
              <div
                key={i}
                className="w-[260px] h-[350px] bg-slate-100 animate-pulse rounded-2xl flex-shrink-0"
              />
            ))}
          </div>
        ) : (
          <div className="flex gap-5 overflow-x-auto pb-4 scrollbar-hide">

            {products.slice(0, 10).map((product) => (
              <div
                key={product.id}
                className="w-[260px] flex-shrink-0"
              >
                <ProductCard product={product} />
              </div>
            ))}

          </div>
        )}

        {/* View Category */}
        <div className="mt-8 text-center">
          <a
            href={`/category/${activeCategory}`}
            className="inline-flex items-center gap-2 font-bold text-green-600 hover:text-green-700"
          >
            View More
            <ChevronRight size={18} />
          </a>
        </div>

      </div>
    </section>
  );
}