"use client";

import { useEffect, useState } from "react";
import { useParams } from "next/navigation";
import { toast } from "sonner";
import {
  PageHeader,
  Panel,
  AdminButton,
  StatusBadge,
  EmptyState,
} from "@/components/admin/ui";
import { formatCurrency } from "@/components/admin/adminNav";
import { useAuth } from "@/context/AuthContext";
import { api, ApiError, mediaOrPlaceholder, type OrderDetailsResponse } from "@/lib/api";
import { downloadOrderPdf } from "@/lib/orderPdf";

export default function AdminOrderDetailPage() {
  const params = useParams<{ id: string }>();
  const orderId = String(params.id);
  const { token } = useAuth();
  const [order, setOrder] = useState<OrderDetailsResponse | null | undefined>(undefined);
  const [error, setError] = useState("");

  useEffect(() => {
    if (!token) {
      setOrder(null);
      setError("Please login as admin to view this order.");
      return;
    }
    let cancelled = false;
    setOrder(undefined);
    void api.checkout
      .orderById(orderId, token)
      .then((data) => {
        if (!cancelled) setOrder(data);
      })
      .catch((err) => {
        if (cancelled) return;
        const message = err instanceof ApiError ? err.message : "Failed to load order.";
        setError(message);
        setOrder(null);
        toast.error(message);
      });
    return () => {
      cancelled = true;
    };
  }, [orderId, token]);

  if (order === undefined) {
    return <p className="text-sm text-muted-foreground">Loading order details…</p>;
  }

  if (!order) {
    return (
      <div className="space-y-6">
        <PageHeader
          title={`Order #${orderId}`}
          description={error || "Order not found."}
          actions={<AdminButton href="/admin/orders" variant="secondary">Back</AdminButton>}
        />
        <EmptyState title="Order not found" description={error || "It may have been deleted."} />
      </div>
    );
  }

  const email = order.contact_email || order.contact?.email || order.email || "—";
  const customerName =
    order.customer_name ||
    `${order.shipping_address?.first_name || ""} ${order.shipping_address?.last_name || ""}`.trim() ||
    "Customer";
  const phone = order.phone || order.shipping_address?.phone || "—";

  return (
    <div className="space-y-6">
      <PageHeader
        title={`Order #${order.id}`}
        description={
          order.created_at
            ? `Placed on ${new Date(order.created_at).toLocaleString()}`
            : "Order details"
        }
        actions={
          <>
            <AdminButton href="/admin/orders" variant="secondary">
              Back to Orders
            </AdminButton>
            <AdminButton
              onClick={() => {
                downloadOrderPdf(order);
                toast.success("PDF downloaded.");
              }}
            >
              Download PDF
            </AdminButton>
          </>
        }
      />

      <div className="flex flex-wrap items-center gap-2">
        <StatusBadge status={order.status} />
        {order.payment_method ? <StatusBadge status={String(order.payment_method).toUpperCase()} /> : null}
      </div>

      <div className="grid gap-4 xl:grid-cols-3">
        <Panel title="Customer">
          <div className="space-y-2 text-sm">
            <p className="font-semibold">{customerName}</p>
            <p className="text-muted-foreground">{email}</p>
            <p className="text-muted-foreground">{phone}</p>
            {order.city ? <p className="text-muted-foreground">{order.city}</p> : null}
          </div>
        </Panel>

        <Panel title="Payment">
          <div className="space-y-2 text-sm">
            <p>
              <span className="text-muted-foreground">Method:</span>{" "}
              {String(order.payment_method || "—").toUpperCase()}
            </p>
            {(order.payments || []).map((payment, idx) => (
              <div key={payment.id || idx} className="rounded-lg border border-border bg-secondary/30 p-3">
                <p className="font-medium">{payment.method || "Payment"} · {payment.status || "—"}</p>
                <p className="text-xs text-muted-foreground">
                  {payment.amount != null ? formatCurrency(Number(payment.amount)) : "—"}
                  {payment.reference ? ` · Ref ${payment.reference}` : ""}
                </p>
              </div>
            ))}
            {!order.payments?.length ? (
              <p className="text-muted-foreground">No payment records yet.</p>
            ) : null}
          </div>
        </Panel>

        <Panel title="Shipping">
          <div className="space-y-2 text-sm">
            <p>
              <span className="text-muted-foreground">Method:</span>{" "}
              {order.shipping_method?.name || "—"}
            </p>
            {order.shipping_method?.cost != null ? (
              <p>
                <span className="text-muted-foreground">Cost:</span>{" "}
                {formatCurrency(Number(order.shipping_method.cost))}
              </p>
            ) : null}
            {(order.shipments || []).map((shipment, idx) => (
              <div key={shipment.id || idx} className="rounded-lg border border-border bg-secondary/30 p-3">
                <p className="font-medium">{shipment.status || "Shipment"}</p>
                <p className="text-xs text-muted-foreground">
                  {shipment.tracking_number ? `Tracking: ${shipment.tracking_number}` : "No tracking yet"}
                </p>
              </div>
            ))}
          </div>
        </Panel>
      </div>

      <div className="grid gap-4 xl:grid-cols-2">
        <Panel title="Shipping Address">
          {order.shipping_address ? (
            <div className="space-y-1 text-sm text-muted-foreground">
              <p className="font-semibold text-foreground">
                {order.shipping_address.first_name} {order.shipping_address.last_name}
              </p>
              <p>{order.shipping_address.address}</p>
              {order.shipping_address.apartment ? <p>{order.shipping_address.apartment}</p> : null}
              <p>
                {order.shipping_address.city}
                {order.shipping_address.postal_code ? ` ${order.shipping_address.postal_code}` : ""}
              </p>
              <p>{order.shipping_address.country}</p>
              <p>{order.shipping_address.phone}</p>
            </div>
          ) : (
            <p className="text-sm text-muted-foreground">No shipping address.</p>
          )}
        </Panel>
        <Panel title="Billing Address">
          {order.billing_address ? (
            <div className="space-y-1 text-sm text-muted-foreground">
              <p className="font-semibold text-foreground">
                {order.billing_address.first_name} {order.billing_address.last_name}
              </p>
              <p>{order.billing_address.address}</p>
              {order.billing_address.apartment ? <p>{order.billing_address.apartment}</p> : null}
              <p>
                {order.billing_address.city}
                {order.billing_address.postal_code ? ` ${order.billing_address.postal_code}` : ""}
              </p>
              <p>{order.billing_address.country}</p>
              <p>{order.billing_address.phone}</p>
            </div>
          ) : (
            <p className="text-sm text-muted-foreground">Same as shipping address</p>
          )}
        </Panel>
      </div>

      <Panel title="Products">
        <div className="overflow-x-auto">
          <table className="w-full min-w-[560px] text-left text-sm">
            <thead>
              <tr className="border-b border-border text-xs uppercase tracking-wide text-muted-foreground">
                <th className="pb-2 font-semibold">Product</th>
                <th className="pb-2 font-semibold">Qty</th>
                <th className="pb-2 font-semibold">Unit Price</th>
                <th className="pb-2 font-semibold">Line Total</th>
              </tr>
            </thead>
            <tbody>
              {(order.items || []).map((item, idx) => (
                <tr key={`${item.product_id}-${idx}`} className="border-b border-border/60">
                  <td className="py-3">
                    <div className="flex items-center gap-3">
                      {/* eslint-disable-next-line @next/next/no-img-element */}
                      <img
                        src={mediaOrPlaceholder(item.image)}
                        alt=""
                        className="h-12 w-12 rounded-lg border border-border object-cover"
                      />
                      <span className="font-medium">
                        {item.product_name || `Product #${item.product_id}`}
                      </span>
                    </div>
                  </td>
                  <td className="py-3">{item.quantity}</td>
                  <td className="py-3">{formatCurrency(Number(item.unit_price))}</td>
                  <td className="py-3 font-semibold">{formatCurrency(Number(item.subtotal))}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
        <div className="mt-4 ml-auto max-w-xs space-y-1.5 text-sm">
          <div className="flex justify-between">
            <span className="text-muted-foreground">Subtotal</span>
            <span>{formatCurrency(Number(order.summary?.subtotal || 0))}</span>
          </div>
          <div className="flex justify-between">
            <span className="text-muted-foreground">Shipping</span>
            <span>{formatCurrency(Number(order.summary?.shipping || 0))}</span>
          </div>
          <div className="flex justify-between border-t border-border pt-2 font-semibold">
            <span>Total ({order.summary?.currency || "PKR"})</span>
            <span>{formatCurrency(Number(order.summary?.total || 0))}</span>
          </div>
        </div>
      </Panel>
    </div>
  );
}
