"use client";

import { useEffect, useRef, useState } from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { CruiseCard } from "@/components/CruiseCard";
import {
  fetchPublicTours,
  mapPublicTourToCatalog,
  type CatalogTour,
  type TourListParams,
} from "@/lib/tours-api";

type Props = {
  id?: string;
  title: string;
  description: string;
  layout?: "mosaic" | "row";
  fetchParams?: TourListParams;
  seeAllHref?: string;
  limit?: number;
};

export function CruiseSection({
  id,
  title,
  description,
  layout = "row",
  fetchParams,
  seeAllHref = "/cruise-tours",
  limit,
}: Props) {
  const scrollerRef = useRef<HTMLDivElement>(null);
  const [cruises, setCruises] = useState<CatalogTour[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let active = true;
    (async () => {
      setLoading(true);
      try {
        const res = await fetchPublicTours({
          per_page: limit || (layout === "mosaic" ? 7 : 12),
          sort: "latest",
          ...fetchParams,
        });
        if (!active) return;
        setCruises((res.data || []).map(mapPublicTourToCatalog));
      } catch {
        if (!active) return;
        setCruises([]);
      } finally {
        if (active) setLoading(false);
      }
    })();
    return () => {
      active = false;
    };
  }, [fetchParams, layout, limit]);

  const scrollBy = (dir: 1 | -1) => {
    const el = scrollerRef.current;
    if (!el) return;
    el.scrollBy({ left: dir * Math.min(320, el.clientWidth * 0.8), behavior: "smooth" });
  };

  const items =
    limit != null ? cruises.slice(0, limit) : layout === "mosaic" ? cruises.slice(0, 7) : cruises;

  return (
    <section id={id} className="pb-10 sm:pb-12">
      <div className="container-page">
        <div className="mb-5 flex flex-col gap-4 sm:mb-6 sm:flex-row sm:items-end sm:justify-between">
          <div className="max-w-2xl">
            <h2 className="font-[family-name:var(--font-display)] text-2xl font-semibold text-brand sm:text-3xl">
              {title}
            </h2>
            <p className="mt-2 text-sm leading-relaxed text-muted sm:text-base">{description}</p>
          </div>
          <div className="flex items-center gap-2">
            {layout === "row" && (
              <>
                <button
                  type="button"
                  onClick={() => scrollBy(-1)}
                  className="grid h-10 w-10 place-items-center rounded-full border border-[var(--line)] text-brand transition hover:bg-accent/10"
                  aria-label="Previous"
                >
                  <ChevronLeft className="h-4 w-4" strokeWidth={2.4} />
                </button>
                <button
                  type="button"
                  onClick={() => scrollBy(1)}
                  className="grid h-10 w-10 place-items-center rounded-full border border-[var(--line)] text-brand transition hover:bg-accent/10"
                  aria-label="Next"
                >
                  <ChevronRight className="h-4 w-4" strokeWidth={2.4} />
                </button>
              </>
            )}
            <a
              href={seeAllHref}
              className="inline-flex items-center gap-2 rounded-full border border-[var(--line)] bg-white px-5 py-2.5 text-sm font-semibold text-brand transition hover:border-accent hover:text-accent"
            >
              See All
              <ChevronRight className="h-4 w-4" strokeWidth={2.4} />
            </a>
          </div>
        </div>

        {loading && (
          <p className="py-8 text-sm text-muted">Loading cruise tours…</p>
        )}

        {!loading && items.length === 0 && (
          <div className="rounded-2xl border border-dashed border-[var(--line)] px-6 py-12 text-center text-sm text-muted">
            No tours in this section yet.{" "}
            <a href={seeAllHref} className="font-semibold text-accent">
              Browse all cruises
            </a>
          </div>
        )}

        {!loading && items.length > 0 && layout === "mosaic" && (
          <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
            {items.map((cruise, index) => (
              <div
                key={cruise.id}
                className={`min-h-[22rem] ${index === 0 ? "sm:col-span-2" : ""}`}
              >
                <CruiseCard cruise={cruise} featured={index === 0} />
              </div>
            ))}
          </div>
        )}

        {!loading && items.length > 0 && layout === "row" && (
          <div
            ref={scrollerRef}
            className="flex gap-4 overflow-x-auto pb-1 [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
          >
            {items.map((cruise) => (
              <div key={cruise.id} className="w-[18rem] shrink-0 sm:w-[16.5rem]">
                <CruiseCard cruise={cruise} />
              </div>
            ))}
          </div>
        )}
      </div>
    </section>
  );
}
