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

import { ListPage } from "@/components/app/ListPage";
import { formatDate } from "@/components/app/Primitives";
import { StatusPill } from "@/components/app/StatusPill";
import { TourBookingToggleDialog } from "@/components/app/TourBookingToggleDialog";
import type { TableColumn } from "@/components/table/DataTable";
import { Button } from "@/components/ui/button";
import { useTours, type Tour } from "@/features/tours/api";
import { destinationImage } from "@/lib/images";

export const Route = createFileRoute("/tours/")({
  head: () => ({
    meta: [
      { title: "Tours | KareVoyage Operations" },
      {
        name: "description",
        content:
          "The KareVoyage tour catalogue: destinations, durations, pricing and publishing status.",
      },
      { property: "og:title", content: "Tours | KareVoyage Operations" },
      { property: "og:description", content: "Manage the travel product catalogue." },
    ],
  }),
  component: ToursPage,
});

const formatMoney = (currency: string, amount: string) =>
  `${currency} ${Number(amount).toLocaleString("en-IN", { maximumFractionDigits: 0 })}`;

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

function ToursPage() {
  const navigate = useNavigate();
  const { data, isLoading } = useTours({ limit: 100 });
  const tours = data?.rows ?? [];
  const [bookingToggleTarget, setBookingToggleTarget] = useState<Tour | undefined>(undefined);

  const columns: TableColumn<Tour>[] = [
    {
      key: "tour",
      header: "Tour",
      sortValue: (t) => t.title,
      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}</p>
            <p className="truncate text-xs text-muted-foreground">
              {t.destination}, {t.country}
            </p>
          </div>
        </div>
      ),
    },
    {
      key: "duration",
      header: "Duration",
      align: "right",
      sortValue: (t) => t.durationDays,
      cell: (t) => `${t.durationNights}N / ${t.durationDays}D`,
    },
    {
      key: "price",
      header: "From",
      align: "right",
      sortValue: (t) => Number(t.price),
      cell: (t) => formatMoney(t.currency, t.price),
    },
    {
      key: "publishingState",
      header: "Publishing",
      sortValue: (t) => t.publishingState,
      cell: (t) => <StatusPill value={titleCase(t.publishingState)} />,
    },
    {
      // Paired with the row action that flips it: an operator must be able to see which tours are
      // closed, or a refused booking has no visible explanation.
      key: "bookings",
      header: "Bookings",
      sortValue: (t) => (t.allowBooking ? "open" : "closed"),
      cell: (t) => <StatusPill value={t.allowBooking ? "Open" : "Closed"} />,
    },
    {
      key: "featured",
      header: "Featured",
      responsive: "hidden lg:table-cell",
      cell: (t) => (t.featured ? "Yes" : "—"),
    },
    {
      key: "updated",
      header: "Updated",
      responsive: "hidden lg:table-cell",
      sortValue: (t) => t.updatedAt,
      cell: (t) => formatDate(t.updatedAt),
    },
    {
      key: "status",
      header: "Status",
      sortValue: (t) => (t.isActive ? "active" : "inactive"),
      cell: (t) => <StatusPill value={t.isActive ? "Active" : "Inactive"} />,
    },
  ];

  return (
    <>
      <ListPage
        title="Tours"
        description="The travel products guests can book, with pricing and publishing state."
        countLabel={(n) => (isLoading ? "Loading…" : `${n} tours`)}
        searchPlaceholder="Search tours and destinations…"
        actions={<Button onClick={() => navigate({ to: "/tours/new" })}>Create tour</Button>}
        rows={tours}
        columns={columns}
        getId={(t) => t.id}
        searchText={(t) => `${t.title} ${t.destination} ${t.country} ${t.slug}`}
        filters={[
          { key: "destination", label: "Destination", get: (t) => t.destination },
          { key: "country", label: "Country", get: (t) => t.country },
          { key: "publishingState", label: "Publishing", get: (t) => t.publishingState },
          { key: "tourType", label: "Tour Type", get: (t) => t.tourType },
        ]}
        onRowClick={(t) => navigate({ to: "/tours/$id", params: { id: t.id } })}
        rowActions={[
          {
            label: "Open tour",
            onSelect: (t) => navigate({ to: "/tours/$id", params: { id: t.id } }),
          },
          {
            label: "Edit tour",
            onSelect: (t) => navigate({ to: "/tours/edit/$id", params: { id: t.id } }),
          },
          {
            // Named by consequence, not by the field: "Allow Booking" never told anyone what
            // turning it off actually does.
            label: "Stop taking bookings",
            destructive: true,
            hidden: (t) => !t.allowBooking,
            onSelect: (t) => setBookingToggleTarget(t),
          },
          {
            label: "Start taking bookings",
            hidden: (t) => t.allowBooking,
            onSelect: (t) => setBookingToggleTarget(t),
          },
        ]}
        emptyTitle={isLoading ? "Loading tours…" : "No tours found"}
        emptyMessage={
          isLoading
            ? "Fetching the tour catalogue from the server."
            : "Create a tour to start selling a new journey."
        }
      />

      <TourBookingToggleDialog
        tour={bookingToggleTarget}
        open={!!bookingToggleTarget}
        onOpenChange={(o) => !o && setBookingToggleTarget(undefined)}
      />
    </>
  );
}
