"use client";

import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import api from "@/lib/api";
import Link from "next/link";
import ProductCard from "@/components/ProductCard";
import { Swiper, SwiperSlide } from "swiper/react";
import { Autoplay } from "swiper/modules";

import "swiper/css";

interface Category {
  id: number;
  name: string;
  slug: string;
  image?: string;
  parent_id?: number | null;
}

export default function CategoryPage() {
  const params = useParams();
  const slug = params?.slug as string;

  const [category, setCategory] = useState<any>(null);
  const [subcategories, setSubcategories] = useState<Category[]>([]);
  const [childCategories, setChildCategories] = useState<Category[]>([]);
  const [products, setProducts] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!slug) return;
    fetchData();
  }, [slug]);

  const fetchData = async () => {
    try {
      setLoading(true);

      const res = await api.get("/categories");
      const all = res.data.data;

      const current = all.find((c: Category) => c.slug === slug);

      if (!current) return;

      setCategory(current);

      const subs = all.filter(
        (c: Category) => Number(c.parent_id) === Number(current.id)
      );

      setSubcategories(subs);

      let child: Category[] = [];

      subs.forEach((sub: Category) => {
        const children = all.filter(
          (c: Category) => Number(c.parent_id) === Number(sub.id)
        );

        child = [...child, ...children];
      });

      setChildCategories(child);

      const productRes = await api.get(`/products?category=${slug}`);

      setProducts(productRes.data.data || []);
    } catch (err) {
      console.log(err);
    } finally {
      setLoading(false);
    }
  };

  if (loading) return <div className="p-10">Loading...</div>;

  if (!category) return <div className="p-10">Category not found</div>;

  return (
    <main className="bg-[#f5f6fa]">

      {/* HERO */}
        <section className="relative py-4 md:py-0">
          <Swiper
            modules={[Autoplay]}
            autoplay={{
              delay: 3500,
              disableOnInteraction: false,
            }}
            loop
            centeredSlides={true}
            spaceBetween={15}
            slidesPerView={1.15}
            breakpoints={{
              768: {
                slidesPerView: 1,
                spaceBetween: 0,
              },
            }}
          >
            {[category, ...subcategories, ...childCategories]
              .filter((i) => i?.image)
              .slice(0, 6)
              .map((item, i) => (
                <SwiperSlide key={i}>
                  <div
                    className="
                      relative
                      h-[280px]
                      md:h-[420px]
                      overflow-hidden
                      rounded-3xl
                      md:rounded-none
                      shadow-lg
                      md:shadow-none
                    "
                  >
                    <img
                      src={item.image}
                      alt={item.name}
                      className="w-full h-full object-cover"
                    />

                    <div className="absolute inset-0 bg-gradient-to-r from-black/60 via-black/20 to-transparent flex items-center">
                      <div className="px-6 md:max-w-7xl md:mx-auto">
                        <h1 className="text-white text-3xl md:text-6xl font-black">
                          {item.name}
                        </h1>

                        <p className="text-white/80 mt-3 text-sm md:text-base">
                          Discover latest styles in {category.name}
                        </p>
                      </div>
                    </div>
                  </div>
                </SwiperSlide>
              ))}
          </Swiper>
        </section>

      {/* SHOP BY CATEGORY */}
      {subcategories.length > 0 && (
        <section className="bg-white py-12">
          <div className="max-w-7xl mx-auto px-6">

            <h2 className="text-2xl font-black mb-6">
              Shop by Category
            </h2>

            <Swiper
              modules={[Autoplay]}
              spaceBetween={20}
              slidesPerView={2.2}
              loop={subcategories.length > 6}
              grabCursor={true}
              autoplay={{
                delay: 0,
                disableOnInteraction: false,
                reverseDirection: false,
              }}
              speed={6000}
              breakpoints={{
                640: { slidesPerView: 3 },
                768: { slidesPerView: 4 },
                1024: { slidesPerView: 6 },
              }}
            >
              {subcategories.map((sub) => (
                <SwiperSlide key={sub.id}>
                  <Link href={`/categories/${sub.slug}`} prefetch={false}>
                    <div className="bg-white border rounded-2xl overflow-hidden hover:shadow-xl transition-all">

                      <div className="aspect-square overflow-hidden">
                        <img
                          src={sub.image}
                          alt={sub.name}
                          className="w-full h-full object-cover hover:scale-105 transition duration-500"
                        />
                      </div>

                      <div className="p-3 text-center">
                        <p className="font-semibold text-sm">
                          {sub.name}
                        </p>
                      </div>

                    </div>
                  </Link>
                </SwiperSlide>
              ))}
            </Swiper>

          </div>
        </section>
        )}

      {/* MORE TO EXPLORE */}
      {childCategories.length > 0 && (
        <section className="bg-[#f5f6fa] py-12">
          <div className="max-w-7xl mx-auto px-6">

            <h2 className="text-2xl font-black mb-6">
              More To Explore
            </h2>

            <Swiper
              modules={[Autoplay]}
              spaceBetween={20}
              slidesPerView={2.2}
              loop={childCategories.length > 6}
              grabCursor={true}
              autoplay={{
                delay: 0,
                disableOnInteraction: false,
                reverseDirection: true,
              }}
              speed={7000}
              breakpoints={{
                640: { slidesPerView: 3 },
                768: { slidesPerView: 4 },
                1024: { slidesPerView: 6 },
              }}
            >
              {childCategories.map((item) => (
                <SwiperSlide key={item.id}>
                  <Link href={`/categories/${item.slug}`} prefetch={false}>
                    <div className="bg-white rounded-2xl overflow-hidden hover:shadow-xl transition-all">

                      <div className="aspect-square overflow-hidden">
                        <img
                          src={item.image}
                          alt={item.name}
                          className="w-full h-full object-cover hover:scale-105 transition duration-500"
                        />
                      </div>

                      <div className="p-3 text-center">
                        <p className="font-semibold text-sm">
                          {item.name}
                        </p>
                      </div>

                    </div>
                  </Link>
                </SwiperSlide>
              ))}
            </Swiper>

          </div>
        </section>
        )}

      {/* PRODUCTS */}
      <section className="bg-white py-14">
        <div className="max-w-7xl mx-auto px-6">

          <div className="flex justify-between items-center mb-8">
            <h2 className="text-3xl font-black">
              Products
            </h2>

            <span className="text-sm text-gray-500">
              {products.length} items
            </span>
          </div>

          {products.length === 0 ? (
            <div className="text-center py-20 text-gray-500">
              No products available yet
            </div>
          ) : (
            <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
              {products.map((product) => (
                <ProductCard
                  key={product.id}
                  product={product}
                />
              ))}
            </div>
          )}

        </div>
      </section>

    </main>
  );
}