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

import { DeleteTripDialog } from "@/components/app/DeleteTripDialog";
import { ListPage, type QuickFilter } from "@/components/app/ListPage";
import { formatDate } from "@/components/app/Primitives";
import { StatusPill } from "@/components/app/StatusPill";
import type { TableColumn } from "@/components/table/DataTable";
import { Button } from "@/components/ui/button";
import { useTrips, type Trip } from "@/features/trips/api";
import { destinationImage } from "@/lib/images";

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

/** Whole days between today and an ISO date — negative once the date has passed. */
const daysUntil = (iso: string) => {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  const target = new Date(`${iso}T00:00:00`);
  return Math.round((target.getTime() - today.getTime()) / 86_400_000);
};

/** "Needs attention" from the original design is deliberately not here — it needs a readiness
 * score from Payments/Documents/Bookings data that doesn't exist yet (see the Trips plan's
 * explicitly-deferred list). Everything else that only needs a Trip's own fields is included. */
const QUICK_FILTERS: QuickFilter<Trip>[] = [
  { key: "all", label: "All", test: () => true },
  { key: "draft", label: "Draft", test: (t) => t.displayStatus === "draft" },
  { key: "upcoming", label: "Upcoming", test: (t) => t.displayStatus === "upcoming" },
  {
    key: "week",
    label: "Departing this week",
    test: (t) => t.displayStatus === "upcoming" && daysUntil(t.departureDate) <= 7,
  },
  {
    key: "month",
    label: "Departing this month",
    test: (t) => t.displayStatus === "upcoming" && daysUntil(t.departureDate) <= 31,
  },
  { key: "active", label: "Ongoing", test: (t) => t.displayStatus === "active" },
  { key: "completed", label: "Completed", test: (t) => t.displayStatus === "completed" },
];

export const Route = createFileRoute("/trips/")({
  head: () => ({
    meta: [
      { title: "Trips | KareVoyage Operations" },
      {
        name: "description",
        content: "Scheduled departures — guests, tour manager, hotel, and status per trip.",
      },
    ],
  }),
  component: TripsPage,
});

function TripsPage() {
  const navigate = useNavigate();
  const [deleteTarget, setDeleteTarget] = useState<Trip | undefined>(undefined);
  const { data, isLoading } = useTrips({ limit: 100 });
  const trips = data?.rows ?? [];

  const columns: TableColumn<Trip>[] = [
    {
      key: "trip",
      header: "Trip",
      sortValue: (t) => t.departureDate,
      cell: (t) => (
        <div className="flex items-center gap-3">
          <img
            src={destinationImage(t.destination)}
            alt=""
            loading="lazy"
            width={64}
            height={64}
            className="h-10 w-14 shrink-0 rounded-md object-cover"
          />
          <div className="min-w-0">
            <p className="truncate font-medium">{t.title || t.tourTitle}</p>
            <p className="truncate text-xs text-muted-foreground">
              {t.title ? `${t.tourTitle} · ` : ""}
              {t.code} · {t.destination}
            </p>
          </div>
        </div>
      ),
    },
    {
      key: "dates",
      header: "Departure → Return",
      sortValue: (t) => t.departureDate,
      cell: (t) => `${formatDate(t.departureDate)} → ${formatDate(t.returnDate)}`,
    },
    {
      key: "maxGroupSize",
      header: "Max Group Size",
      align: "right",
      sortValue: (t) => t.maxGroupSize ?? 0,
      cell: (t) => t.maxGroupSize ?? "—",
    },
    {
      key: "tourManager",
      header: "Tour Manager",
      responsive: "hidden lg:table-cell",
      cell: (t) => t.tourManagerName ?? "—",
    },
    {
      key: "status",
      header: "Status",
      sortValue: (t) => t.displayStatus,
      cell: (t) => <StatusPill value={titleCase(t.displayStatus)} />,
    },
  ];

  return (
    <>
      <ListPage
        title="Trips"
        description="Scheduled departures being run operationally, one per tour departure date."
        countLabel={(n) => (isLoading ? "Loading…" : `${n} trips`)}
        searchPlaceholder="Search trips, tours, destinations…"
        actions={<Button onClick={() => navigate({ to: "/trips/new" })}>Create trip</Button>}
        rows={trips}
        columns={columns}
        getId={(t) => t.id}
        searchText={(t) =>
          `${t.code} ${t.title ?? ""} ${t.tourTitle} ${t.destination} ${t.tourManagerName ?? ""}`
        }
        quickFilters={QUICK_FILTERS}
        filters={[
          { key: "status", label: "Status", get: (t) => t.displayStatus },
          { key: "tourTitle", label: "Tour", get: (t) => t.tourTitle },
        ]}
        onRowClick={(t) => navigate({ to: "/trips/$id", params: { id: t.id } })}
        rowActions={[
          {
            label: "Open trip",
            onSelect: (t) => navigate({ to: "/trips/$id", params: { id: t.id } }),
          },
          {
            label: "Edit trip",
            onSelect: (t) => navigate({ to: "/trips/edit/$id", params: { id: t.id } }),
          },
          {
            // Confirmed in a dialog that first checks for live bookings, so triaging from the list
            // cannot delete a departure people have paid for.
            label: "Delete trip",
            destructive: true,
            onSelect: (t) => setDeleteTarget(t),
          },
        ]}
        emptyTitle={isLoading ? "Loading trips…" : "No trips found"}
        emptyMessage={
          isLoading
            ? "Fetching scheduled departures from the server."
            : "Create a trip to start operationally tracking a tour's departure."
        }
      />

      <DeleteTripDialog
        trip={deleteTarget}
        open={!!deleteTarget}
        onOpenChange={(o) => !o && setDeleteTarget(undefined)}
        onShowBookings={(t) => navigate({ to: "/trips/$id", params: { id: t.id } })}
      />
    </>
  );
}
