import { createFileRoute, useNavigate } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { Loader2, RefreshCcw } from "lucide-react";
import { supabase } from "@/integrations/supabase/client";
import { listOrders } from "@/lib/orders.functions";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent } from "@/components/ui/card";
import { SiteHeader } from "@/components/site-header";
import { SiteFooter } from "@/components/site-footer";

export const Route = createFileRoute("/_authenticated/orders")({
  head: () => ({
    meta: [
      { title: "Orders — Phoenix Clarity Owner Console" },
      {
        name: "description",
        content: "Every PayPal order received, with amount, payer details and payment status.",
      },
      { property: "og:title", content: "Orders — Phoenix Clarity Owner Console" },
      { property: "og:description", content: "Every PayPal order received, with payment status." },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary" },
      { name: "robots", content: "noindex" },
    ],
  }),
  component: OrdersPage,
  errorComponent: ({ error }) => (
    <div className="mx-auto max-w-2xl px-5 py-24 text-center">
      <h1 className="text-2xl font-bold">Couldn&apos;t load orders</h1>
      <p className="mt-3 text-sm text-muted-foreground">{error.message}</p>
    </div>
  ),
  notFoundComponent: () => <div className="p-10 text-center">Page not found</div>,
});

const money = (v: number, c: string) =>
  new Intl.NumberFormat("en-US", { style: "currency", currency: c || "USD" }).format(v);

function OrdersPage() {
  const navigate = useNavigate();
  const fetchOrders = useServerFn(listOrders);
  const { data, isLoading, error, refetch, isFetching } = useQuery({
    queryKey: ["orders"],
    queryFn: () => fetchOrders(),
  });

  const orders = data ?? [];
  const paid = orders.filter((o) => o.status === "COMPLETED");
  const revenue = paid.reduce((sum, o) => sum + Number(o.amount), 0);

  return (
    <div className="flex min-h-dvh flex-col">
      <SiteHeader />
      <main className="mx-auto w-full max-w-5xl flex-1 px-5 py-12">
        <div className="flex flex-wrap items-end justify-between gap-4">
          <div>
            <h1 className="text-3xl font-bold">Orders</h1>
            <p className="mt-2 text-sm text-muted-foreground">
              Every checkout captured on this site, verified server-side with PayPal.
            </p>
          </div>
          <div className="flex gap-2">
            <Button variant="heroOutline" size="sm" onClick={() => refetch()} disabled={isFetching}>
              <RefreshCcw className="mr-2 size-4" /> Refresh
            </Button>
            <Button
              variant="ghost"
              size="sm"
              onClick={async () => {
                await supabase.auth.signOut();
                navigate({ to: "/auth" });
              }}
            >
              Sign out
            </Button>
          </div>
        </div>

        <div className="mt-8 grid gap-4 sm:grid-cols-3">
          <Card className="surface-panel">
            <CardContent className="pt-6">
              <p className="text-sm text-muted-foreground">Paid orders</p>
              <p className="mt-1 text-3xl font-bold">{paid.length}</p>
            </CardContent>
          </Card>
          <Card className="surface-panel">
            <CardContent className="pt-6">
              <p className="text-sm text-muted-foreground">Revenue captured</p>
              <p className="mt-1 text-3xl font-bold">{money(revenue, "USD")}</p>
            </CardContent>
          </Card>
          <Card className="surface-panel">
            <CardContent className="pt-6">
              <p className="text-sm text-muted-foreground">All records</p>
              <p className="mt-1 text-3xl font-bold">{orders.length}</p>
            </CardContent>
          </Card>
        </div>

        <h2 className="mt-10 text-xl font-semibold">Order history</h2>

        {isLoading ? (
          <div className="flex items-center gap-2 py-10 text-sm text-muted-foreground">
            <Loader2 className="size-4 animate-spin text-primary" /> Loading orders…
          </div>
        ) : error ? (
          <p className="py-8 text-sm text-destructive">
            {(error as Error).message} — your account may not have admin access yet.
          </p>
        ) : orders.length === 0 ? (
          <p className="py-8 text-sm text-muted-foreground">
            No orders recorded yet. Payments taken before this page existed live only in your
            PayPal account.
          </p>
        ) : (
          <div className="mt-4 overflow-x-auto rounded-xl border border-border">
            <table className="w-full text-sm">
              <thead className="bg-card/60 text-left text-xs uppercase tracking-wide text-muted-foreground">
                <tr>
                  <th className="px-4 py-3">Date</th>
                  <th className="px-4 py-3">Package</th>
                  <th className="px-4 py-3">Customer</th>
                  <th className="px-4 py-3">Amount</th>
                  <th className="px-4 py-3">Status</th>
                  <th className="px-4 py-3">PayPal ID</th>
                </tr>
              </thead>
              <tbody>
                {orders.map((o) => (
                  <tr key={o.id} className="border-t border-border/60">
                    <td className="whitespace-nowrap px-4 py-3 text-muted-foreground">
                      {new Date(o.created_at).toLocaleString()}
                    </td>
                    <td className="px-4 py-3">{o.package_name}</td>
                    <td className="px-4 py-3">
                      <div>{o.payer_name ?? "—"}</div>
                      <div className="text-xs text-muted-foreground">{o.payer_email ?? ""}</div>
                    </td>
                    <td className="whitespace-nowrap px-4 py-3 font-medium">
                      {money(Number(o.amount), o.currency)}
                    </td>
                    <td className="px-4 py-3">
                      <Badge variant={o.status === "COMPLETED" ? "default" : "secondary"}>
                        {o.status}
                      </Badge>
                    </td>
                    <td className="px-4 py-3 font-mono text-xs text-muted-foreground">
                      {o.paypal_order_id}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </main>
      <SiteFooter />
    </div>
  );
}
