import { notFound, redirect } from "next/navigation";
import { format } from "date-fns";
import { User, Mail, Phone, ShoppingBag, Coins } from "lucide-react";
import { desc, eq, inArray } from "drizzle-orm";
import { db } from "@db/client";
import { events, orders } from "@db/schema";
import { getDashboardUser } from "@/lib/view-as";
import { getMyCustomerById } from "@db/queries/customers";
import type { OrderStatus } from "@/lib/types";
import { formatPrice } from "@/lib/format";
import {
  PageHeader,
  Card,
  StatCard,
  TableShell,
  StatusPill,
  EmptyState,
  type Tone,
} from "@/components/ui";

const STATUS_TONE: Record<OrderStatus, Tone> = {
  pending: "muted",
  paid: "ok",
  cancelled: "danger",
  refunded: "warn",
};

export default async function CustomerDetailPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  const { id } = await params;
  const { user } = await getDashboardUser();
  if (!user) redirect("/login");

  const row = await getMyCustomerById(user.id, id);
  if (!row) notFound();

  const customerOrders = await db
    .select()
    .from(orders)
    .where(eq(orders.customerId, id))
    .orderBy(desc(orders.createdAt));

  const eventIds = Array.from(new Set(customerOrders.map((o) => o.eventId)));
  const eventTitles = eventIds.length
    ? await db.select({ id: events.id, title: events.title }).from(events).where(inArray(events.id, eventIds))
    : [];
  const titleByEvent = new Map(eventTitles.map((e) => [e.id, e.title]));

  return (
    <div className="space-y-8">
      <PageHeader
        icon={User}
        title={row.full_name || row.email}
        description={row.full_name ? row.email : undefined}
      />

      <section className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        <StatCard icon={ShoppingBag} label="Orders" value={row.total_orders.toString()} />
        <StatCard
          icon={Coins}
          label="Total spent"
          value={formatPrice(row.total_spent_cents, "kes")}
          accent="gold"
        />
        <StatCard icon={Mail} label="Email" value={row.email} />
        <StatCard icon={Phone} label="Phone" value={row.phone || "—"} />
      </section>

      <Card>
        <p className="text-sm text-be-muted">
          Customer since {format(new Date(row.created_at), "PP")}.
        </p>
      </Card>

      <section className="space-y-3">
        <h2 className="text-lg font-medium text-be-text">Order history</h2>
        {customerOrders.length === 0 ? (
          <EmptyState
            icon={ShoppingBag}
            title="No orders yet"
            body="Orders placed with this email will appear here once paid."
          />
        ) : (
          <TableShell>
            <thead>
              <tr>
                <th>Event</th>
                <th>When</th>
                <th className="text-right">Amount</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              {customerOrders.map((o) => (
                <tr key={o.id}>
                  <td className="font-medium text-be-text">
                    {titleByEvent.get(o.eventId) ?? "—"}
                  </td>
                  <td className="whitespace-nowrap text-be-muted">
                    {format(o.createdAt, "PPp")}
                  </td>
                  <td className="text-right tabular-nums text-be-text">
                    {formatPrice(o.totalCents, o.currency)}
                  </td>
                  <td>
                    <StatusPill tone={STATUS_TONE[o.status] ?? "muted"}>{o.status}</StatusPill>
                  </td>
                </tr>
              ))}
            </tbody>
          </TableShell>
        )}
      </section>
    </div>
  );
}
