"use client";

import {
  type WholesaleOrder,
} from "@/actions/wholesale";
import { AdminButton } from "@/components/admin/design-system";
import StatusBadge from "./StatusBadge";

export default function OrdersTable({
  orders,
  selected,
  fulfilling,
  openActions,
  onToggleSelect,
  onToggleAll,
  onFulfill,
  onRecordDeposit,
  onToggleActions,
  onCloseActions,
  onViewOrder,
  onGenerateManifestForOrder,
  onSendPriceSheetForOrder,
  onCancelOrder,
  onDeleteOrder,
}: {
  orders: WholesaleOrder[];
  selected: Set<string>;
  fulfilling: string | null;
  openActions: string | null;
  onToggleSelect: (id: string) => void;
  onToggleAll: () => void;
  onFulfill: (id: string) => void;
  onRecordDeposit: (id: string) => void;
  onToggleActions: (id: string) => void;
  onCloseActions: () => void;
  onViewOrder: (o: WholesaleOrder) => void;
  onGenerateManifestForOrder: (o: WholesaleOrder) => void;
  onSendPriceSheetForOrder: (o: WholesaleOrder) => void;
  onCancelOrder: (id: string) => void;
  onDeleteOrder: (id: string) => void;
}) {
  return (
    <div className="rounded-2xl bg-white border border-[var(--admin-border)] shadow-sm overflow-hidden">
      <table className="w-full text-sm">
        <thead className="bg-[var(--admin-bg-subtle)] text-[var(--admin-text-muted)]">
          <tr>
            <th className="px-5 py-3 font-semibold text-left w-10">
              <input id="fld-search" aria-label="Checkbox" type="checkbox" checked={selected.size === orders.length && orders.length > 0} onChange={onToggleAll} className="rounded" />
            </th>
            <th className="px-5 py-3 font-semibold text-left">Invoice</th>
            <th className="px-5 py-3 font-semibold text-left">Customer</th>
            <th className="px-5 py-3 font-semibold text-left">Pickup Date</th>
            <th className="px-5 py-3 font-semibold text-right">Subtotal</th>
            <th className="px-5 py-3 font-semibold text-right">Deposit</th>
            <th className="px-5 py-3 font-semibold text-right">Balance</th>
            <th className="px-5 py-3 font-semibold text-left">Status</th>
            <th className="px-5 py-3 font-semibold text-left">Payment</th>
            <th className="px-5 py-3 font-semibold text-left">Actions</th>
          </tr>
        </thead>
        <tbody className="divide-y divide-[var(--admin-border-light)]">
          {orders.length === 0 ? (
            <tr><td colSpan={10} className="py-8 text-center text-[var(--admin-text-muted)]">No orders match the current filters.</td></tr>
          ) : orders.map(o => (
            <tr key={o.id} className={`hover:bg-[var(--admin-bg-subtle)] ${selected.has(o.id) ? "bg-[var(--admin-accent-light)]" : ""}`}>
              <td className="px-5 py-3">
                <input aria-label="Checkbox" type="checkbox" checked={selected.has(o.id)} onChange={() => onToggleSelect(o.id)} className="rounded" />
              </td>
              <td className="px-5 py-3 font-mono text-xs text-[var(--admin-text-muted)]">{o.invoice_number ?? "—"}</td>
              <td className="px-5 py-3 font-medium text-[var(--admin-text-primary)]">{o.company_name}</td>
              <td className="px-5 py-3 text-[var(--admin-text-secondary)]">{o.anticipated_pickup_date ?? "—"}</td>
              <td className="px-5 py-3 text-right font-semibold text-[var(--admin-text-primary)]">${Number(o.subtotal).toFixed(2)}</td>
              <td className="px-5 py-3 text-right text-[var(--admin-text-secondary)]">${Number(o.deposit_paid).toFixed(2)} / ${Number(o.deposit_required).toFixed(2)}</td>
              <td className="px-5 py-3 text-right">
                <span className={Number(o.balance_due) > 0 ? "text-[var(--admin-warning)] font-medium" : "text-[var(--admin-accent)]"}>
                  ${Number(o.balance_due).toFixed(2)}
                </span>
              </td>
              <td className="px-5 py-3"><StatusBadge status={o.status} /></td>
              <td className="px-5 py-3">
                <span className={`text-xs font-medium ${o.payment_status === "paid" ? "text-[var(--admin-accent)]" : "text-[var(--admin-warning)]"}`}>
                  {o.payment_status}
                </span>
              </td>
              <td className="px-5 py-4 actions-cell relative">
                <div className="flex items-center gap-2">
                  {/* Primary: Mark Fulfilled — only when order is not yet fulfilled */}
                  {o.fulfillment_status !== "fulfilled" && (
                    <AdminButton
                      variant="primary"
                      size="sm"
                      onClick={() => !fulfilling && onFulfill(o.id)}
                      disabled={fulfilling === o.id}
                      isLoading={fulfilling === o.id}
                    >
                      <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2.5}><path strokeLinecap="round" strokeLinejoin="round" d="M5 13l4 4L19 7" /></svg>
                      {fulfilling === o.id ? "..." : "Fulfill"}
                    </AdminButton>
                  )}

                  {/* Primary: Record Deposit — when there's a balance due */}
                  {Number(o.balance_due) > 0 && o.fulfillment_status !== "fulfilled" && (
                    <AdminButton
                      variant="secondary"
                      size="sm"
                      onClick={() => onRecordDeposit(o.id)}
                    >
                      <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}><path strokeLinecap="round" strokeLinejoin="round" d="M12 6v12m-9-9h18" /></svg>
                      Deposit
                    </AdminButton>
                  )}

                  {/* Invoice download — always visible as icon button */}
                  <a aria-label="Download Invoice"
                    href={`/api/wholesale/invoice/${o.id}/pdf`}
                    target="_blank"
                    rel="noopener noreferrer" title="Download Invoice"
                    className="inline-flex items-center justify-center rounded-xl w-9 h-9 text-[var(--admin-text-muted)] hover:text-[var(--admin-accent)] hover:bg-[var(--admin-bg-subtle)] transition-colors">
                    <svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.75}><path strokeLinecap="round" strokeLinejoin="round" d="M9 12h9m-9-6h6m-3 12a9 9 0 110 12H15M6 2h9l4 4v14a2 2 0 01-2 2H6a2 2 0 01-2-2V4a2 2 0 012-2z"/></svg>
                  </a>

                  {/* ⋮ Actions dropdown — opens upward to avoid table cutoff */}
                  <div className="relative">
                    <button type="button"
                      onClick={(e) => { e.stopPropagation(); onToggleActions(o.id); }}
                      title="More actions"
                      aria-label="More actions"
                      className="inline-flex items-center justify-center rounded-xl w-9 h-9 text-[var(--admin-text-muted)] hover:text-[var(--admin-text-secondary)] hover:bg-[var(--admin-bg-subtle)] transition-colors"
                    >
                      <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20"><circle cx="10" cy="4" r="1.5"/><circle cx="10" cy="10" r="1.5"/><circle cx="10" cy="16" r="1.5"/></svg>
                    </button>

                    {openActions === o.id && (
                      <div
                        className="absolute bottom-full right-0 mb-1 z-30 w-56 rounded-xl bg-white shadow-xl ring-1 ring-[var(--admin-border)] py-1 text-sm"
                        onClick={e => e.stopPropagation()}
                      >
                        <button type="button"
                          onClick={() => { onCloseActions(); onViewOrder(o); }}
                          className="w-full text-left px-4 py-3 text-[var(--admin-accent)] hover:bg-[var(--admin-accent-light)] flex items-center gap-3 font-medium"
                        >
                          <svg className="w-4 h-4 text-[var(--admin-accent)]" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}><path strokeLinecap="round" strokeLinejoin="round" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path strokeLinecap="round" strokeLinejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>
                          View / Edit Order
                        </button>

                        <button type="button"
                          onClick={() => { onCloseActions(); onGenerateManifestForOrder(o); }}
                          className="w-full text-left px-4 py-3 text-[var(--admin-text-secondary)] hover:bg-[var(--admin-bg-subtle)] flex items-center gap-3"
                        >
                          <svg className="w-4 h-4 text-[var(--admin-text-muted)]" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}><path strokeLinecap="round" strokeLinejoin="round" d="M9 12h9m-9-6h6m-3 12a9 9 0 01-18 0 9 9 0 0118 0z"/></svg>
                          Generate Manifest
                        </button>

                        <button type="button"
                          onClick={() => { onCloseActions(); onSendPriceSheetForOrder(o); }}
                          className="w-full text-left px-4 py-3 text-[var(--admin-text-secondary)] hover:bg-[var(--admin-bg-subtle)] flex items-center gap-3"
                        >
                          <svg className="w-4 h-4 text-[var(--admin-text-muted)]" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}><path strokeLinecap="round" strokeLinejoin="round" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/></svg>
                          Send Price Sheet
                        </button>

                        <div className="my-1 border-t border-[var(--admin-border)]" />

                        {o.status !== "cancelled" && o.fulfillment_status !== "fulfilled" && (
                          <button type="button"
                            onClick={() => { onCloseActions(); onCancelOrder(o.id); }}
                            className="w-full text-left px-4 py-3 text-[var(--admin-danger)] hover:bg-[var(--admin-danger-light)] flex items-center gap-3"
                          >
                            <svg className="w-4 h-4 text-[var(--admin-danger)]" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}><path strokeLinecap="round" strokeLinejoin="round" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636"/></svg>
                            Cancel Order
                          </button>
                        )}

                        {o.fulfillment_status !== "fulfilled" && (
                          <button type="button"
                            onClick={() => { onCloseActions(); onDeleteOrder(o.id); }}
                            className="w-full text-left px-4 py-3 text-[var(--admin-danger)] hover:bg-[var(--admin-danger-light)] flex items-center gap-3"
                          >
                            <svg className="w-4 h-4 text-[var(--admin-danger)]" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={1.75}><path strokeLinecap="round" strokeLinejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                            Delete Order
                          </button>
                        )}
                      </div>
                    )}
                  </div>
                </div>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
