"use client";

import { useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import {
  ChevronDown,
  MapPin,
  Plus,
  Route,
  Search,
  Ship,
  SlidersHorizontal,
  X,
} from "lucide-react";
import { AiImage } from "@/components/AiImage";
import { cruiseSlug } from "@/data/cruise-detail";
import {
  normalizeCruiseDestination,
  normalizeCruiseDuration,
} from "@/data/cruises";
import { useHomeSettings } from "@/components/HomeProvider";
import {
  baitulongCruises,
  bestSellers,
  cruiseImage,
  cruiseTypes,
  filterDestinations,
  halongCruises,
  heroImage as fallbackHeroImage,
  lanhaCruises,
  type Cruise,
} from "@/data/home";
import {
  categoryImageUrl,
  fetchPublicCategories,
  type Category,
} from "@/lib/categories-api";
import { homeImageUrl } from "@/lib/home-api";
import { aiImage } from "@/lib/pollinations";

const defaultSuggestionIds = [
  "indochina",
  "indochina-lanha",
  "signature-royal",
  "signature-halong",
] as const;

const tabs = [
  { key: "filter", label: "Filter", icon: SlidersHorizontal },
  { key: "search", label: "Search Cruise’s Name", icon: Ship },
  { key: "package", label: "Package Tour", icon: Route },
] as const;

export function Hero() {
  const router = useRouter();
  const { home } = useHomeSettings();
  const [tab, setTab] = useState<(typeof tabs)[number]["key"]>("filter");
  const [destination, setDestination] = useState("");
  const [duration, setDuration] = useState("");
  const [packageTypes, setPackageTypes] = useState<string[]>(["Family"]);
  const [categories, setCategories] = useState<Category[]>([]);
  const [searchQuery, setSearchQuery] = useState("");
  const [showSuggestions, setShowSuggestions] = useState(false);
  const heroSrc = homeImageUrl(home.hero_image, fallbackHeroImage);
  const heroTitle =
    home.hero_title ||
    "Emerald Waters of the Gulf of Tonkin, Booking all cruise with best price here";

  useEffect(() => {
    let active = true;
    (async () => {
      try {
        const res = await fetchPublicCategories();
        if (!active) return;
        setCategories(res.data || []);
      } catch {
        if (!active) return;
        setCategories([]);
      }
    })();
    return () => {
      active = false;
    };
  }, []);

  const typeOptions = useMemo(() => {
    if (categories.length > 0) {
      return categories.map((c, index) => ({
        key: c.slug || String(c.id),
        name: c.title,
        image: c.image ? categoryImageUrl(c.image) : null,
        prompt: `${c.title} cruise Ha Long Bay Vietnam`,
        seed: 40 + index,
      }));
    }
    return cruiseTypes.map((t) => ({
      key: t.name,
      name: t.name,
      image: null as string | null,
      prompt: t.prompt,
      seed: t.seed,
    }));
  }, [categories]);

  const goCruiseTours = (params: Record<string, string | undefined>) => {
    const qs = new URLSearchParams();
    Object.entries(params).forEach(([key, value]) => {
      if (value) qs.set(key, value);
    });
    const query = qs.toString();
    router.push(query ? `/cruise-tours?${query}` : "/cruise-tours");
  };

  const searchByFilter = () => {
    const normalized = normalizeCruiseDestination(destination);
    const dest = normalized || destination.trim() || undefined;
    const dur = normalizeCruiseDuration(duration);
    goCruiseTours({
      destination: dest,
      duration: dur ?? undefined,
    });
  };

  const searchByPackage = () => {
    const types = [...new Set(packageTypes.map((t) => t.trim()).filter(Boolean))];
    goCruiseTours({
      category: "package",
      type: types.length ? types.join(",") : undefined,
    });
  };

  const searchByName = () => {
    const q = searchQuery.trim();
    goCruiseTours(q ? { q } : {});
  };

  const allCruises = useMemo(() => {
    const map = new Map<string, Cruise>();
    [...bestSellers, ...halongCruises, ...lanhaCruises, ...baitulongCruises].forEach((c) => {
      map.set(c.id, c);
    });
    return [...map.values()];
  }, []);

  const searchSuggestions = useMemo(() => {
    const q = searchQuery.trim().toLowerCase();
    if (!q) {
      return defaultSuggestionIds
        .map((id) => allCruises.find((c) => c.id === id))
        .filter((c): c is Cruise => Boolean(c));
    }
    return allCruises
      .filter(
        (c) => c.name.toLowerCase().includes(q) || c.bay.toLowerCase().includes(q),
      )
      .slice(0, 4);
  }, [allCruises, searchQuery]);

  const canAddType = packageTypes.length < typeOptions.length;

  const togglePackageType = (name: string) => {
    setPackageTypes((prev) => {
      if (prev.includes(name)) {
        if (prev.length <= 1) return prev;
        return prev.filter((n) => n !== name);
      }
      if (prev.length >= typeOptions.length) return prev;
      return [...prev, name];
    });
  };

  const removeType = (index: number) => {
    setPackageTypes((prev) => {
      if (prev.length <= 1) return prev;
      return prev.filter((_, i) => i !== index);
    });
  };

  useEffect(() => {
    if (!typeOptions.length) return;
    setPackageTypes((prev) => {
      const valid = prev.filter((name) => typeOptions.some((t) => t.name === name));
      if (valid.length) return valid;
      return [typeOptions[0].name];
    });
  }, [typeOptions]);

  return (
    <section className="relative overflow-hidden">
      <div className="relative min-h-[100svh]">
        <div className="absolute inset-0">
          <AiImage src={heroSrc} alt="Emerald waters of Ha Long Bay" className="h-full w-full" />
          <div className="absolute inset-0 bg-[linear-gradient(180deg,rgba(10,45,55,0.45)_0%,rgba(10,45,55,0.22)_42%,rgba(10,45,55,0.42)_100%)]" />
        </div>

        <div className="relative mx-auto flex min-h-[100svh] w-[min(1240px,calc(100%-2rem))] flex-col justify-center gap-7 pt-[92px] pb-10 lg:gap-8 lg:pb-14">
          <div className="max-w-[760px] text-left fade-up">
            <h1 className="font-[family-name:var(--font-display)] text-[1.85rem] leading-[1.15] font-semibold tracking-[-0.02em] text-white sm:text-[2.45rem] lg:text-[2.75rem]">
              {heroTitle}
            </h1>
          </div>

          <div className="mx-auto w-full max-w-[1260px] fade-up-delay">
            <div className="overflow-hidden rounded-[16px] bg-white shadow-[0_18px_50px_rgba(0,0,0,0.28)]">
              <div className="flex flex-wrap bg-[#1a2f44]">
                {tabs.map(({ key, label, icon: Icon }) => {
                  const active = tab === key;
                  return (
                    <button
                      key={key}
                      type="button"
                      onClick={() => {
                        setTab(key);
                        setShowSuggestions(key === "search");
                      }}
                      className={`relative inline-flex items-center gap-2 px-4 py-3 text-[13px] font-semibold transition sm:px-5 sm:text-sm ${
                        active
                          ? "bg-white text-[#1c2b33] before:absolute before:top-0 before:left-0 before:h-full before:w-[3px] before:bg-[#ff6a2b]"
                          : "text-white/85 hover:text-white"
                      }`}
                    >
                      <Icon
                        className={`h-4 w-4 ${active ? "text-[#ff6a2b]" : "text-current"}`}
                        strokeWidth={2}
                      />
                      <span className="whitespace-nowrap">{label}</span>
                    </button>
                  );
                })}
              </div>

              <div className="p-3.5 sm:p-4">
                {tab === "filter" && (
                  <>
                    <div className="grid gap-2.5 md:grid-cols-[1.35fr_1fr_52px]">
                      <label className="relative flex h-[54px] cursor-pointer flex-col justify-center rounded-[12px] bg-[#eef2f3] px-4 pr-9">
                        <span className="text-[10px] font-bold tracking-[0.08em] text-[#8a969c] uppercase">
                          Destination
                        </span>
                        <select
                          value={destination}
                          onChange={(e) => setDestination(e.target.value)}
                          className="w-full appearance-none bg-transparent text-[14px] font-semibold text-[#1c2b33] outline-none"
                        >
                          <option value="">Choose A Destination</option>
                          {filterDestinations.map((item) => (
                            <option key={item.name} value={item.name}>
                              {item.name}
                            </option>
                          ))}
                        </select>
                        <ChevronDown className="pointer-events-none absolute top-1/2 right-3.5 h-4 w-4 -translate-y-1/2 text-[#1c2b33]/55" />
                      </label>

                      <label className="relative flex h-[54px] cursor-pointer flex-col justify-center rounded-[12px] bg-[#eef2f3] px-4 pr-9">
                        <span className="text-[10px] font-bold tracking-[0.08em] text-[#8a969c] uppercase">
                          Duration
                        </span>
                        <select
                          value={duration}
                          onChange={(e) => setDuration(e.target.value)}
                          className="w-full appearance-none bg-transparent text-[14px] font-semibold text-[#1c2b33] outline-none"
                        >
                          <option value="">Option</option>
                          <option value="Day Cruise">Day Cruise</option>
                          <option value="Dinner Cruise">Dinner Cruise</option>
                          <option value="Overnight Cruise">Overnight Cruise</option>
                          <option value="2D1N">2D1N</option>
                          <option value="3D2N">3D2N</option>
                        </select>
                        <ChevronDown className="pointer-events-none absolute top-1/2 right-3.5 h-4 w-4 -translate-y-1/2 text-[#1c2b33]/55" />
                      </label>

                      <button
                        type="button"
                        onClick={searchByFilter}
                        className="grid h-[54px] w-full place-items-center rounded-[12px] bg-[#ff6a2b] text-white transition hover:bg-[#ff814d] md:w-[52px]"
                        aria-label="Search cruises"
                      >
                        <Search className="h-5 w-5" strokeWidth={2.4} />
                      </button>
                    </div>

                    <div className="dest-scroll mt-3 flex gap-2 overflow-x-auto pb-2 [scroll-snap-type:x_mandatory] [-webkit-overflow-scrolling:touch]">
                      {filterDestinations.map((item) => {
                        const active = destination === item.name;
                        return (
                          <button
                            key={item.name}
                            type="button"
                            onClick={() =>
                              setDestination((prev) =>
                                prev === item.name ? "" : item.name,
                              )
                            }
                            className="relative h-[78px] w-[min(148px,42vw)] shrink-0 overflow-hidden rounded-[12px] text-left [scroll-snap-align:start] sm:h-[84px] sm:w-[168px]"
                          >
                            <AiImage
                              src={aiImage(item.prompt, {
                                width: 360,
                                height: 220,
                                seed: item.seed,
                              })}
                              alt={item.name}
                              className="h-full w-full"
                            />
                            <div className="absolute inset-0 bg-gradient-to-t from-black/75 via-black/20 to-black/5" />
                            <span
                              className={`absolute top-2.5 left-2.5 h-3.5 w-3.5 rounded-full border-2 border-white ${
                                active ? "bg-[#ff6a2b]" : "bg-transparent"
                              }`}
                            />
                            <span className="absolute bottom-2.5 left-2.5 text-[12px] font-semibold text-white">
                              {item.name}
                            </span>
                          </button>
                        );
                      })}
                    </div>
                  </>
                )}

                {tab === "package" && (
                  <div className="space-y-4">
                    <div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
                      <div className="flex min-w-0 flex-1 flex-wrap items-start gap-x-1 gap-y-3">
                        {packageTypes.map((type, index) => (
                          <div key={`${type}-${index}`} className="flex items-start">
                            <div className="flex w-[132px] flex-col items-center sm:w-[148px]">
                              <span className="grid h-7 w-7 place-items-center rounded-full bg-[#ff6a2b] text-[11px] font-bold text-white">
                                {String(index + 1).padStart(2, "0")}
                              </span>
                              <div className="mt-2 inline-flex max-w-full items-center gap-1.5 rounded-full bg-[#2b98ba] px-3 py-1.5 text-[12px] font-semibold text-white">
                                <Ship className="h-3.5 w-3.5 shrink-0" />
                                <span className="truncate">{type}</span>
                                {packageTypes.length > 1 && (
                                  <button
                                    type="button"
                                    onClick={() => removeType(index)}
                                    className="ml-0.5 grid h-4 w-4 place-items-center rounded-full bg-white/20 text-white hover:bg-white/30"
                                    aria-label={`Remove ${type}`}
                                  >
                                    <X className="h-3 w-3" strokeWidth={2.6} />
                                  </button>
                                )}
                              </div>
                            </div>
                            {index < packageTypes.length - 1 || canAddType ? (
                              <div className="mt-3.5 h-px w-6 border-t border-dashed border-[#c5ced3] sm:w-8" />
                            ) : null}
                          </div>
                        ))}

                        {canAddType && (
                          <div className="flex w-[72px] flex-col items-center">
                            <span className="grid h-7 w-7 place-items-center rounded-full bg-[#e8eef1] text-[11px] font-bold text-[#8a969c]">
                              {String(packageTypes.length + 1).padStart(2, "0")}
                            </span>
                            <span
                              className="mt-2 grid h-9 w-9 place-items-center rounded-full border border-[#d7dee2] bg-white text-[#8a969c]"
                              aria-hidden
                            >
                              <Plus className="h-4 w-4" strokeWidth={2.4} />
                            </span>
                          </div>
                        )}
                      </div>

                      <button
                        type="button"
                        onClick={searchByPackage}
                        className="grid h-[48px] w-full place-items-center rounded-[12px] bg-[#ff6a2b] text-white transition hover:bg-[#ff814d] sm:w-[52px]"
                        aria-label="Search packages"
                      >
                        <Search className="h-5 w-5" strokeWidth={2.4} />
                      </button>
                    </div>

                    <p className="max-w-3xl text-[13px] leading-relaxed text-[#7a8790]">
                      Choose the type of cruise tour you desire. No matter who you are, we offer a
                      cruise that suits you. Select from the list below, then search matching
                      packages.
                    </p>

                    <div className="dest-scroll flex gap-2.5 overflow-x-auto px-0.5 py-1 [scroll-snap-type:x_mandatory] [-webkit-overflow-scrolling:touch]">
                      {typeOptions.map((item) => {
                        const selected = packageTypes.includes(item.name);
                        return (
                          <button
                            key={item.key}
                            type="button"
                            onClick={() => togglePackageType(item.name)}
                            className="relative h-[78px] w-[132px] shrink-0 overflow-hidden rounded-[10px] text-left transition [scroll-snap-align:start] sm:h-[88px] sm:w-[148px]"
                          >
                            <AiImage
                              src={
                                item.image ||
                                aiImage(item.prompt, {
                                  width: 640,
                                  height: 420,
                                  seed: item.seed,
                                })
                              }
                              alt={item.name}
                              className="h-full w-full"
                            />
                            <div className="absolute inset-0 bg-gradient-to-t from-black/65 via-black/10 to-transparent" />
                            {selected ? (
                              <span
                                aria-hidden
                                className="pointer-events-none absolute inset-[2px] rounded-[8px] border-2 border-[#ff6a2b]"
                              />
                            ) : null}
                            <span className="absolute bottom-2 left-2 rounded-md bg-black/55 px-2 py-0.5 text-[11px] font-semibold text-white backdrop-blur-sm">
                              {item.name}
                            </span>
                            {selected && (
                              <span className="absolute top-2 right-2 rounded-full bg-[#ff6a2b] px-1.5 py-0.5 text-[9px] font-bold text-white">
                                Selected
                              </span>
                            )}
                          </button>
                        );
                      })}
                    </div>
                  </div>
                )}

                {tab === "search" && (
                  <div className="relative space-y-3">
                    <div className="grid gap-2.5 md:grid-cols-[1fr_52px]">
                      <input
                        type="search"
                        value={searchQuery}
                        onChange={(e) => {
                          setSearchQuery(e.target.value);
                          setShowSuggestions(true);
                        }}
                        onFocus={() => setShowSuggestions(true)}
                        onKeyDown={(e) => {
                          if (e.key === "Enter") {
                            e.preventDefault();
                            searchByName();
                          }
                        }}
                        placeholder="Search For Cruises, Everything You Want"
                        className="h-[54px] rounded-[12px] bg-[#eef2f3] px-4 text-[14px] font-semibold text-[#1c2b33] outline-none placeholder:font-medium placeholder:text-[#1c2b33]/75"
                      />
                      <button
                        type="button"
                        onClick={searchByName}
                        className="grid h-[54px] w-full place-items-center rounded-[12px] bg-[#ff6a2b] text-white transition hover:bg-[#ff814d] md:w-[52px]"
                        aria-label="Search cruises"
                      >
                        <Search className="h-5 w-5" strokeWidth={2.4} />
                      </button>
                    </div>

                    {showSuggestions && (
                      <div className="rounded-[14px] border border-[#e6ecef] bg-white p-3 shadow-[0_12px_40px_rgba(0,0,0,0.12)] sm:p-4">
                        <div className="mb-3 flex items-center justify-between">
                          <h3 className="text-[15px] font-bold text-[#1c2b33]">Suggestion</h3>
                          <button
                            type="button"
                            onClick={() => setShowSuggestions(false)}
                            className="grid h-7 w-7 place-items-center rounded-full text-[#8a969c] hover:bg-[#eef2f3] hover:text-[#1c2b33]"
                            aria-label="Close suggestions"
                          >
                            <X className="h-4 w-4" strokeWidth={2.2} />
                          </button>
                        </div>

                        {searchSuggestions.length === 0 ? (
                          <p className="py-6 text-center text-sm text-[#8a969c]">No cruises found</p>
                        ) : (
                          <div className="grid gap-2.5 sm:grid-cols-2">
                            {searchSuggestions.map((cruise) => (
                              <SearchSuggestionCard key={cruise.id} cruise={cruise} />
                            ))}
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

function SearchSuggestionCard({ cruise }: { cruise: Cruise }) {
  return (
    <a
      href={`/cruise-tours/${cruiseSlug(cruise.name)}`}
      className="flex overflow-hidden rounded-[12px] border border-[#e6ecef] bg-white transition hover:border-[#ff6a2b]/40 hover:shadow-sm"
    >
      <div className="relative h-[88px] w-[96px] shrink-0 sm:h-[96px] sm:w-[108px]">
        <AiImage
          src={cruiseImage(cruise)}
          alt={cruise.name}
          className="h-full w-full"
        />
      </div>
      <div className="flex min-w-0 flex-1 flex-col justify-center gap-1 p-2.5 sm:p-3">
        <h4 className="line-clamp-1 text-[13px] font-bold text-[#1c2b33] sm:text-[14px]">
          {cruise.name}
        </h4>
        <p className="flex items-center gap-1 text-[12px] text-[#7a8790]">
          <MapPin className="h-3.5 w-3.5 text-[#1c2b33]" fill="currentColor" strokeWidth={0} />
          <span className="truncate">{cruise.bay}</span>
        </p>
        <p className="text-[12px]">
          {cruise.price == null ? (
            <span className="font-bold text-[#ff6a2b]">Price updating!</span>
          ) : (
            <>
              <span className="text-[#7a8790]">From </span>
              <span className="font-bold text-[#ff6a2b]">${cruise.price}</span>{" "}
              <span className="text-[11px] text-[#9aa6ad]">USD per person</span>
            </>
          )}
        </p>
      </div>
    </a>
  );
}
