"use client";

import { useEffect, useMemo, useState, type ReactNode } from "react";
import { useSearchParams } from "next/navigation";
import {
  ChevronDown,
  Clock,
  Mountain,
  RotateCcw,
  SlidersHorizontal,
  Star,
} from "lucide-react";
import { CruiseListCard } from "@/components/CruiseListCard";
import {
  cruiseFilterMeta,
  parseCruiseToursSearchParams,
  PRICE_MAX,
  PRICE_MIN,
  type CruiseToursInitialFilters,
} from "@/data/cruises";
import {
  fetchPublicTours,
  mapPublicTourToCatalog,
  type CatalogTour,
} from "@/lib/tours-api";

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

const PAGE_SIZE = 8;

function Pill({
  active,
  onClick,
  children,
}: {
  active: boolean;
  onClick: () => void;
  children: ReactNode;
}) {
  return (
    <button
      type="button"
      onClick={onClick}
      className={`inline-flex items-center gap-1.5 rounded-full border px-3 py-1.5 text-xs font-semibold transition ${
        active
          ? "border-accent bg-accent text-white"
          : "border-[var(--line)] bg-white text-brand-deep hover:border-accent/40 hover:bg-[#f3fafc]"
      }`}
    >
      {children}
    </button>
  );
}

export function CruiseToursCatalog() {
  const searchParams = useSearchParams();
  const initial = useMemo(
    () =>
      parseCruiseToursSearchParams({
        destination: searchParams.get("destination") ?? undefined,
        duration: searchParams.get("duration") ?? undefined,
        type: searchParams.get("type") ?? undefined,
        q: searchParams.get("q") ?? undefined,
        category: searchParams.get("category") ?? undefined,
      }),
    [searchParams],
  );

  return <CruiseToursCatalogInner key={searchParams.toString()} initial={initial} />;
}

