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 type { TableColumn } from "@/components/table/DataTable";
import { Button } from "@/components/ui/button";
import { useDestinations, type Destination } from "@/features/destinations/api";
import { destinationImage } from "@/lib/images";

export const Route = createFileRoute("/destinations/")({
  head: () => ({
    meta: [
      { title: "Destinations | KareVoyage Operations" },
      { name: "description", content: "Destination library with regions, best travel seasons and travel styles." },
      { property: "og:title", content: "Destinations | KareVoyage Operations" },
      { property: "og:description", content: "Curate the destinations KareVoyage sells." },
    ],
  }),
  component: DestinationsPage,
});

function DestinationsPage() {
  const navigate = useNavigate();
  const { data, isLoading } = useDestinations({ limit: 100 });
  const rows = data?.rows ?? [];

  const columns: TableColumn<Destination>[] = [
    {
      key: "destination",
      header: "Destination",
      sortValue: (d) => d.name,
      cell: (d) => (
        <div className="flex items-center gap-3">
          <img
            src={d.heroImageUrl || destinationImage(d.name)}
            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">{d.name}</p>
            <p className="truncate text-xs text-muted-foreground">
              {d.country}
              {d.region ? ` · ${d.region}` : ""}
            </p>
          </div>
        </div>
      ),
    },
    {
      key: "bestTime",
      header: "Best time",
      responsive: "hidden lg:table-cell",
      sortValue: (d) => d.bestTime ?? "",
      cell: (d) => d.bestTime || "—",
    },
    {
      key: "style",
      header: "Travel style",
      responsive: "hidden lg:table-cell",
      sortValue: (d) => d.travelStyle ?? "",
      cell: (d) => d.travelStyle || "—",
    },
    {
      key: "featured",
      header: "Featured",
      cell: (d) => (d.featured ? "Yes" : "—"),
    },
    {
      key: "updated",
      header: "Updated",
      responsive: "hidden lg:table-cell",
      sortValue: (d) => d.updatedAt,
      cell: (d) => formatDate(d.updatedAt),
    },
    {
      key: "status",
      header: "Status",
      sortValue: (d) => (d.isActive ? "active" : "inactive"),
      cell: (d) => <StatusPill value={d.isActive ? "Active" : "Inactive"} />,
    },
  ];

  return (
    <ListPage
      title="Destinations"
      description="The places KareVoyage travels to, and when they are at their best."
      countLabel={(n) => (isLoading ? "Loading…" : `${n} destinations`)}
      searchPlaceholder="Search destinations, countries, regions…"
      actions={<Button onClick={() => navigate({ to: "/destinations/new" })}>Add destination</Button>}
      rows={rows}
      columns={columns}
      getId={(d) => d.id}
      searchText={(d) => `${d.name} ${d.country} ${d.region ?? ""} ${d.travelStyle ?? ""}`}
      filters={[
        { key: "region", label: "Region", get: (d) => d.region ?? "" },
        { key: "style", label: "Travel style", get: (d) => d.travelStyle ?? "" },
        { key: "status", label: "Status", get: (d) => (d.isActive ? "active" : "inactive") },
      ]}
      onRowClick={(d) => navigate({ to: "/destinations/$id", params: { id: d.id } })}
      rowActions={[
        {
          label: "Edit Destination",
          onSelect: (d) => navigate({ to: "/destinations/$id", params: { id: d.id } }),
        },
      ]}
      emptyTitle={isLoading ? "Loading destinations…" : "No destinations"}
      emptyMessage={
        isLoading
          ? "Fetching the destination library from the server."
          : "Add a destination to build tours around it."
      }
    />
  );
}
