import { db } from "@/lib/db"
import { notFound } from "next/navigation"
import Link from "next/link"
import { Badge } from "@/components/ui/badge"
import { Select } from "@/components/ui/select"
import { Button } from "@/components/ui/button"
import { formatPrice } from "@/lib/utils"
import { updateOrderStatus } from "../actions"

export const metadata = { title: "Admin — Détail commande" }

const STATUS_LABEL: Record<string, string> = {
  PENDING: "En attente",
  PAID: "Payée",
  SHIPPED: "Expédiée",
  DELIVERED: "Livrée",
  CANCELLED: "Annulée",
}

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null && !Array.isArray(value)
}

export default async function AdminOrderDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params
  const order = await db.order.findUnique({
    where: { id },
    include: { user: true, items: { include: { product: true } } },
  })

  if (!order) notFound()

  const updateStatus = updateOrderStatus.bind(null, order.id)
  const address = isRecord(order.shippingAddress) ? order.shippingAddress : null
  const addressEntries = address
    ? Object.entries(address).filter(([, v]) => v !== null && v !== undefined && v !== "")
    : []

  return (
    <div>
      <Link
        href="/admin/orders"
        className="font-mono text-xs uppercase tracking-widest text-[var(--text-secondary)] hover:text-[var(--text)] transition-colors"
      >
        ← Commandes
      </Link>

      <div className="flex items-center justify-between mt-4 mb-8">
        <h1 className="text-2xl font-heading font-bold uppercase tracking-tight text-[var(--text)]">
          Commande #{order.id.slice(-8).toUpperCase()}
        </h1>
        <Badge variant="outline">{STATUS_LABEL[order.status]}</Badge>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <div className="lg:col-span-2 space-y-8">
          <div className="border border-[var(--border)] bg-[var(--surface)]">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-[var(--border)]">
                  {["Produit", "Taille", "Édition", "Qté", "Prix"].map((h) => (
                    <th
                      key={h}
                      className="text-left px-4 py-3 font-mono text-xs uppercase tracking-widest text-[var(--text-muted)]"
                    >
                      {h}
                    </th>
                  ))}
                </tr>
              </thead>
              <tbody className="divide-y divide-[var(--border)]">
                {order.items.map((item) => (
                  <tr key={item.id}>
                    <td className="px-4 py-4 text-[var(--text)]">{item.product.name}</td>
                    <td className="px-4 py-4 font-mono text-[var(--text-secondary)]">{item.size}</td>
                    <td className="px-4 py-4 font-mono text-[var(--text-secondary)]">
                      {item.editionNumber ? `#${item.editionNumber}` : "—"}
                    </td>
                    <td className="px-4 py-4 font-mono text-[var(--text-secondary)]">{item.quantity}</td>
                    <td className="px-4 py-4 font-mono text-[var(--text)]">{formatPrice(item.price)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
            <div className="flex justify-end px-4 py-4 border-t border-[var(--border)]">
              <p className="font-mono text-sm font-bold text-[var(--text)]">
                Total : {formatPrice(order.total)}
              </p>
            </div>
          </div>

          {addressEntries.length > 0 && (
            <div className="border border-[var(--border)] bg-[var(--surface)] p-6">
              <p className="font-mono text-xs uppercase tracking-widest text-[var(--text-muted)] mb-4">
                Adresse de livraison
              </p>
              <dl className="space-y-1 text-sm">
                {addressEntries.map(([k, v]) => (
                  <div key={k} className="flex gap-2">
                    <dt className="text-[var(--text-muted)] capitalize">{k} :</dt>
                    <dd className="text-[var(--text)]">{String(v)}</dd>
                  </div>
                ))}
              </dl>
            </div>
          )}
        </div>

        <div className="space-y-8">
          <div className="border border-[var(--border)] bg-[var(--surface)] p-6">
            <p className="font-mono text-xs uppercase tracking-widest text-[var(--text-muted)] mb-4">
              Client
            </p>
            <p className="text-sm text-[var(--text)]">{order.user.name ?? "—"}</p>
            <p className="text-sm text-[var(--text-secondary)]">{order.user.email}</p>
            <p className="font-mono text-xs text-[var(--text-muted)] mt-2">
              Commande du {new Date(order.createdAt).toLocaleDateString("fr-BE")}
            </p>
          </div>

          <div className="border border-[var(--border)] bg-[var(--surface)] p-6">
            <p className="font-mono text-xs uppercase tracking-widest text-[var(--text-muted)] mb-4">
              Statut
            </p>
            <form action={updateStatus} className="flex flex-col gap-3">
              <Select name="status" defaultValue={order.status}>
                <option value="PENDING">En attente</option>
                <option value="PAID">Payée</option>
                <option value="SHIPPED">Expédiée</option>
                <option value="DELIVERED">Livrée</option>
                <option value="CANCELLED">Annulée</option>
              </Select>
              <Button type="submit" size="sm">
                Mettre à jour
              </Button>
            </form>
          </div>
        </div>
      </div>
    </div>
  )
}
