"use client";
import React, { useRef, useEffect, useCallback, useState } from "react";
import Image from "next/image";
import Link from "next/link";
import { BtnLink } from "../button";
import { Swiper, SwiperSlide } from "swiper/react";
import { Autoplay, FreeMode } from "swiper/modules";
import "swiper/css";
import type { Swiper as SwiperType } from "swiper";
import { AWS_CDN_URL } from "@/utils/staticValues";

type Story = {
  id: number;
  slug: string;
  title: string;
  subtitle: string;
  thumbnail: string;
  pieceThumbnail: string;
  designHouse: string;
  isFeatured: number;
  display_order: number;
};

type StoriesResponse = {
  success: boolean;
  data: Story[];
};

const MAX_STORIES = 10;

const sliderBreakpoints = {
  320: { slidesPerView: 2, spaceBetween: 16 },
  680: { slidesPerView: 3, spaceBetween: 16 },
  1024: { slidesPerView: 4, spaceBetween: 32 },
};

export default function HomeStoriesSwiper() {
  const swiperRef = useRef<SwiperType | null>(null);
  const [stories, setStories] = useState<Story[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const handleMouseEnter = useCallback(() => {
    swiperRef.current?.autoplay?.stop();
  }, []);

  const handleMouseLeave = useCallback(() => {
    swiperRef.current?.autoplay?.start();
  }, []);

  /* ===== fetch stories ===== */
  useEffect(() => {
    const fetchStories = async () => {
      try {
        const res = await fetch("/api/stories");

        if (!res.ok) throw new Error("Network error");

        const json: StoriesResponse = await res.json();

        if (!json.success) throw new Error("API error");

        // sort by latest first, then by display order
        const limited = json.data
          .sort((a, b) => b.id - a.id) // latest first
          .slice(0, MAX_STORIES); // limit to MAX_STORIES items

        setStories(limited);
      } catch (err) {
        console.error(err);
        setError("Failed to load stories");
      } finally {
        setLoading(false);
      }
    };

    fetchStories();
  }, []);

  if (error) {
    return <div className="py-10 text-center">{error}</div>;
  }

  return (
    <div className="relative flex w-full flex-col">
      <div className="absolute inset-0 z-2 bg-gradient-to-b from-gray-100 via-teal-300 to-blue-600" />
      <div className="mob-noise absolute inset-0 z-8" />

      {/* Decorative bars */}
      <div className="relative -top-[6px] z-20 flex h-[21px] w-full justify-center gap-10 overflow-hidden md:gap-[200px]">
        {[9, 6, 12, 3, 15, 12].map((width, i) => (
          <span
            key={i}
            className={`hairline-12 inline-flex h-3 w-${width} bg-pink-500`}
          />
        ))}
      </div>

      <div className="relative z-20 flex flex-col">
        <div
          className="relative -top-[22px] z-12 flex overflow-hidden border-t border-gray-950/75 pt-20"
          onMouseEnter={handleMouseEnter}
          onMouseLeave={handleMouseLeave}
        >
          <Swiper
            loop
            freeMode={{ enabled: true, momentum: false }}
            speed={10000}
            autoplay={{ delay: 0, disableOnInteraction: false }}
            breakpoints={sliderBreakpoints}
            modules={[Autoplay, FreeMode]}
            onSwiper={(swiper) => (swiperRef.current = swiper)}
            className="swiper product-home"
          >
            {!loading &&
              stories.map((story, index) => (
                <SwiperSlide
                  key={story.id}
                  virtualIndex={index}
                  className="md:p-4"
                >
                  <Link
                    href={`/stories/${story.slug}`}
                    className="group relative flex border border-gray-950/25 bg-teal-600/50 p-1 transition-all duration-300 hover:border-gray-950 md:p-3"
                  >
                    <div className="relative h-52 w-full overflow-hidden border-1 border-dashed border-gray-100/75 p-2 pb-0 group-hover:border-gray-100 md:h-80 md:border-2 md:p-4 md:pb-0">
                      <div className="absolute top-0 left-0 h-full w-full bg-teal-600/25 opacity-75 blur-[40px]" />
                      <div className="align-center relative z-6 flex items-center justify-center p-1 md:p-2">
                        <h4 className="storyHeading line-clamp-3 text-center font-medium text-gray-100 capitalize">
                          {story.title}
                        </h4>
                      </div>
                      <div className="relative flex w-full items-center justify-center overflow-hidden align-top">
                        <div className="mx-auto flex aspect-[4/5] h-42 md:h-64">
                          {story.thumbnail && (
                            <Image
                              src={`${AWS_CDN_URL}/${story.thumbnail}`}
                              alt={story.title}
                              width={800}
                              height={1000}
                              className="aspect-[4/5] h-full w-full object-cover object-center"
                            />
                          )}
                        </div>
                      </div>
                    </div>
                  </Link>
                </SwiperSlide>
              ))}
          </Swiper>
        </div>

        <div className="flex flex-col items-center justify-center pt-8 pb-16">
          <div>
            <BtnLink
              id="link_view_all_stories"
              href="/stories"
              label="View all stories"
              target={false}
              color="white"
            />
          </div>
        </div>
      </div>
    </div>
  );
}
