"use client";

import Link from "next/link";
import { useQuery } from "@tanstack/react-query";
import { ArrowUpRight, PackageCheck, TriangleAlert } from "lucide-react";
import { PageHeader } from "@/components/shared/page-header";
import { Pagination } from "@/components/shared/pagination";
import { EmptyState, ErrorState, TableSkeleton } from "@/components/shared/states";
import { OrderStatusBadge } from "@/components/shared/status-badges";
import { Card } from "@/components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { getAwaitingCollection } from "@/services/orders";
import { queryKeys } from "@/lib/query-keys";
import { useUrlState } from "@/lib/use-url-state";
import { useI18n, useT } from "@/i18n";
import { formatDateTime } from "@/lib/format";
import { friendlyErrorMessage } from "@/lib/errors";

/**
 * Wrapped orders nobody can be sent for yet.
 *
 * These sit in ordinary `pending`, which is the point: on the main orders list they are
 * indistinguishable from work a dispatcher could hand out right now, and the only other way to
 * discover the difference is to click Assign and be told 409. Nothing in the system will move
 * them either — they become assignable when a *different* row reaches `delivered`.
 *
 * Oldest first, deliberately the opposite of every other list here: the order blocked longest is
 * the one somebody needs to look at, not the one that arrived most recently.
 */
export default function AwaitingCollectionPage() {
  const t = useT();
  const { locale } = useI18n();

  const [page, setPage] = useUrlState("page", 1, (value) => {
    const n = Number(value);
    return Number.isFinite(n) && n >= 1 ? n : null;
  });

  const { data, isLoading, isError, error, refetch } = useQuery({
    queryKey: queryKeys.orders.awaitingCollection(page),
    queryFn: () => getAwaitingCollection(page),
  });

  const orders = data?.Model ?? [];

  return (
    <div className="space-y-4">
      <PageHeader
        title={t("orders.awaitingCollection.title")}
        subtitle={t("orders.awaitingCollection.subtitle")}
      />

      <Card className="p-4">
        {isLoading ? (
          <TableSkeleton rows={6} cols={5} />
        ) : isError ? (
          <ErrorState message={friendlyErrorMessage(error, t)} onRetry={() => refetch()} />
        ) : orders.length === 0 ? (
          <EmptyState
            title={t("orders.awaitingCollection.empty")}
            description={t("orders.collection.arrivedHint")}
            icon={PackageCheck}
          />
        ) : (
          <>
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>{t("orders.orderNumber")}</TableHead>
                    <TableHead>{t("orders.customer")}</TableHead>
                    <TableHead>{t("orders.legs.collection")}</TableHead>
                    <TableHead>{t("common.createdAt")}</TableHead>
                    <TableHead aria-label={t("common.actions")} />
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {orders.map((order) => {
                    const legs = order.collection_legs ?? [];
                    const failed = legs.find((leg) => leg.status === "delivery_failed");

                    return (
                      <TableRow key={order.uuid}>
                        <TableCell className="font-semibold text-primary">
                          {order.order_number}
                          {order.store?.name ? (
                            <p className="text-xs font-normal text-muted-foreground">
                              {order.store.name}
                            </p>
                          ) : null}
                        </TableCell>

                        <TableCell>
                          <p className="font-medium text-foreground">{order.customer_name}</p>
                          <p className="text-xs text-muted-foreground">{order.dropoff_address}</p>
                        </TableCell>

                        {/*
                          The legs, not the order's own status — the order's status is `pending`
                          on every row here, so printing it would tell the reader nothing. What
                          differs from row to row, and decides what to do about it, is the state
                          of the leg fetching the goods.
                        */}
                        <TableCell>
                          <div className="space-y-1">
                            {legs.map((leg) => (
                              <div key={leg.uuid} className="flex items-center gap-2">
                                <span className="text-xs text-muted-foreground">
                                  {leg.order_number}
                                </span>
                                <OrderStatusBadge status={leg.status} label={leg.status_label} />
                              </div>
                            ))}
                          </div>

                          {/* A failure is not a delay: nobody is bringing these goods. */}
                          {failed ? (
                            <p className="mt-1 flex items-start gap-1 text-xs text-destructive">
                              <TriangleAlert className="mt-0.5 h-3.5 w-3.5 shrink-0" aria-hidden />
                              <span>
                                {failed.failed_reason ?? t("orders.collection.failed")}
                              </span>
                            </p>
                          ) : null}
                        </TableCell>

                        <TableCell className="text-sm text-muted-foreground">
                          {order.created_at ? formatDateTime(order.created_at, locale) : "—"}
                        </TableCell>

                        <TableCell>
                          <Link
                            href={`/orders/${order.uuid}`}
                            className="inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline"
                          >
                            {t("common.view")}
                            <ArrowUpRight className="h-3 w-3" aria-hidden />
                          </Link>
                        </TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>
            </div>

            <Pagination
              page={data?.Page ?? page}
              totalPages={data?.Total ?? 1}
              records={data?.Records ?? orders.length}
              onPageChange={setPage}
            />
          </>
        )}
      </Card>
    </div>
  );
}
