import { getAdminUser } from "@/lib/admin-permissions";
import { getAdminOrderDetail, type AdminOrder } from "@/actions/orders";
import OrderEditForm from "@/components/admin/OrderEditForm";
import OrderPaymentSection from "@/components/admin/OrderPaymentSection";
import OrderPickupAction from "@/components/admin/OrderPickupAction";
import AdminAccessDenied from "@/components/admin/AdminAccessDenied";
import AdminBadge from "@/components/admin/design-system/AdminBadge";
import { PageHeader } from "@/components/admin/design-system";
import { formatDate } from "@/lib/format-date";
import { redirect } from "next/navigation";
import Link from "next/link";

type OrderDetailPageProps = {
  params: Promise<{
    id: string;
  }>;
};

type OrderItem = {
  id: string;
  quantity: number;
  price: number | string;
  products?: {
    name: string;
  } | null;
};

function formatCurrency(amount: number) {
  return new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(amount);
}

export default async function OrderDetailPage({ params }: OrderDetailPageProps) {
  const { id } = await params;

  const order = await getAdminOrderDetail(id);

  if (!order) {
    return (
      <main
        className="min-h-screen px-6 py-10"
        style={{ backgroundColor: "var(--admin-bg)" }}
      >
        <div className="mx-auto max-w-4xl">
          <Link
            href="/admin/orders"
            className="inline-flex items-center gap-2 text-sm transition-colors"
            style={{ color: "var(--admin-text-muted)" }}
          >
            ← Back to Orders
          </Link>
          <div
            className="mt-8 rounded-2xl border p-8 text-center"
            style={{
              borderColor: "var(--admin-danger-soft)",
              backgroundColor: "var(--admin-danger-soft)",
            }}
          >
            <p
              className="text-lg font-semibold"
              style={{ color: "var(--admin-danger)" }}
            >
              Order not found
            </p>
          </div>
        </div>
      </main>
    );
  }

  const adminUser = await getAdminUser();

  if (!adminUser) return <AdminAccessDenied />;

  if (!adminUser.can_manage_orders) redirect("/admin/pickup");

  if (adminUser?.brand_id && order.stops?.brand_id !== adminUser.brand_id) {
    return <AdminAccessDenied />;
  }

  const brandId = order.stops?.brand_id ?? null;
  const subtotal = Number(order.subtotal);
  const discount_amount = Number(order.discount_amount ?? 0);
  const taxAmount = Number(order.tax_amount ?? 0);
  const total = subtotal + taxAmount - discount_amount;

  return (
    <main
      className="min-h-screen px-6 py-8"
      style={{ backgroundColor: "var(--admin-bg)" }}
    >
      <div className="mx-auto max-w-4xl space-y-6">
        {/* Back link */}
        <Link
          href="/admin/orders"
          className="inline-flex items-center gap-2 text-xs font-semibold transition-colors"
          style={{ color: "var(--admin-text-muted)" }}
        >
          <svg className="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
            <path strokeLinecap="round" strokeLinejoin="round" d="M15 19l-7-7 7-7" />
          </svg>
          Back to Orders
        </Link>

        {/* Header */}
        <div>
          <p className="ha-eyebrow mb-2">
            Order #{order.id.slice(0, 8).toUpperCase()} · {formatDate(order.created_at)}
          </p>
          <PageHeader
            title={order.customer_name}
            subtitle={`${formatCurrency(total)} · ${order.pickup_complete ? "Picked Up" : "Awaiting Pickup"}${order.stops ? ` · ${order.stops.city}, ${order.stops.state}` : ""}`}
            actions={
              <div className="flex items-center gap-2">
                <AdminBadge tone={order.pickup_complete ? "success" : "warning"} dot>
                  {order.pickup_complete ? "Picked Up" : "Pending"}
                </AdminBadge>
                {order.payment_processor && (
                  <AdminBadge tone="info">{order.payment_processor}</AdminBadge>
                )}
              </div>
            }
          />
        </div>

        {/* Customer info */}
        <div
          className="rounded-2xl border p-6 shadow-sm"
          style={{
            borderColor: "var(--admin-border)",
            backgroundColor: "var(--admin-card-bg)",
          }}
        >
          <div className="flex items-start justify-between gap-4">
            <div>
              <p
                className="text-xs font-semibold uppercase tracking-wider"
                style={{ color: "var(--admin-text-muted)" }}
              >
                Customer
              </p>
              <h2
                className="mt-1 text-2xl font-bold"
                style={{ color: "var(--admin-text-primary)" }}
              >
                {order.customer_name}
              </h2>
            </div>
            <OrderPickupAction
              orderId={order.id}
              brandId={brandId}
              currentlyPickedUp={order.pickup_complete}
            />
          </div>

          <div className="mt-5 grid grid-cols-2 gap-4">
            {order.customer_phone && (
              <div>
                <p
                  className="text-xs font-semibold"
                  style={{ color: "var(--admin-text-muted)" }}
                >
                  Phone
                </p>
                <p
                  className="mt-0.5 text-sm font-medium"
                  style={{ color: "var(--admin-text-primary)" }}
                >
                  {order.customer_phone}
                </p>
              </div>
            )}
            {order.customer_email && (
              <div>
                <p
                  className="text-xs font-semibold"
                  style={{ color: "var(--admin-text-muted)" }}
                >
                  Email
                </p>
                <p
                  className="mt-0.5 text-sm font-medium"
                  style={{ color: "var(--admin-text-primary)" }}
                >
                  {order.customer_email}
                </p>
              </div>
            )}
          </div>
        </div>

        {/* Stop info */}
        {order.stops && (
          <div
            className="rounded-2xl border p-6 shadow-sm"
            style={{
              borderColor: "var(--admin-border)",
              backgroundColor: "var(--admin-card-bg)",
            }}
          >
            <p
              className="text-xs font-semibold uppercase tracking-wider"
              style={{ color: "var(--admin-text-muted)" }}
            >
              Pickup Location
            </p>
            <p
              className="mt-1 text-lg font-bold"
              style={{ color: "var(--admin-text-primary)" }}
            >
              {order.stops.city}, {order.stops.state}
            </p>
            <p
              className="mt-0.5 text-sm"
              style={{ color: "var(--admin-text-muted)" }}
            >
              {formatDate(order.stops.date)}
            </p>
          </div>
        )}

        {/* Order items */}
        <div
          className="rounded-2xl border p-6 shadow-sm"
          style={{
            borderColor: "var(--admin-border)",
            backgroundColor: "var(--admin-card-bg)",
          }}
        >
          <h3
            className="text-lg font-bold"
            style={{ color: "var(--admin-text-primary)" }}
          >
            Order Items
          </h3>

          {order.order_items && order.order_items.length > 0 ? (
            <div
              className="mt-4 divide-y"
              style={{ borderColor: "var(--admin-border-light)" }}
            >
              {order.order_items.map((item: OrderItem) => (
                <div
                  key={item.id}
                  className="flex items-center justify-between py-3"
                >
                  <div>
                    <p
                      className="font-medium"
                      style={{ color: "var(--admin-text-primary)" }}
                    >
                      {item.products?.name ?? "Unknown Product"}
                    </p>
                    <p
                      className="text-xs"
                      style={{ color: "var(--admin-text-muted)" }}
                    >
                      Qty: {item.quantity} × {formatCurrency(Number(item.price))}
                    </p>
                  </div>
                  <p
                    className="font-semibold"
                    style={{ color: "var(--admin-text-primary)" }}
                  >
                    {formatCurrency(Number(item.price) * item.quantity)}
                  </p>
                </div>
              ))}
            </div>
          ) : (
            <p
              className="mt-4 text-sm"
              style={{ color: "var(--admin-text-muted)" }}
            >
              No items found
            </p>
          )}

          {/* Totals */}
          <div
            className="mt-6 border-t pt-6 space-y-2"
            style={{ borderColor: "var(--admin-border-light)" }}
          >
            <div className="flex justify-between text-sm">
              <span style={{ color: "var(--admin-text-muted)" }}>Subtotal</span>
              <span style={{ color: "var(--admin-text-primary)" }}>
                {formatCurrency(subtotal)}
              </span>
            </div>
            {taxAmount > 0 && (
              <div className="flex justify-between text-sm">
                <span style={{ color: "var(--admin-text-muted)" }}>Tax</span>
                <span style={{ color: "var(--admin-text-primary)" }}>
                  {formatCurrency(taxAmount)}
                </span>
              </div>
            )}
            {discount_amount > 0 && (
              <div className="flex justify-between text-sm">
                <span style={{ color: "var(--admin-text-muted)" }}>Discount</span>
                <span style={{ color: "var(--admin-danger)" }}>
                  -{formatCurrency(discount_amount)}
                </span>
                {order.discount_reason && (
                  <span
                    className="text-xs ml-2"
                    style={{ color: "var(--admin-text-muted)" }}
                  >
                    ({order.discount_reason})
                  </span>
                )}
              </div>
            )}
            <div
              className="flex justify-between text-lg font-bold pt-2 border-t"
              style={{
                color: "var(--admin-text-primary)",
                borderColor: "var(--admin-border)",
              }}
            >
              <span>Total</span>
              <span>{formatCurrency(total)}</span>
            </div>
          </div>
        </div>

        {/* Payment & Refunds */}
        <div
          className="rounded-2xl border p-6 shadow-sm"
          style={{
            borderColor: "var(--admin-border)",
            backgroundColor: "var(--admin-card-bg)",
          }}
        >
          <h3
            className="text-lg font-bold"
            style={{ color: "var(--admin-text-primary)" }}
          >
            Payment & Refunds
          </h3>
          <p
            className="mt-1 text-sm"
            style={{ color: "var(--admin-text-muted)" }}
          >
            Record payment details and manage refunds
          </p>

          <div className="mt-5">
            <OrderPaymentSection
              orderId={order.id}
              brandId={brandId}
              orderTotal={total}
              payment_processor={order.payment_processor}
              payment_status={order.payment_status}
              payment_transaction_id={order.payment_transaction_id}
              refunded_amount={order.refunded_amount ?? 0}
              refund_reason={order.refund_reason}
              existingRefunds={order.refunds ?? []}
            />
          </div>
        </div>

        {/* Edit form */}
        <div
          className="rounded-2xl border p-6 shadow-sm"
          style={{
            borderColor: "var(--admin-border)",
            backgroundColor: "var(--admin-card-bg)",
          }}
        >
          <h3
            className="text-lg font-bold"
            style={{ color: "var(--admin-text-primary)" }}
          >
            Edit Order
          </h3>
          <p
            className="mt-1 text-sm"
            style={{ color: "var(--admin-text-muted)" }}
          >
            Update customer details, pricing, and status
          </p>

          <div className="mt-5">
            <OrderEditForm order={order as unknown as Parameters<typeof OrderEditForm>[0]["order"]} brandId={brandId} />
          </div>
        </div>

        {/* Internal notes */}
        {order.internal_notes && (
          <div
            className="rounded-2xl border p-6"
            style={{
              borderColor: "var(--admin-warning-soft)",
              backgroundColor: "var(--admin-warning-soft)",
            }}
          >
            <p
              className="text-xs font-semibold uppercase tracking-wider"
              style={{ color: "var(--admin-warning)" }}
            >
              Internal Notes
            </p>
            <p
              className="mt-1 text-sm"
              style={{ color: "var(--admin-text-primary)" }}
            >
              {order.internal_notes}
            </p>
          </div>
        )}
      </div>
    </main>
  );
}
