import { useState } from "react";
import { createFileRoute, Link, useNavigate } from "@tanstack/react-router";
import { ArrowLeft, Trash2 } from "lucide-react";

import { DeleteTripDialog } from "@/components/app/DeleteTripDialog";
import { Page } from "@/components/app/Page";
import { DetailRow, EmptyState, formatDate, SectionHeading } from "@/components/app/Primitives";
import { StatusPill } from "@/components/app/StatusPill";
import { TripItineraryManager } from "@/components/app/TripItineraryManager";
import { TripManifestPanel } from "@/components/app/TripManifestPanel";
import { TripQuickActions, TripReadinessStrip } from "@/components/app/TripOverviewPanels";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useDropdownOptions } from "@/features/master-types/api";
import { useTour } from "@/features/tours/api";
import { useTrip, type Trip } from "@/features/trips/api";
import { useBreadcrumbLabel } from "@/lib/breadcrumb-label";
import { destinationImage } from "@/lib/images";

export const Route = createFileRoute("/trips/$id")({
  head: () => ({
    meta: [{ title: "Trip | KareVoyage Operations" }],
  }),
  component: TripDetail,
});

/** `displayStatus` is stored/computed lowercase ("draft"/"upcoming"/"active"/...) — capitalized
 * here for display only, same treatment as the Tour detail page's own publishingState. */
const titleCase = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);

/** Resolves a Master Type option value to its label — read-only chip, mirrors the Tour form's
 * own displays. */
function TourAttributeChip({ groupKey, value }: { groupKey: string; value: string | null }) {
  const { data: options } = useDropdownOptions(groupKey);
  if (!value) return null;
  return (
    <span className="rounded-md bg-surface-muted px-1.5 py-0.5 text-xs text-foreground">
      {options?.find((o) => o.value === value)?.label ?? value}
    </span>
  );
}

/** Resolves a tour's `requiredDocuments` (Master Type option values) to their labels, as a chip
 * list — read-only, mirrors the Tour form's own multi-select. */
function RequiredDocumentsValue({ values }: { values: string[] }) {
  const { data: options } = useDropdownOptions("document_type");
  if (values.length === 0) return null;
  return (
    <span className="flex flex-wrap justify-end gap-1">
      {values.map((v) => (
        <span key={v} className="rounded-md bg-surface-muted px-1.5 py-0.5 text-xs text-foreground">
          {options?.find((o) => o.value === v)?.label ?? v}
        </span>
      ))}
    </span>
  );
}

function TripDetail() {
  const { id } = Route.useParams();
  const { data: trip, isLoading, isError } = useTrip(id);

  if (isLoading) {
    return (
      <Page>
        <p className="text-sm text-muted-foreground">Loading trip…</p>
      </Page>
    );
  }

  if (isError || !trip) {
    return (
      <Page>
        <EmptyState
          title="Trip not found"
          message="This trip doesn't exist or may have been removed."
          action={
            <Button asChild>
              <Link to="/trips">Back to trips</Link>
            </Button>
          }
        />
      </Page>
    );
  }

  return <TripDetailView trip={trip} />;
}

type TripTab = "overview" | "guests" | "itinerary";

/**
 * Edit and delete for the whole departure.
 *
 * Delete is deliberately refused by the server while live bookings hang off the trip — removing it
 * would hide their money on every ledger and skip refunds nobody reviewed. Rather than let the
 * operator find that out from an error, the button says so up front and points at the bookings
 * they have to deal with first.
 */
function TripHeaderActions({ trip, onShowBookings }: { trip: Trip; onShowBookings: () => void }) {
  const navigate = useNavigate();
  const [confirming, setConfirming] = useState(false);

  return (
    <>
      <Button size="sm" variant="secondary" asChild>
        <Link to="/trips/edit/$id" params={{ id: trip.id }}>
          Edit trip
        </Link>
      </Button>
      <Button
        size="sm"
        variant="secondary"
        className="gap-1.5 text-destructive hover:bg-destructive/10"
        onClick={() => setConfirming(true)}
      >
        <Trash2 className="h-3.5 w-3.5" /> Delete
      </Button>

      <DeleteTripDialog
        trip={trip}
        open={confirming}
        onOpenChange={setConfirming}
        onShowBookings={onShowBookings}
        onDeleted={() => void navigate({ to: "/trips" })}
      />
    </>
  );
}

