import type { Metadata } from "next";
import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft, ExternalLink, Package, User as UserIcon } from "lucide-react";
import { requireAdmin } from "@/lib/auth/admin-guard";
import { getOrderForAdmin } from "@/lib/store/queries";
import { formatMinor } from "@/lib/store/cart";
import {
  AdminHeading,
  FormSection,
  InputField,
  StatusBadge,
  TextareaField,
  formatAdminDateTime,
} from "@/components/admin";
import { Button } from "@/components/Button";
import { updateOrder } from "../actions";

export const metadata: Metadata = { title: "Manage order" };
export const dynamic = "force-dynamic";

const STATUS_OPTIONS = [
  { value: "pending_invoice", label: "Pending invoice" },
  { value: "invoiced", label: "Invoice sent" },
  { value: "paid", label: "Paid" },
  { value: "shipped", label: "Shipped" },
  { value: "delivered", label: "Delivered" },
  { value: "cancelled", label: "Cancelled" },
];

export default async function AdminStoreOrderPage({
  params,
}: {
  params: Promise<{ id: string }>;
}) {
  await requireAdmin();
  const { id } = await params;
  const data = await getOrderForAdmin(id);
  if (!data) notFound();
  const { order, lines } = data;

  return (
    <>
      <div className="mb-4">
        <Link
          href="/admin/store/orders"
          className="inline-flex items-center gap-1 text-[13px] font-semibold text-[var(--color-slate)] hover:text-[var(--color-blue)]"
        >
          <ArrowLeft className="h-3.5 w-3.5" aria-hidden />
          Back to orders
        </Link>
      </div>
      <AdminHeading
        eyebrow={`Order · ${order.orderNumber}`}
        title={`${order.customerName}`}
        lede={
          <>
            <span>{order.customerEmail}</span>
            <span className="text-[var(--color-slate)]"> · placed </span>
            <span>{formatAdminDateTime(order.createdAt)}</span>
          </>
        }
        actions={
          <StatusBadge
            label={order.status.replace("_", " ")}
            dot
            tone={
              order.status === "paid" || order.status === "delivered"
                ? "success"
                : order.status === "cancelled"
                  ? "danger"
                  : order.status === "shipped"
                    ? "info"
                    : order.status === "invoiced"
                      ? "info"
                      : "warning"
            }
          />
        }
      />

      <div className="grid gap-6 lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
        <div className="flex flex-col gap-6">
          <FormSection
            title="Items"
            description={`${lines.length} line${lines.length === 1 ? "" : "s"} · ${formatMinor(order.totalMinor, order.currency)} total`}
          >
            <ul className="divide-y divide-[var(--color-line)]">
              {lines.map((l) => (
                <li
                  key={l.id}
                  className="flex items-start justify-between gap-3 py-3 text-[14px]"
                >
                  <div className="min-w-0">
                    <div className="font-semibold text-[var(--color-ink)]">
                      {l.productTitle}
                    </div>
                    <div className="text-[12px] text-[var(--color-slate)]">
                      {l.quantity} × {formatMinor(l.unitPriceMinor, order.currency)}
                      {l.productSku && <> · SKU {l.productSku}</>}
                    </div>
                  </div>
                  <div className="font-semibold text-[var(--color-ink)]">
                    {formatMinor(l.lineTotalMinor, order.currency)}
                  </div>
                </li>
              ))}
            </ul>
            <dl className="mt-4 space-y-1.5 border-t border-[var(--color-line)] pt-3 text-[13px]">
              <Row
                label="Subtotal"
                value={formatMinor(order.subtotalMinor, order.currency)}
              />
              <Row
                label="Shipping"
                value={
                  order.shippingMinor === 0
                    ? "Free"
                    : formatMinor(order.shippingMinor, order.currency)
                }
              />
              <Row
                label="Total"
                strong
                value={formatMinor(order.totalMinor, order.currency)}
              />
            </dl>
          </FormSection>

          <FormSection
            title="Fulfilment"
            description="Move the order through its workflow. The customer is emailed automatically when the status changes."
          >
            <form action={updateOrder} className="grid gap-4">
              <input type="hidden" name="id" value={order.id} />
              <div className="flex flex-wrap items-center gap-2">
                <label className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
                  Status
                </label>
                <select
                  name="status"
                  defaultValue={order.status}
                  className="rounded-md border border-[var(--color-line)] bg-white px-3 py-2 text-[14px] focus:border-[var(--color-blue)] focus:outline-none"
                >
                  {STATUS_OPTIONS.map((o) => (
                    <option key={o.value} value={o.value}>
                      {o.label}
                    </option>
                  ))}
                </select>
              </div>
              <div className="grid gap-4 md:grid-cols-2">
                <InputField
                  label="Invoice URL"
                  name="invoiceUrl"
                  type="url"
                  defaultValue={order.invoiceUrl ?? ""}
                  hint="Link sent in the invoiced-status email."
                />
                <InputField
                  label="Tracking URL"
                  name="trackingUrl"
                  type="url"
                  defaultValue={order.trackingUrl ?? ""}
                />
                <InputField
                  label="Tracking number"
                  name="trackingNumber"
                  defaultValue={order.trackingNumber ?? ""}
                />
              </div>
              <TextareaField
                label="Admin notes (private)"
                name="adminNotes"
                rows={3}
                maxLength={2000}
                defaultValue={order.adminNotes}
              />
              <Button type="submit" variant="primary" className="!px-4 !py-2 !text-[13px]">
                Save &amp; notify customer
              </Button>
            </form>
          </FormSection>

          <FormSection title="Timestamps">
            <dl className="grid grid-cols-2 gap-3 text-[12px]">
              <Stamp label="Placed" value={order.createdAt} />
              <Stamp label="Invoiced" value={order.invoicedAt} />
              <Stamp label="Paid" value={order.paidAt} />
              <Stamp label="Shipped" value={order.shippedAt} />
              <Stamp label="Delivered" value={order.deliveredAt} />
              <Stamp label="Cancelled" value={order.cancelledAt} />
            </dl>
          </FormSection>
        </div>

        <aside className="flex flex-col gap-6">
          <FormSection
            title={
              <span className="inline-flex items-center gap-2">
                <UserIcon className="h-4 w-4 text-[var(--color-blue)]" aria-hidden />
                Customer
              </span>
            }
          >
            <div className="space-y-1 text-[13px] text-[var(--color-ink)]">
              <div className="font-semibold">{order.customerName}</div>
              <div>{order.customerEmail}</div>
              {order.customerPhone && <div>{order.customerPhone}</div>}
            </div>
          </FormSection>
          <FormSection
            title={
              <span className="inline-flex items-center gap-2">
                <Package className="h-4 w-4 text-[var(--color-blue)]" aria-hidden />
                Ship to
              </span>
            }
          >
            <div className="text-[13px] leading-relaxed text-[var(--color-ink)]">
              <div className="whitespace-pre-wrap">
                {order.shippingAddress}
              </div>
              <div className="mt-1 font-semibold">{order.shippingCountry}</div>
            </div>
            {order.notes && (
              <div className="mt-3 border-t border-[var(--color-line)] pt-2 text-[12px] text-[var(--color-slate)]">
                <div className="font-bold uppercase tracking-wider">
                  Customer note
                </div>
                <p className="mt-1 whitespace-pre-wrap text-[var(--color-ink)]">
                  {order.notes}
                </p>
              </div>
            )}
          </FormSection>
          <FormSection title="Public order page">
            <Link
              href={`/products/store/orders/${order.id}`}
              target="_blank"
              className="inline-flex items-center gap-1 text-[13px] font-semibold text-[var(--color-blue)] hover:underline"
            >
              Open as the customer sees it
              <ExternalLink className="h-3 w-3" aria-hidden />
            </Link>
          </FormSection>
        </aside>
      </div>
    </>
  );
}

function Row({
  label,
  value,
  strong,
}: {
  label: string;
  value: string;
  strong?: boolean;
}) {
  return (
    <div className="flex justify-between">
      <dt className="text-[var(--color-slate)]">{label}</dt>
      <dd
        className={
          strong
            ? "font-display text-[15px] font-extrabold text-[var(--color-ink)]"
            : "font-semibold text-[var(--color-ink)]"
        }
      >
        {value}
      </dd>
    </div>
  );
}

function Stamp({
  label,
  value,
}: {
  label: string;
  value: Date | null | undefined;
}) {
  return (
    <div>
      <dt className="text-[10px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
        {label}
      </dt>
      <dd className="mt-0.5 text-[var(--color-ink)]">
        {value ? formatAdminDateTime(value) : "—"}
      </dd>
    </div>
  );
}
