"use client";

import { useRef, useState, useEffect } from "react";
import Link from "next/link";
import { ChevronLeft, ChevronRight, ArrowRight } from "lucide-react";
import { SampleArticle } from "@/services/joomlaService";

interface RelatedSamplesCarouselProps {
  samples: SampleArticle[];
  subjectAlias: string;
}

export function RelatedSamplesCarousel({ samples, subjectAlias }: RelatedSamplesCarouselProps) {
  const scrollRef = useRef<HTMLDivElement>(null);
  const [canScrollLeft, setCanScrollLeft] = useState(false);
  const [canScrollRight, setCanScrollRight] = useState(true);

  const checkScroll = () => {
    if (!scrollRef.current) return;
    const { scrollLeft, scrollWidth, clientWidth } = scrollRef.current;
    setCanScrollLeft(scrollLeft > 5);
    setCanScrollRight(scrollLeft + clientWidth < scrollWidth - 5);
  };

  useEffect(() => {
    checkScroll();
    const current = scrollRef.current;
    if (current) {
      current.addEventListener("scroll", checkScroll, { passive: true });
      window.addEventListener("resize", checkScroll);
    }
    return () => {
      if (current) {
        current.removeEventListener("scroll", checkScroll);
      }
      window.removeEventListener("resize", checkScroll);
    };
  }, []);

  const handleScroll = (direction: "left" | "right") => {
    if (!scrollRef.current) return;
    const container = scrollRef.current;
    const scrollAmount = container.clientWidth;
    container.scrollBy({
      left: direction === "left" ? -scrollAmount : scrollAmount,
      behavior: "smooth",
    });
  };

  if (!samples || samples.length === 0) return null;

  return (
    <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-10 border-t border-slate-200 mt-12">
      {/* Header section with orange underline under title */}
      <div className="flex flex-wrap items-baseline justify-between gap-3 mb-6 pb-2 border-b border-slate-100">
        <div className="flex items-baseline gap-2">
          <h2 className="text-xl sm:text-2xl font-bold text-slate-900 border-b-2 border-[#f58e0e] pb-1 inline-block">
            Latest Related Free-samples
          </h2>
          <span className="text-xs sm:text-sm font-normal text-slate-500">
            (1000+ Free-samples )
          </span>
        </div>
        <Link
          href={subjectAlias ? `/free-samples/${subjectAlias}` : "/free-samples"}
          className="text-sm font-bold text-[#f58e0e] hover:underline shrink-0"
        >
          View More
        </Link>
      </div>

      {/* Carousel Container with side arrows */}
      <div className="relative flex items-center">
        {/* Left Arrow */}
        <button
          onClick={() => handleScroll("left")}
          disabled={!canScrollLeft}
          aria-label="Previous samples"
          className={`p-2 transition-all text-[#f58e0e] shrink-0 disabled:opacity-30 disabled:cursor-not-allowed hover:scale-110 active:scale-95 ${
            !canScrollLeft ? "opacity-30 cursor-not-allowed" : "cursor-pointer"
          }`}
        >
          <ChevronLeft className="w-7 h-7 sm:w-8 sm:h-8 stroke-[2.5]" />
        </button>

        {/* Scrollable Cards Track */}
        <div
          ref={scrollRef}
          className="flex-1 flex gap-5 overflow-x-auto scroll-smooth no-scrollbar py-2 px-1 snap-x snap-mandatory"
          style={{ scrollbarWidth: "none", msOverflowStyle: "none" }}
        >
          {samples.map((sample) => (
            <div
              key={sample.id}
              className="w-full sm:w-[calc(50%-10px)] lg:w-[calc(33.333%-14px)] shrink-0 snap-start flex flex-col justify-between bg-[#f8f8f8] hover:bg-[#f3f3f3] border border-slate-200/80 rounded-lg p-5 sm:p-6 transition-all duration-200 shadow-sm hover:shadow-md"
            >
              <div>
                <h3 className="font-bold text-sm sm:text-base text-slate-900 line-clamp-2 leading-snug mb-3 min-h-[2.75rem]">
                  {sample.title}
                </h3>
                <p className="text-xs text-slate-600 leading-relaxed line-clamp-6 mb-4">
                  {sample.excerpt}
                </p>
              </div>
              <Link
                href={`/free-samples/${subjectAlias || "business-assignment-help"}/${sample.alias}`}
                className="inline-flex items-center gap-1.5 text-xs sm:text-sm font-semibold text-[#f58e0e] hover:text-[#e07d0d] hover:underline mt-auto pt-2"
              >
                <span>View or Download Sample</span>
                <ArrowRight className="w-4 h-4 stroke-[2.5]" />
              </Link>
            </div>
          ))}
        </div>

        {/* Right Arrow */}
        <button
          onClick={() => handleScroll("right")}
          disabled={!canScrollRight}
          aria-label="Next samples"
          className={`p-2 transition-all text-[#f58e0e] shrink-0 disabled:opacity-30 disabled:cursor-not-allowed hover:scale-110 active:scale-95 ${
            !canScrollRight ? "opacity-30 cursor-not-allowed" : "cursor-pointer"
          }`}
        >
          <ChevronRight className="w-7 h-7 sm:w-8 sm:h-8 stroke-[2.5]" />
        </button>
      </div>
    </div>
  );
}