function TripDetailView({ trip }: { trip: Trip }) {
  const { data: tour } = useTour(trip.tourId);
  const [tab, setTab] = useState<TripTab>("overview");
  useBreadcrumbLabel(trip.code);

  return (
    <div className="min-h-0 flex-1 overflow-y-auto kv-scroll">
      <div className="relative h-52 w-full overflow-hidden md:h-60">
        <img
          src={destinationImage(trip.destination)}
          alt={`${trip.destination} landscape`}
          width={1024}
          height={640}
          className="h-full w-full object-cover"
        />
        <div className="absolute inset-0 bg-gradient-to-t from-foreground/80 via-foreground/35 to-transparent" />
        <div className="absolute inset-x-0 bottom-0 mx-auto w-full max-w-[1440px] px-5 pb-6 md:px-8">
          <Link
            to="/trips"
            className="mb-3 inline-flex items-center gap-1.5 text-xs text-background/80 hover:text-background"
          >
            <ArrowLeft className="h-3.5 w-3.5" /> All trips
          </Link>
          <div className="flex flex-wrap items-end justify-between gap-4">
            <div>
              <p className="text-[11px] font-semibold uppercase tracking-[0.16em] text-background/70">
                {trip.code} · {trip.destination}
              </p>
              <h1 className="mt-1 text-[32px] leading-tight text-background">
                {trip.title || trip.tourTitle}
              </h1>
              <Link
                to="/tours/$id"
                params={{ id: trip.tourId }}
                className="mt-0.5 inline-block w-fit text-xs text-background/80 hover:text-background hover:underline"
              >
                {trip.tourTitle}
              </Link>
              <p className="mt-2 text-xs text-background/85">
                {formatDate(trip.departureDate)} → {formatDate(trip.returnDate)}
              </p>
            </div>
            <div className="flex flex-wrap items-center gap-2">
              <StatusPill value={titleCase(trip.displayStatus)} className="bg-background/90" />
              <TripHeaderActions trip={trip} onShowBookings={() => setTab("guests")} />
              {/* The single most common job on a departure, so it lives in the header rather than
                  only inside a card further down the page. */}
              <Button size="sm" onClick={() => setTab("guests")}>
                Record payment
              </Button>
            </div>
          </div>
        </div>
      </div>

      <Page className="space-y-8">
        <TripReadinessStrip trip={trip} />

        <Tabs value={tab} onValueChange={(v) => setTab(v as TripTab)}>
          <TabsList className="flex h-auto w-full flex-wrap justify-start gap-1 bg-transparent p-0">
            {[
              { value: "overview", label: "Overview" },
              { value: "guests", label: "Guests & Bookings" },
              { value: "itinerary", label: "Itinerary" },
            ].map((t) => (
              <TabsTrigger
                key={t.value}
                value={t.value}
                className="rounded-lg px-3 py-1.5 text-sm data-[state=active]:bg-primary-soft data-[state=active]:text-accent-foreground data-[state=active]:shadow-none"
              >
                {t.label}
              </TabsTrigger>
            ))}
          </TabsList>

          <TabsContent value="overview" className="mt-6 grid gap-6 lg:grid-cols-3">
            {/* Main column: the reference material. */}
            <div className="space-y-6 lg:col-span-2">
              <div className="grid gap-6 sm:grid-cols-2">
                <div className="rounded-xl border border-border bg-surface p-5">
                  <SectionHeading title="Journey" />
                  <dl className="divide-y divide-border">
                    <DetailRow label="Trip code" value={trip.code} />
                    <DetailRow label="Tour" value={trip.tourTitle} />
                    <DetailRow label="Trip title" value={trip.title} />
                    <DetailRow label="Destination" value={trip.destination} />
                    <DetailRow label="Departure city" value={trip.departureCity} />
                    <DetailRow
                      label="Max group size"
                      value={trip.maxGroupSize ?? tour?.groupSizeMax ?? null}
                    />
                    <DetailRow label="Departure" value={formatDate(trip.departureDate)} />
                    <DetailRow label="Return" value={formatDate(trip.returnDate)} />
                  </dl>
                </div>
                <div className="rounded-xl border border-border bg-surface p-5">
                  <SectionHeading title="Operations" />
                  <dl className="divide-y divide-border">
                    <DetailRow label="Tour manager" value={trip.tourManagerName} />
                    <DetailRow label="Hotel" value={trip.hotelName} />
                    <DetailRow
                      label="Accommodation"
                      value={
                        tour ? (
                          <TourAttributeChip
                            groupKey="accommodation_type"
                            value={tour.accommodationType}
                          />
                        ) : null
                      }
                    />
                    <DetailRow
                      label="Meal plan"
                      value={
                        tour ? (
                          <TourAttributeChip groupKey="meal_plan" value={tour.mealPlan} />
                        ) : null
                      }
                    />
                    <DetailRow
                      label="Transport"
                      value={
                        tour ? (
                          <TourAttributeChip groupKey="transport_type" value={tour.transportType} />
                        ) : null
                      }
                    />
                    <DetailRow
                      label="Document requirements"
                      value={
                        tour ? <RequiredDocumentsValue values={tour.requiredDocuments} /> : null
                      }
                    />
                  </dl>
                </div>
              </div>

              {/* Notes sit full-width under the two cards. As their own column they left a blank
                  white box whenever a trip had no notes, which read as a broken panel. */}
              {trip.notes ? (
                <div className="rounded-xl border border-border bg-surface p-5">
                  <SectionHeading title="Notes" />
                  <p className="whitespace-pre-wrap text-sm text-muted-foreground">{trip.notes}</p>
                </div>
              ) : null}
            </div>

            {/* Action rail: sticky, so the actions stay reachable however far the operator
                scrolls, and visible without scrolling at all. */}
            <aside className="lg:sticky lg:top-4 lg:self-start">
              <TripQuickActions trip={trip} onGoToTab={setTab} />
            </aside>
          </TabsContent>

          <TabsContent value="guests" className="mt-6">
            <TripManifestPanel tripId={trip.id} />
          </TabsContent>

          <TabsContent value="itinerary" className="mt-6">
            <div className="rounded-xl border border-border bg-surface p-5">
              <TripItineraryManager trip={trip} />
            </div>
          </TabsContent>
        </Tabs>
      </Page>
    </div>
  );
}
