"use client";

import * as React from "react";

import { Download, Mail, Pencil, Receipt } from "lucide-react";
import Link from "next/link";
import { toast } from "sonner";

import { FormPageHeader, FormPanel } from "@/app/dashboard/_components/form";
import { Button } from "@/components/ui/button";
import { FRONTEND_ROUTES } from "@/config/frontend-routes";
import { requestDashboardApi } from "@/lib/dashboard-api-client";
import { toastApiError } from "@/lib/toast-api-error";
import { cn } from "@/lib/utils";

import type { OrderDetail } from "../../_lib/orders-server-api";
import { DeletedCustomerBadge } from "../deleted-customer-badge";
import { ORDER_STATUS_FORM_OPTIONS } from "../order-form/constants";
import { OrderNotesPanel } from "../order-form/notes-panel";
import { OrderStatusBadge } from "../status-badge";

const LIST_HREF = "/dashboard/plans-orders/orders";
const STATUS_LABELS: Record<string, string> = Object.fromEntries(
  ORDER_STATUS_FORM_OPTIONS.map((option) => [option.value, option.label]),
);

function Field({ label, children }: { label: string; children: React.ReactNode }) {
  return (
    <div className="space-y-0.5">
      <dt className="text-muted-foreground text-xs">{label}</dt>
      <dd className="text-sm">{children || "—"}</dd>
    </div>
  );
}

function AmountRow({
  label,
  value,
  bold,
  tone,
}: {
  label: string;
  value: string;
  bold?: boolean;
  tone?: string;
}) {
  return (
    <div className="flex items-center justify-between gap-3">
      <dt className={cn("text-muted-foreground text-sm", bold && "font-semibold text-foreground")}>
        {label}
      </dt>
      <dd className={cn("tabular-nums text-sm", bold && "font-bold text-base", tone)}>{value}</dd>
    </div>
  );
}

/** Read-only order page: summary, amounts, billing details, history and invoice actions. */
export function OrderDetailView({ order }: { order: OrderDetail }) {
  const { view } = order;
  const [isEmailing, setIsEmailing] = React.useState(false);

  const handleEmailInvoice = async () => {
    if (!view.customerId || !view.customerEmail) {
      toast.error("This order has no customer email to send the invoice to.");
      return;
    }

    setIsEmailing(true);
    try {
      const data = await requestDashboardApi<{ message?: string }>({
        url: FRONTEND_ROUTES.plansOrders.orders.emailInvoice,
        method: "POST",
        body: { id: order.id },
        fallbackError: "Invoice could not be emailed.",
      });
      toast.success(data.message?.trim() || "Invoice emailed to the customer.");
    } catch (error) {
      toastApiError(error, "Invoice could not be emailed.");
    } finally {
      setIsEmailing(false);
    }
  };

  const editHref = `${LIST_HREF}/${order.id}`;
  const invoiceHref = `${FRONTEND_ROUTES.plansOrders.orders.invoice}?id=${order.id}`;

  return (
    <div className="m-8 flex flex-col">
      <FormPageHeader
        backHref={LIST_HREF}
        parentLabel="Orders"
        currentLabel={view.uid}
        titleIcon={<Receipt className="size-4 text-primary" />}
        title={`Order ${view.uid}`}
        meta={
          <div className="flex flex-wrap items-center gap-2">
            <OrderStatusBadge status={view.status} label={view.statusLabel} />
            <Button variant="outline" size="sm" className="gap-1.5" asChild>
              <a href={invoiceHref} target="_blank" rel="noreferrer">
                <Download className="size-4" />
                Invoice PDF
              </a>
            </Button>
            <Button
              variant="outline"
              size="sm"
              className="gap-1.5"
              onClick={() => void handleEmailInvoice()}
              disabled={isEmailing || !view.customerId}
              title={view.customerId ? undefined : "This order's customer was deleted."}
            >
              <Mail className="size-4" />
              {isEmailing ? "Sending…" : "Email invoice"}
            </Button>
            <Button size="sm" className="gap-1.5" asChild>
              <Link href={editHref}>
                <Pencil className="size-4" />
                Edit
              </Link>
            </Button>
          </div>
        }
      />

      <div className="grid gap-6 lg:grid-cols-[1fr_360px]">
        <div className="space-y-6">
          <FormPanel title="Order">
            <dl className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
              <Field label="Order ID">
                <span className="font-mono">{view.uid}</span>
              </Field>
              <Field label="Type">{view.typeLabel}</Field>
              <Field label="Plan">{view.planName}</Field>
              <Field label="Payment type">{view.paymentTypeLabel}</Field>
              <Field label="Date added">{view.dateAdded}</Field>
              <Field label="Membership period">
                {view.dateStart ? `${view.dateStart} → ${view.dateEnd || "—"}` : ""}
              </Field>
              <Field label="Promo code">
                {view.promoCode ? <span className="font-mono uppercase">{view.promoCode}</span> : ""}
              </Field>
            </dl>
          </FormPanel>

          <FormPanel title="Customer & billing">
            <dl className="grid gap-4 sm:grid-cols-2">
              <Field label="Customer">
                {view.customerId ? (
                  <Link
                    href={`/dashboard/customers/${view.customerId}?action=view`}
                    className="text-primary hover:underline"
                  >
                    {view.customerName}
                  </Link>
                ) : (
                  <span className="inline-flex flex-wrap items-center gap-1.5">
                    {view.customerName}
                    <DeletedCustomerBadge />
                  </span>
                )}
              </Field>
              <Field label="Customer email">{view.customerEmail}</Field>
              <Field label="Billing name">{view.billing.name}</Field>
              <Field label="Billing email">{view.billing.email}</Field>
              <Field label="Phone">{view.billing.phone}</Field>
              <Field label="Address">
                {[view.billing.address, view.billing.city, view.billing.country]
                  .filter(Boolean)
                  .join(", ")}
              </Field>
            </dl>
          </FormPanel>

          <FormPanel title="History" description="Notes and status changes, newest first.">
            <OrderNotesPanel notes={order.notes} statusLabels={STATUS_LABELS} />
          </FormPanel>
        </div>

        <aside className="lg:sticky lg:top-24 lg:self-start">
          <FormPanel title="Amounts">
            <dl className="space-y-2">
              <AmountRow label="Subtotal" value={view.formatted.subtotal} />
              <AmountRow
                label="Discount"
                value={view.formatted.discount}
                tone="text-emerald-700"
              />
              <AmountRow label="Shipping" value={view.formatted.shipping} />
              <AmountRow label={`Tax (${view.taxPercent}%)`} value={view.formatted.tax} />
              <AmountRow label="Wallet used" value={view.formatted.wallet} />
              <div className="my-1 border-t" />
              <AmountRow label="Total" value={view.formatted.total} bold />
            </dl>
          </FormPanel>
        </aside>
      </div>
    </div>
  );
}