function CruiseToursCatalogInner({ initial }: { initial: CruiseToursInitialFilters }) {
  const [tours, setTours] = useState<CatalogTour[]>([]);
  const [total, setTotal] = useState(0);
  const [totalPages, setTotalPages] = useState(1);
  const [loading, setLoading] = useState(true);
  const [loadError, setLoadError] = useState("");
  const [destinations, setDestinations] = useState<string[]>(initial.destinations ?? []);
  const [durations, setDurations] = useState<string[]>(initial.durations ?? []);
  const [category, setCategory] = useState<"all" | "best-seller" | "package">(
    initial.category ?? "all",
  );
  const [priceMin, setPriceMin] = useState(PRICE_MIN);
  const [priceMax, setPriceMax] = useState(PRICE_MAX);
  const [minRating, setMinRating] = useState(0);
  const [types, setTypes] = useState<string[]>(
    initial.types?.length ? initial.types : ["All"],
  );
  const [activities, setActivities] = useState<string[]>([]);
  const [facilities, setFacilities] = useState<string[]>([]);
  const [query, setQuery] = useState(initial.q ?? "");
  const [sort, setSort] = useState<SortKey>("latest");
  const [page, setPage] = useState(1);
  const [mobileFilters, setMobileFilters] = useState(false);

  const [debouncedPriceMin, setDebouncedPriceMin] = useState(priceMin);
  const [debouncedPriceMax, setDebouncedPriceMax] = useState(priceMax);
  const [debouncedQuery, setDebouncedQuery] = useState(query);

  useEffect(() => {
    const timer = window.setTimeout(() => {
      setDebouncedPriceMin(priceMin);
      setDebouncedPriceMax(priceMax);
    }, 250);
    return () => window.clearTimeout(timer);
  }, [priceMin, priceMax]);

  useEffect(() => {
    const timer = window.setTimeout(() => setDebouncedQuery(query), 300);
    return () => window.clearTimeout(timer);
  }, [query]);

  useEffect(() => {
    let active = true;
    const timer = window.setTimeout(async () => {
      setLoading(true);
      setLoadError("");
      try {
        const selectedTypes = types.filter((t) => t !== "All");
        const res = await fetchPublicTours({
          q: debouncedQuery.trim() || undefined,
          bay: destinations.length ? destinations.join(",") : undefined,
          duration: durations.length ? durations.join(",") : undefined,
          category: category === "all" ? undefined : category,
          types: selectedTypes.length ? selectedTypes.join(",") : undefined,
          activities: activities.length ? activities.join(",") : undefined,
          facilities: facilities.length ? facilities.join(",") : undefined,
          min_price: debouncedPriceMin,
          max_price: debouncedPriceMax,
          rating: minRating > 0 ? minRating : undefined,
          sort,
          page,
          per_page: PAGE_SIZE,
        });
        if (!active) return;
        setTours(res.data.map(mapPublicTourToCatalog));
        setTotal(res.total);
        setTotalPages(Math.max(1, res.last_page));
      } catch (err) {
        if (!active) return;
        setLoadError(err instanceof Error ? err.message : "Failed to load tours");
        setTours([]);
        setTotal(0);
        setTotalPages(1);
      } finally {
        if (active) setLoading(false);
      }
    }, 0);

    return () => {
      active = false;
      window.clearTimeout(timer);
    };
  }, [
    destinations,
    durations,
    category,
    debouncedPriceMin,
    debouncedPriceMax,
    minRating,
    types,
    activities,
    facilities,
    debouncedQuery,
    sort,
    page,
  ]);

  const priceSpan = PRICE_MAX - PRICE_MIN;
  const rangeLeft = ((priceMin - PRICE_MIN) / priceSpan) * 100;
  const rangeRight = ((PRICE_MAX - priceMax) / priceSpan) * 100;

  const toggle = (
    value: string,
    list: string[],
    setList: (next: string[]) => void,
    exclusiveAll = false,
  ) => {
    setPage(1);
    if (exclusiveAll && value === "All") {
      setList(["All"]);
      return;
    }
    const withoutAll = list.filter((v) => v !== "All");
    if (list.includes(value)) {
      const next = withoutAll.filter((v) => v !== value);
      setList(next.length ? next : exclusiveAll ? ["All"] : []);
    } else {
      setList(exclusiveAll ? [...withoutAll, value] : [...list, value]);
    }
  };

  const clearAll = () => {
    setDestinations([]);
    setDurations([]);
    setCategory("all");
    setPriceMin(PRICE_MIN);
    setPriceMax(PRICE_MAX);
    setMinRating(0);
    setTypes(["All"]);
    setActivities([]);
    setFacilities([]);
    setQuery("");
    setSort("latest");
    setPage(1);
  };

  const currentPage = Math.min(page, totalPages);
  const pageItems = tours;

  const filters = (
    <div className="space-y-6">
      <div className="flex items-center justify-between gap-3">
        <h2 className="text-base font-bold text-brand-deep">Filter by</h2>
        <button
          type="button"
          onClick={clearAll}
          className="inline-flex items-center gap-1 text-xs font-semibold text-accent hover:text-accent-hover"
        >
          <RotateCcw className="h-3.5 w-3.5" />
          Clear all
        </button>
      </div>

      <div>
        <p className="mb-2.5 text-sm font-semibold text-brand-deep">Choose a destination</p>
        <div className="flex flex-wrap gap-2">
          {cruiseFilterMeta.destinations.map((item) => (
            <Pill
              key={item}
              active={destinations.includes(item)}
              onClick={() => toggle(item, destinations, setDestinations)}
            >
              <Mountain className="h-3.5 w-3.5" />
              {item}
            </Pill>
          ))}
        </div>
      </div>

      <div>
        <p className="mb-2.5 text-sm font-semibold text-brand-deep">Duration</p>
        <div className="flex flex-wrap gap-2">
          {cruiseFilterMeta.durations.map((item) => (
            <Pill
              key={item}
              active={durations.includes(item)}
              onClick={() => toggle(item, durations, setDurations)}
            >
              <Clock className="h-3.5 w-3.5" />
              {item}
            </Pill>
          ))}
        </div>
      </div>

      <div>
        <p className="mb-2.5 text-sm font-semibold text-brand-deep">Category</p>
        <div className="flex flex-wrap gap-2">
          <Pill active={category === "best-seller"} onClick={() => { setCategory(category === "best-seller" ? "all" : "best-seller"); setPage(1); }}>
            Best seller
          </Pill>
          <Pill active={category === "package"} onClick={() => { setCategory(category === "package" ? "all" : "package"); setPage(1); }}>
            Package tour
          </Pill>
        </div>
      </div>

      <div>
        <div className="mb-3 flex items-center justify-between gap-2">
          <p className="text-sm font-semibold text-brand-deep">Price</p>
          <p className="text-xs font-semibold text-accent">
            ${priceMin} – ${priceMax}
          </p>
        </div>
        <div className="price-slider mt-2 mb-1">
          <div className="price-slider__rail" />
          <div
            className="price-slider__fill"
            style={{ left: `${rangeLeft}%`, right: `${rangeRight}%` }}
          />
          <input
            type="range"
            min={PRICE_MIN}
            max={PRICE_MAX}
            step={5}
            value={priceMin}
            aria-label="Minimum price"
            className="price-range"
            onChange={(e) => {
              const next = Math.min(Number(e.target.value), priceMax - 5);
              setPriceMin(next);
              setPage(1);
            }}
          />
          <input
            type="range"
            min={PRICE_MIN}
            max={PRICE_MAX}
            step={5}
            value={priceMax}
            aria-label="Maximum price"
            className="price-range"
            onChange={(e) => {
              const next = Math.max(Number(e.target.value), priceMin + 5);
              setPriceMax(next);
              setPage(1);
            }}
          />
        </div>
        <div className="flex justify-between text-[11px] text-muted">
          <span>${PRICE_MIN}</span>
          <span>${PRICE_MAX}</span>
        </div>
      </div>

      <div>
        <p className="mb-2.5 text-sm font-semibold text-brand-deep">Ranking</p>
        <div className="space-y-2">
          <button
            type="button"
            onClick={() => {
              setMinRating(0);
              setPage(1);
            }}
            className={`flex w-full items-center justify-between rounded-xl border px-3 py-2 text-sm transition ${
              minRating === 0
                ? "border-accent bg-accent/10 text-brand-deep"
                : "border-[var(--line)] text-brand-deep hover:bg-[#f3fafc]"
            }`}
          >
            Any ranking
          </button>
          {cruiseFilterMeta.rankings.map((stars) => (
            <button
              key={stars}
              type="button"
              onClick={() => {
                setMinRating(stars);
                setPage(1);
              }}
              className={`flex w-full items-center justify-between rounded-xl border px-3 py-2 text-sm transition ${
                minRating === stars
                  ? "border-accent bg-accent/10 text-brand-deep"
                  : "border-[var(--line)] text-brand-deep hover:bg-[#f3fafc]"
              }`}
            >
              <span className="inline-flex items-center gap-0.5 text-amber-400">
                {Array.from({ length: 5 }).map((_, i) => (
                  <Star
                    key={i}
                    className={`h-3.5 w-3.5 ${i < stars ? "text-amber-400" : "text-[#d7e2e7]"}`}
                    fill="currentColor"
                    strokeWidth={0}
                  />
                ))}
              </span>
              <span className="text-xs font-semibold text-muted">
                {stars === 5 ? "5 stars" : `${stars}+ stars`}
              </span>
            </button>
          ))}
        </div>
      </div>

      <div>
        <p className="mb-2.5 text-sm font-semibold text-brand-deep">Cruise type</p>
        <div className="space-y-2">
          {cruiseFilterMeta.cruiseTypes.map((type) => (
            <label key={type} className="flex cursor-pointer items-center gap-2 text-sm text-brand-deep">
              <input
                type="checkbox"
                checked={types.includes(type)}
                onChange={() => toggle(type, types, setTypes, true)}
                className="accent-[var(--accent)]"
              />
              {type}
            </label>
          ))}
        </div>
      </div>

      <div>
        <p className="mb-2.5 text-sm font-semibold text-brand-deep">Activities</p>
        <div className="flex flex-wrap gap-2">
          {cruiseFilterMeta.activities.map((item) => (
            <Pill
              key={item}
              active={activities.includes(item)}
              onClick={() => toggle(item, activities, setActivities)}
            >
              {item}
            </Pill>
          ))}
        </div>
      </div>

      <div>
        <p className="mb-2.5 text-sm font-semibold text-brand-deep">Facilities</p>
        <div className="flex flex-wrap gap-2">
          {cruiseFilterMeta.facilities.map((item) => (
            <Pill
              key={item}
              active={facilities.includes(item)}
              onClick={() => toggle(item, facilities, setFacilities)}
            >
              {item}
            </Pill>
          ))}
        </div>
      </div>
    </div>
  );

  return (
    <section className="bg-white py-10 sm:py-12">
      <div className="mx-auto grid w-[min(1180px,calc(100%-2rem))] gap-6 lg:grid-cols-[280px_1fr] lg:gap-8">
        {/* Desktop filters */}
        <aside className="hidden h-fit rounded-2xl border border-[var(--line)] bg-white p-5 shadow-[0_8px_24px_rgba(13,58,77,0.04)] lg:sticky lg:top-28 lg:block">
          {filters}
        </aside>

        <div>
          <div className="mb-5 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
            <div>
              <h2 className="font-[family-name:var(--font-display)] text-xl font-semibold text-brand-deep sm:text-2xl">
                {total} suitable cruise tours
              </h2>
              {query.trim() ? (
                <p className="mt-1 text-sm text-muted">
                  Search results for{" "}
                  <span className="font-semibold text-brand-deep">“{query.trim()}”</span>
                </p>
              ) : null}
            </div>
            <div className="flex items-center gap-2">
              <button
                type="button"
                onClick={() => setMobileFilters(true)}
                className="inline-flex items-center gap-2 rounded-full border border-[var(--line)] px-3 py-2 text-sm font-semibold text-brand-deep lg:hidden"
              >
                <SlidersHorizontal className="h-4 w-4" />
                Filters
              </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">
            {loading && (
              <div className="rounded-2xl border border-[var(--line)] px-6 py-16 text-center text-muted">
                Loading tours…
              </div>
            )}
            {!loading && loadError && (
              <div className="rounded-2xl border border-red-200 bg-red-50 px-6 py-10 text-center text-sm text-red-600">
                {loadError}
              </div>
            )}
            {!loading &&
              !loadError &&
              pageItems.map((cruise) => (
                <CruiseListCard key={cruise.id} cruise={cruise} />
              ))}
            {!loading && !loadError && pageItems.length === 0 && (
              <div className="rounded-2xl border border-dashed border-[var(--line)] px-6 py-16 text-center text-muted">
                No cruises match your filters. Try clearing some filters.
              </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>
      </div>

      {/* Mobile filter drawer */}
      {mobileFilters && (
        <div className="fixed inset-0 z-[70] lg:hidden">
          <button
            type="button"
            className="absolute inset-0 bg-black/40"
            aria-label="Close filters"
            onClick={() => setMobileFilters(false)}
          />
          <div className="absolute inset-y-0 left-0 w-[min(340px,88vw)] overflow-y-auto bg-white p-5 shadow-xl">
            {filters}
            <button
              type="button"
              onClick={() => setMobileFilters(false)}
              className="btn-accent mt-6 w-full py-3 text-sm"
            >
              Show {total} cruises
            </button>
          </div>
        </div>
      )}
    </section>
  );
}
