"use client";

import { useMemo, useState } from "react";
import { ChevronDown } from "lucide-react";
import { CruiseListCard } from "@/components/CruiseListCard";
import type { CatalogTour } from "@/lib/tours-api";

type SortKey = "latest" | "price-asc" | "price-desc" | "rating-desc";

const PAGE_SIZE = 8;

type Props = {
  cruises: CatalogTour[];
  destinationName: string;
};

export function DestinationCatalog({ cruises, destinationName }: Props) {
  const [duration, setDuration] = useState<"all" | "Day tour" | "Overnight Tour">("all");
  const [sort, setSort] = useState<SortKey>("latest");
  const [page, setPage] = useState(1);

  const filtered = useMemo(() => {
    let list = [...cruises];
    if (duration !== "all") list = list.filter((c) => c.duration === duration);
    list.sort((a, b) => {
      if (sort === "price-asc") return (a.price ?? 9999) - (b.price ?? 9999);
      if (sort === "price-desc") return (b.price ?? 0) - (a.price ?? 0);
      if (sort === "rating-desc") return b.rating - a.rating;
      return b.seed - a.seed;
    });
    return list;
  }, [cruises, duration, sort]);

  const totalPages = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));
  const currentPage = Math.min(page, totalPages);
  const pageItems = filtered.slice((currentPage - 1) * PAGE_SIZE, currentPage * PAGE_SIZE);

  return (
    <section className="bg-white py-10 sm:py-12">
      <div className="mx-auto w-[min(1180px,calc(100%-2rem))]">
        <div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
          <h2 className="font-[family-name:var(--font-display)] text-xl font-semibold text-brand-deep sm:text-2xl">
            {filtered.length} suitable cruise tours in {destinationName}
          </h2>
          <div className="flex flex-wrap items-center gap-2">
            {(["all", "Day tour", "Overnight Tour"] as const).map((item) => (
              <button
                key={item}
                type="button"
                onClick={() => {
                  setDuration(item);
                  setPage(1);
                }}
                className={`rounded-full px-3 py-1.5 text-xs font-semibold ${
                  duration === item
                    ? "bg-accent text-white"
                    : "border border-[var(--line)] text-brand-deep hover:bg-[#f3fafc]"
                }`}
              >
                {item === "all" ? "All" : item}
              </button>
            ))}
            <label className="relative inline-flex items-center gap-2 text-sm text-muted">
              Sort by:
              <select
                value={sort}
                onChange={(e) => {
                  setSort(e.target.value as SortKey);
                  setPage(1);
                }}
                className="appearance-none rounded-full border border-[var(--line)] bg-white py-2 pr-8 pl-3 text-sm font-semibold text-brand-deep outline-none"
              >
                <option value="latest">Latest</option>
                <option value="price-asc">Pricing ascending</option>
                <option value="price-desc">Pricing descending</option>
                <option value="rating-desc">Highest ranking</option>
              </select>
              <ChevronDown className="pointer-events-none absolute top-1/2 right-2.5 h-4 w-4 -translate-y-1/2 text-muted" />
            </label>
          </div>
        </div>

        <div className="space-y-4">
          {pageItems.map((cruise) => (
            <CruiseListCard key={cruise.id} cruise={cruise} />
          ))}
          {pageItems.length === 0 && (
            <div className="rounded-2xl border border-dashed border-[var(--line)] px-6 py-16 text-center text-muted">
              No cruises for this destination yet.{" "}
              <a href="/cruise-tours" className="font-semibold text-accent">
                Browse all cruises
              </a>
            </div>
          )}
        </div>

        {totalPages > 1 && (
          <nav className="mt-8 flex flex-wrap items-center justify-center gap-2" aria-label="Pagination">
            <button
              type="button"
              disabled={currentPage <= 1}
              onClick={() => setPage((p) => Math.max(1, p - 1))}
              className="rounded-full border border-[var(--line)] px-3 py-1.5 text-sm font-semibold text-brand-deep disabled:opacity-40"
            >
              Prev
            </button>
            {Array.from({ length: totalPages }, (_, i) => i + 1).map((n) => (
              <button
                key={n}
                type="button"
                onClick={() => setPage(n)}
                className={`grid h-9 w-9 place-items-center rounded-full text-sm font-semibold ${
                  n === currentPage
                    ? "bg-accent text-white"
                    : "border border-[var(--line)] text-brand-deep hover:bg-[#f3fafc]"
                }`}
              >
                {n}
              </button>
            ))}
            <button
              type="button"
              disabled={currentPage >= totalPages}
              onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
              className="rounded-full border border-[var(--line)] px-3 py-1.5 text-sm font-semibold text-brand-deep disabled:opacity-40"
            >
              Next
            </button>
          </nav>
        )}
      </div>
    </section>
  );
}
