"use client";

import { Suspense, useEffect, useMemo, useState } from "react";

import Link from "next/link";
import { notFound, useParams, useSearchParams } from "next/navigation";

import { Anchor, Calendar, MapPin, Ship, Sparkles, Tag } from "lucide-react";

import { CABIN_CATEGORIES, isSailingBookable } from "@/components/admin/cruise-admin-constants";
import { DeckPlanViewer } from "@/components/cruise/deck-plan-viewer";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Separator } from "@/components/ui/separator";
import { getAuthUser } from "@/lib/auth";
import {
  getAddOnsForSailing,
  getBrandById,
  getCabinsBySailing,
  getDeckPlansForSailing,
  getSailingBySlug,
} from "@/lib/cruise-store";
import { formatCurrency } from "@/lib/utils";
import type { AddOn, Sailing } from "@/types/cruise";

function formatDate(date: string) {
  return new Date(`${date}T12:00:00`).toLocaleDateString("en-US", {
    weekday: "short",
    month: "long",
    day: "numeric",
    year: "numeric",
  });
}

export default function EventLandingPage() {
  return (
    <Suspense fallback={<div className="flex min-h-[40vh] items-center justify-center text-muted-foreground text-sm">Loading…</div>}>
      <EventLandingContent />
    </Suspense>
  );
}

