"use client";
import React, { useRef, useState, useEffect } from "react";
import Image from "next/image";
import Link from "next/link";
import { AWS_CDN_URL } from "@/utils/staticValues";

import { Swiper, SwiperSlide } from "swiper/react";
import "swiper/css/navigation";
import "swiper/css";
import { Navigation } from "swiper/modules";
import SwiperCore from "swiper";

interface FabricFamily {
  id: number;
  name: string;
  image: string;
  icon:string;
  alt_text?: string;
  slug: string;
}

export default function FabricTopNav() {
  const [fabricFamilyList, setFabricFamilyList] = useState<FabricFamily[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  
  useEffect(
    () => {
      async function getFabricFamilies() {
        try {
          setIsLoading(true);
          // Use cached API route instead of direct external API call
          const response = await fetch('/api/fabrics/families', {
            method: "GET",
            headers: {
              "Content-Type": "application/json",
            },
            cache: 'force-cache',
            next: { revalidate: 900 }, // 15 minutes
          });

          if (!response.ok) {
            throw new Error(
              `Error: ${response.status} - ${response.statusText}`,
            );
          }

          const result = await response.json();
          setFabricFamilyList(result.data?.fabric || []);
        } catch (error) {
          console.error("Error fetching fabric families:", error);
        } finally {
          setIsLoading(false);
        }
      }

      getFabricFamilies();
    },
    [],
  );

  const swiperRef = useRef<SwiperCore | null>(null);
  const [isBeginning, setIsBeginning] = useState(true);
  const [isEnd, setIsEnd] = useState(false);

  const handleSwiperInit = (swiper: SwiperCore) => {
    swiperRef.current = swiper;
    setIsBeginning(swiper.isBeginning);
    setIsEnd(swiper.isEnd);
  };

  const handleSlideChange = () => {
    if (!swiperRef.current) return;
    setIsBeginning(swiperRef.current.isBeginning);
    setIsEnd(swiperRef.current.isEnd);
  };

  const baseStyle =
    "absolute h-[60%] flex items-center justify-center top-[60%] z-10 -translate-y-1/2 bg-gray-100 p-2 text-black transition";

  return (
    <div className="relative bg-gray-100 pt-12 z-10">
      <div className="wrapper">
        <div className="mx-auto flex w-full flex-col items-center justify-center">
          <Swiper
            slidesPerView={3}
            spaceBetween={16}
            breakpoints={{
              640: {
                slidesPerView: 8,
                spaceBetween: 48,
              }
            }}
            pagination={{
              clickable: true,
            }}
            navigation={{
              nextEl: ".custom-next",
              prevEl: ".custom-prev",
            }}
            modules={[Navigation]}
            className="fabricCatNavItem"
            onSwiper={handleSwiperInit}
            onSlideChange={handleSlideChange}
          >
            {isLoading ? (
              <SwiperSlide className="flex items-center justify-center py-10">
                <div className="h-6 w-6 animate-spin rounded-full border-2 border-gray-300 border-t-gray-900"></div>
              </SwiperSlide>
            ) : fabricFamilyList.length > 0 ? (
              fabricFamilyList.map((item, index) => (
              <SwiperSlide key={`${item.id}_${index}`} className="w-36 h-38 pt-8 flex flex-col">
                <Link
                  href={`/fabric/${item.slug}`}
                  className="mx-auto flex flex-col w-full h-35 gap-1 transition-all duration-300 hover:scale-115"
                >
                  <div className="mx-auto flex w-20 h-auto flex-col items-center justify-center align-top">
                    <Image
                      src={`${AWS_CDN_URL}/${item.icon}`}
                      alt={item.alt_text || item.name}
                      width={256}
                      height={256}
                      className="img-responsive"
                    />
                  </div>
                  <div className="font-bogart md:text-md/4 items-center justify-center text-center align-top text-sm/4 capitalize">
                    {item.name}
                  </div>
                </Link>
              </SwiperSlide>
            ))
            ) : (
              <SwiperSlide className="flex items-center justify-center py-10">
                <p className="text-gray-500 text-sm">No fabrics available</p>
              </SwiperSlide>
            )}
          </Swiper>
          {/* Previous Button */}
          <button
            className={`custom-prev left-0 ${baseStyle} ${
              isBeginning ? "cursor-not-allowed opacity-25" : "opacity-100"
            }`}
            disabled={isBeginning}
          >
            <i
              className="icon-[solar--arrow-left-broken]"
              style={{ width: 24, height: 24 }}
            />
          </button>

          {/* Next Button */}
          <button
            className={`custom-next right-0 ${baseStyle} ${
              isEnd ? "cursor-not-allowed opacity-25" : "opacity-100"
            }`}
            disabled={isEnd}
          >
            <i
              className="icon-[solar--arrow-right-broken]"
              style={{ width: 24, height: 24 }}
            />
          </button>
        </div>
      </div>
    </div>
  );
}
