"use client";

import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import api from "@/lib/api";

import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/css";

import {
  Sparkles,
  ChevronLeft,
  ChevronRight,
} from "lucide-react";

import { Navigation } from "swiper/modules";

interface Category {
  id: number;
  parent_id?: number | string | null;
  name: string;
  slug?: string;
  image?: string | null;
  icon?: string | null;
  description?: string | null;
}

export default function CategoriesPage() {
  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchCategories();
  }, []);

  const fetchCategories = async () => {
    try {
      setLoading(true);

      const res = await api.get("/categories");

      setCategories(res.data.data || []);
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

  const parentCategories = useMemo(() => {
    return categories.filter(
      (item) =>
        item.parent_id === null ||
        item.parent_id === undefined ||
        item.parent_id === "" ||
        Number(item.parent_id) === 0
    );
  }, [categories]);

  const getImage = (
    image?: string | null,
    icon?: string | null
  ) =>
    image ||
    icon ||
    "https://via.placeholder.com/500x500?text=Category";

  return (
    <main className="min-h-screen bg-[#f8f4ee] pb-20">

      {/* HERO */}

      <section className="relative overflow-hidden bg-gradient-to-br from-green-700 via-green-600 to-emerald-500">
        <div className="absolute -top-32 -right-32 h-96 w-96 rounded-full bg-white/10 blur-3xl" />

        <div className="absolute -bottom-32 -left-32 h-96 w-96 rounded-full bg-white/10 blur-3xl" />

        <div className="relative mx-auto max-w-7xl px-4 py-16 md:py-24">

          <div className="inline-flex items-center gap-2 rounded-full border border-white/20 bg-white/10 px-5 py-2 text-sm font-bold text-white backdrop-blur">
            <Sparkles size={16} />
            Shop By Department
          </div>

          <h1 className="mt-6 max-w-4xl text-4xl font-black text-white md:text-7xl">
            Explore All Categories
          </h1>

          <p className="mt-5 max-w-2xl text-base font-medium text-white/90 md:text-lg">
            Browse groceries, daily essentials,
            fresh produce, household products,
            snacks, beverages and much more.
          </p>
        </div>
      </section>

      <div className="mx-auto max-w-7xl px-4 py-10">

        {/* MAIN CATEGORIES */}

        <section className="mb-14">

          <div className="mb-8 flex items-center justify-between">
            <h2 className="text-2xl md:text-4xl font-black text-slate-900">
              Main Categories
            </h2>
          </div>

          {loading ? (
            <div className="grid grid-cols-2 gap-4 md:grid-cols-4 lg:grid-cols-6">
              {[...Array(12)].map((_, index) => (
                <div
                  key={index}
                  className="h-52 animate-pulse rounded-3xl bg-white"
                />
              ))}
            </div>
          ) : (
            <div className="grid grid-cols-2 gap-4 md:grid-cols-4 lg:grid-cols-6">
              {parentCategories.map((category) => (
                <Link
                  key={category.id}
                  href={`/categories/${category.slug}`}
                  className="group"
                >
                  <div className=" rounded-3xl border border-[#efe6d9] bg-white p-4 transition-all duration-300 hover:-translate-y-2 hover:shadow-2xl hover:border-green-200">

                    <img
                      src={getImage(
                        category.image,
                        category.icon
                      )}
                      alt={category.name}
                      className="mx-auto h-24 w-24 rounded-full object-cover transition-transform duration-500group-hover:scale-110 md:h-32 md:w-32" />

                    <h3 className="mt-4 text-center text-sm font-black text-slate-900 md:text-base">
                      {category.name}
                    </h3>

                  </div>
                </Link>
              ))}
            </div>
          )}
        </section>

        {/* POPULAR CATEGORIES */}

        {!loading && categories.length > 0 && (
          <section className="mb-14">

            <div className="mb-8 flex items-center justify-between">
              <h2 className="text-2xl md:text-4xl font-black text-slate-900">
                Browse More Categories
              </h2>

              <div className="flex gap-3">
                <button
                  className="
                  category-prev
                  flex h-11 w-11 items-center justify-center
                  rounded-full
                  bg-white
                  shadow-md
                  border
                  hover:bg-green-600
                  hover:text-white
                  transition
                "
                >
                  <ChevronLeft size={18} />
                </button>

                <button
                  className="
                  category-next
                  flex h-11 w-11 items-center justify-center
                  rounded-full
                  bg-white
                  shadow-md
                  border
                  hover:bg-green-600
                  hover:text-white
                  transition
                "
                >
                  <ChevronRight size={18} />
                </button>
              </div>
            </div>

            <Swiper
              modules={[Navigation]}
              navigation={{
                prevEl: ".category-prev",
                nextEl: ".category-next",
              }}
              slidesPerView={2.2}
              spaceBetween={20}
              breakpoints={{
                640: {
                  slidesPerView: 3,
                },
                768: {
                  slidesPerView: 4,
                },
                1024: {
                  slidesPerView: 6,
                },
                1280: {
                  slidesPerView: 8,
                },
              }}
            >
              {categories.map((category) => (
                <SwiperSlide key={category.id}>
                  <Link
                    href={`/categories/${category.slug}`}
                  >
                   <div className=" rounded-3xl border border-[#efe6d9] bg-white p-4 text-center transition-all duration-300 hover:-translate-y-2 hover:shadow-xl">

                      <img
                        src={getImage(
                          category.image,
                          category.icon
                        )}
                        alt={category.name}
                        className="mx-auto h-20 w-20 rounded-full object-cover transition-transform duration-500 hover:scale-110"/>

                      <h3 className="mt-3 line-clamp-2 text-xs font-bold text-slate-900 md:text-sm">
                        {category.name}
                      </h3>

                    </div>
                  </Link>
                </SwiperSlide>
              ))}
            </Swiper>

          </section>
        )}

        {/* FEATURED DEPARTMENTS */}

        {!loading && parentCategories.length > 0 && (
          <section>

            <div className="mb-8">
              <h2 className="text-2xl md:text-4xl font-black text-slate-900">
                Shop By Department
              </h2>
            </div>

            <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">

              {parentCategories.slice(0, 6).map((category) => (
                <Link
                  key={category.id}
                  href={`/categories/${category.slug}`}
                  className="group"
                >
                  <div className="relative overflow-hidden rounded-[32px] shadow-xl">

                    <img
                      src={getImage(
                        category.image,
                        category.icon
                      )}
                      alt={category.name}
                      className="h-[320px] w-full object-cover transition-all duration-700 group-hover:scale-110"
                    />

                    <div className="absolute inset-0 bg-black/35" />

                    <div className="absolute inset-0 flex items-end p-6">

                      <div>
                        <h3 className="text-2xl font-black text-white">
                          {category.name}
                        </h3>

                        <span className="mt-2 inline-block text-sm font-bold text-white/90">
                          Shop Now →
                        </span>
                      </div>

                    </div>
                  </div>
                </Link>
              ))}

            </div>

          </section>
        )}

      </div>
    </main>
  );
}