"use client";

import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { Order, OrderStatus } from "@/lib/types";
import { formatPrice } from "@/lib/format";

const STATUS_OPTIONS: { value: OrderStatus; label: string }[] = [
  { value: "pending", label: "Pending" },
  { value: "paid", label: "Paid" },
  { value: "processing", label: "Processing" },
  { value: "out_for_delivery", label: "Out for delivery" },
  { value: "delivered", label: "Delivered" },
  { value: "cancelled", label: "Cancelled" },
];

export function OrdersTable({ orders }: { orders: Order[] }) {
  const router = useRouter();
  const [updatingId, setUpdatingId] = useState<string | null>(null);

  async function updateStatus(id: string, status: OrderStatus) {
    setUpdatingId(id);
    try {
      const res = await fetch(`/api/admin/orders/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ status }),
      });
      if (res.ok) router.refresh();
    } finally {
      setUpdatingId(null);
    }
  }

  if (orders.length === 0) {
    return (
      <div className="rounded-xl border border-dashed border-black/10 px-4 py-12 text-center text-sm text-black/50">
        No orders yet.
      </div>
    );
  }

  return (
    <div className="overflow-x-auto rounded-xl border border-black/[0.06]">
      <table className="w-full min-w-[820px] text-left text-sm">
        <thead className="border-b border-black/[0.06] bg-black/[0.015] text-xs uppercase text-black/45">
          <tr>
            <th className="px-4 py-3 font-medium">Order</th>
            <th className="px-4 py-3 font-medium">Customer</th>
            <th className="px-4 py-3 font-medium">Total</th>
            <th className="px-4 py-3 font-medium">Payment</th>
            <th className="px-4 py-3 font-medium">Status</th>
            <th className="px-4 py-3 font-medium"></th>
          </tr>
        </thead>
        <tbody>
          {orders.map((o) => (
            <tr key={o.id} className="border-b border-black/[0.04] last:border-0">
              <td className="px-4 py-3">
                <p className="font-medium text-brand-ink">{o.id}</p>
                <p className="text-xs text-black/45">
                  {new Date(o.createdAt).toLocaleDateString("en-NG", {
                    day: "numeric",
                    month: "short",
                    hour: "2-digit",
                    minute: "2-digit",
                  })}
                </p>
              </td>
              <td className="px-4 py-3">
                <p className="text-brand-ink">{o.customer.name}</p>
                <p className="text-xs text-black/45">{o.customer.phone}</p>
              </td>
              <td className="px-4 py-3 font-medium text-brand-ink">{formatPrice(o.total)}</td>
              <td className="px-4 py-3">
                <span
                  className={`rounded-full px-2 py-0.5 text-xs font-medium ${
                    o.paymentStatus === "paid"
                      ? "bg-[#EAF6EE] text-success"
                      : o.paymentStatus === "failed"
                      ? "bg-red-50 text-danger"
                      : "bg-black/5 text-black/50"
                  }`}
                >
                  {o.paymentStatus}
                </span>
              </td>
              <td className="px-4 py-3">
                <select
                  value={o.status}
                  disabled={updatingId === o.id}
                  onChange={(e) => updateStatus(o.id, e.target.value as OrderStatus)}
                  className="rounded-lg border border-black/10 px-2 py-1.5 text-sm focus:border-brand-orange focus:outline-none"
                >
                  {STATUS_OPTIONS.map((s) => (
                    <option key={s.value} value={s.value}>
                      {s.label}
                    </option>
                  ))}
                </select>
              </td>
              <td className="px-4 py-3 text-right">
                <Link
                  href={`/order/${o.id}`}
                  target="_blank"
                  className="text-sm font-medium text-brand-ink hover:underline"
                >
                  View
                </Link>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