function EventLandingContent() {
  const params = useParams<{ slug: string }>();
  const searchParams = useSearchParams();
  const [sailing, setSailing] = useState<Sailing | null | undefined>(undefined);
  const [addOns, setAddOns] = useState<AddOn[]>([]);
  const [isAdminPreview, setIsAdminPreview] = useState(false);

  useEffect(() => {
    const found = getSailingBySlug(params.slug);
    setSailing(found ?? null);
    if (found) {
      setAddOns(getAddOnsForSailing(found.id));
    }
  }, [params.slug]);

  useEffect(() => {
    const preview = searchParams.get("preview") === "1";
    const user = getAuthUser();
    setIsAdminPreview(preview && !!user && user.role !== "client");
  }, [searchParams]);

  const brand = sailing ? getBrandById(sailing.brandId) : undefined;
  const deckPlans = sailing ? getDeckPlansForSailing(sailing.id) : [];
  const cabins = sailing ? getCabinsBySailing(sailing.id) : [];

  const catalog = useMemo(() => {
    return CABIN_CATEGORIES.map((category) => {
      const inCategory = cabins.filter((c) => c.category === category);
      const available = inCategory.filter((c) => c.status === "available").length;
      return { category, total: inCategory.length, available };
    }).filter((row) => row.total > 0);
  }, [cabins]);

  if (sailing === undefined) {
    return <div className="flex min-h-[40vh] items-center justify-center text-muted-foreground text-sm">Loading…</div>;
  }

  if (!sailing) {
    notFound();
  }

  if (!isSailingBookable(sailing.status) && !isAdminPreview) {
    return (
      <div className="mx-auto max-w-lg px-4 py-16 text-center">
        <h1 className="font-semibold text-2xl">{sailing.name}</h1>
        <p className="mt-3 text-muted-foreground text-sm">
          {sailing.status === "draft"
            ? "This event is not published yet. Check back soon."
            : "This event is no longer available for booking."}
        </p>
        <Button asChild className="mt-6">
          <Link href="/events">Browse published events</Link>
        </Button>
      </div>
    );
  }

  const gallery = sailing.galleryImages ?? [];
  const heroImage = sailing.heroImageUrl ?? gallery[0];
  const accent = brand?.primaryColor ?? "#6366f1";
  const isDraftPreview = isAdminPreview && sailing.status === "draft";

  return (
    <div className="min-h-screen bg-background">
      {isDraftPreview && (
        <div className="border-amber-500/30 border-b bg-amber-50 px-4 py-2 text-center text-amber-900 text-sm dark:bg-amber-950/40 dark:text-amber-100">
          Draft preview — not visible to guests until published.
        </div>
      )}
      {/* Hero banner */}
      <section
        className="relative overflow-hidden border-b"
        style={{ height: "clamp(22rem, 52vh, 36rem)" }}
      >
        {heroImage ? (
          // eslint-disable-next-line @next/next/no-img-element
          <img
            src={heroImage}
            alt=""
            className="absolute inset-0 size-full object-cover object-[center_35%]"
          />
        ) : (
          <div className="absolute inset-0 bg-gradient-to-br from-slate-800 to-slate-950" />
        )}
        <div className="absolute inset-0 bg-gradient-to-t from-black/90 via-black/50 to-black/25" />
        <div className="relative mx-auto flex h-full max-w-6xl flex-col justify-end px-4 py-10 sm:py-14 text-white">
          {brand && (
            <Badge
              variant="outline"
              className="mb-4 w-fit border-white/40 bg-black/30 text-white backdrop-blur-sm"
            >
              {brand.name}
            </Badge>
          )}
          <h1 className="max-w-3xl font-bold text-4xl tracking-tight sm:text-5xl">{sailing.heroTitle}</h1>
          <p className="mt-4 max-w-2xl text-lg text-white/90">{sailing.heroSubtitle}</p>
          <div className="mt-6 flex flex-wrap gap-4 text-sm text-white/85">
            <span className="inline-flex items-center gap-2">
              <Ship className="size-4" style={{ color: accent }} />
              {sailing.ship}
            </span>
            <span className="inline-flex items-center gap-2">
              <Calendar className="size-4" style={{ color: accent }} />
              {formatDate(sailing.departureDate)} – {formatDate(sailing.returnDate)}
            </span>
            <span className="inline-flex items-center gap-2">
              <MapPin className="size-4" style={{ color: accent }} />
              {sailing.departurePort}
            </span>
          </div>
          <div className="mt-8 flex flex-wrap gap-3">
            {isDraftPreview ? (
              <Button size="lg" disabled style={{ backgroundColor: accent }}>
                Book now — {formatCurrency(sailing.basePrice)}
              </Button>
            ) : (
              <Button asChild size="lg" style={{ backgroundColor: accent }}>
                <Link href={`/book/${sailing.id}`}>Book now — {formatCurrency(sailing.basePrice)}</Link>
              </Button>
            )}
            <Button asChild variant="outline" size="lg" className="border-white/40 bg-black/20 text-white hover:bg-black/40">
              <Link href="/events">All events</Link>
            </Button>
          </div>
        </div>
      </section>

      {/* Gallery + page content */}
      <div className="mx-auto max-w-6xl px-4 py-6">
        {gallery.length > 0 && (
          <section className="mb-8">
            <div className="mb-4 flex items-center justify-between gap-3">
              <h2 className="font-semibold text-xl">Event gallery</h2>
              <p className="text-muted-foreground text-sm">{gallery.length} photos</p>
            </div>
            <div className="grid grid-cols-2 gap-2 sm:gap-3 md:h-72 md:grid-cols-4 md:grid-rows-2 lg:h-80">
              {gallery.map((url, i) => (
                <div
                  key={`${url}-${i}`}
                  className={`aspect-[4/3] overflow-hidden rounded-xl bg-muted shadow-sm md:aspect-auto md:h-full ${
                    i === 0 ? "md:col-span-2 md:row-span-2" : ""
                  }`}
                >
                  {/* eslint-disable-next-line @next/next/no-img-element */}
                  <img
                    src={url}
                    alt={`Event photo ${i + 1}`}
                    className="size-full object-cover transition-transform duration-300 hover:scale-[1.02]"
                  />
                </div>
              ))}
            </div>
          </section>
        )}

        {sailing.description && (
          <section className="mb-8">
            <h2 className="mb-3 font-semibold text-2xl">About this event</h2>
            <p className="max-w-3xl text-muted-foreground leading-relaxed">{sailing.description}</p>
          </section>
        )}

        <div className="space-y-10">
        {/* Offers */}
        {(sailing.offers ?? []).length > 0 && (
          <section>
            <div className="mb-6 flex items-center gap-2">
              <Tag className="size-5 text-primary" />
              <h2 className="font-semibold text-2xl">Offers & packages</h2>
            </div>
            <div className="grid gap-4 sm:grid-cols-2">
              {(sailing.offers ?? []).map((offer) => (
                <Card key={offer.id} className="overflow-hidden border-l-4" style={{ borderLeftColor: accent }}>
                  <CardHeader className="pb-2">
                    <div className="flex items-start justify-between gap-2">
                      <CardTitle className="text-base">{offer.title}</CardTitle>
                      {offer.badge && (
                        <Badge variant="secondary" style={{ backgroundColor: `${accent}22`, color: accent }}>
                          {offer.badge}
                        </Badge>
                      )}
                    </div>
                  </CardHeader>
                  <CardContent>
                    <p className="mb-3 text-muted-foreground text-sm">{offer.description}</p>
                    {offer.priceLabel && <p className="font-semibold">{offer.priceLabel}</p>}
                  </CardContent>
                </Card>
              ))}
            </div>
          </section>
        )}

        {/* Cabin catalog */}
        {sailing.publicShowCatalog !== false && catalog.length > 0 && (
          <section>
            <h2 className="mb-6 font-semibold text-2xl">Cabin catalog</h2>
            <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
              {catalog.map((row) => (
                <Card key={row.category}>
                  <CardHeader className="pb-2">
                    <CardTitle className="text-base">{row.category}</CardTitle>
                    <CardDescription>{row.available} of {row.total} available</CardDescription>
                  </CardHeader>
                  <CardContent>
                    <p className="font-bold text-xl">{formatCurrency(sailing.basePrice)}</p>
                    <p className="text-muted-foreground text-xs">from · per person</p>
                  </CardContent>
                </Card>
              ))}
            </div>
          </section>
        )}

        <Separator />

        {/* Itinerary */}
        <section>
          <h2 className="mb-6 font-semibold text-2xl">Itinerary</h2>
          <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
            {sailing.itinerary.map((day) => (
              <Card key={day.day}>
                <CardHeader className="pb-2">
                  <CardTitle className="flex items-center gap-2 text-base">
                    <span
                      className="flex size-7 items-center justify-center rounded-full font-semibold text-xs text-white"
                      style={{ backgroundColor: accent }}
                    >
                      {day.day}
                    </span>
                    {day.title}
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <p className="text-muted-foreground text-sm">{day.description}</p>
                </CardContent>
              </Card>
            ))}
          </div>
        </section>

        <Separator />

        {/* Pricing */}
        <section>
          <h2 className="mb-6 font-semibold text-2xl">Pricing</h2>
          <div className="grid gap-4 sm:grid-cols-3">
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-base">Starting price</CardTitle>
              </CardHeader>
              <CardContent>
                <p className="font-bold text-2xl">{formatCurrency(sailing.basePrice)}</p>
                <p className="text-muted-foreground text-sm">per person, double occupancy</p>
              </CardContent>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-base">Deposit</CardTitle>
              </CardHeader>
              <CardContent>
                <p className="font-bold text-2xl">{formatCurrency(sailing.depositAmount)}</p>
                <p className="text-muted-foreground text-sm">due at booking</p>
              </CardContent>
            </Card>
            <Card>
              <CardHeader className="pb-2">
                <CardTitle className="text-base">Balance due</CardTitle>
              </CardHeader>
              <CardContent>
                <p className="font-bold text-2xl">{formatDate(sailing.balanceDueDate)}</p>
                <p className="text-muted-foreground text-sm">
                  cabin selection upgrade: {formatCurrency(sailing.cabinSelectionUpgradeFee)}
                </p>
              </CardContent>
            </Card>
          </div>
        </section>

        {/* Add-ons */}
        {addOns.length > 0 && (
          <>
            <Separator />
            <section>
              <div className="mb-6 flex items-center gap-2">
                <Sparkles className="size-5 text-primary" />
                <h2 className="font-semibold text-2xl">Add-ons & extras</h2>
              </div>
              <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
                {addOns.map((addOn) => (
                  <Card key={addOn.id}>
                    <CardHeader className="pb-2">
                      <CardTitle className="text-base">{addOn.name}</CardTitle>
                    </CardHeader>
                    <CardContent>
                      <p className="mb-2 text-muted-foreground text-sm">{addOn.description}</p>
                      <p className="font-semibold">{formatCurrency(addOn.price)}</p>
                    </CardContent>
                  </Card>
                ))}
              </div>
            </section>
          </>
        )}

        {/* Deck plans */}
        {sailing.publicShowDeckPlans !== false && deckPlans.length > 0 && (
          <>
            <Separator />
            <section>
              <div className="mb-6">
                <div className="flex items-center gap-2">
                  <Anchor className="size-5 text-primary" />
                  <h2 className="font-semibold text-2xl">Deck plans</h2>
                </div>
                {sailing.ship && (
                  <p className="mt-1 text-muted-foreground text-sm">{sailing.ship}</p>
                )}
              </div>
              <DeckPlanViewer deckPlans={deckPlans} cabins={cabins} />
            </section>
          </>
        )}

        <div className="flex justify-center pt-2">
          {isDraftPreview ? (
            <Button size="lg" disabled style={{ backgroundColor: accent }}>
              Book now — {formatCurrency(sailing.basePrice)}
            </Button>
          ) : (
            <Button asChild size="lg" style={{ backgroundColor: accent }}>
              <Link href={`/book/${sailing.id}`}>Book now — {formatCurrency(sailing.basePrice)}</Link>
            </Button>
          )}
        </div>
        </div>
      </div>
    </div>
  );
}
