"use client";

import { useState } from "react";
import { formatDate } from "@/lib/format-date";
import AdminBadge from "./design-system/AdminBadge";
import { toggleOrderPickupComplete } from "@/actions/orders";

type Order = {
  id: string;
  customer_name: string;
  customer_email: string | null;
  stop_id: string;
  status: string;
  subtotal: number;
  pickup_complete: boolean;
  created_at: string;
};

type OrderStatusTone = "warning" | "info" | "success" | "danger" | "neutral";

const statusToTone: Record<string, OrderStatusTone> = {
  pending: "warning",
  confirmed: "info",
  paid: "success",
  cancelled: "danger",
  completed: "neutral",
};

export default function OrderTableBody({ orders }: { orders: Order[] }) {
  const [pickupToggles, setPickupToggles] = useState<Record<string, boolean>>(
    () => Object.fromEntries(orders.map((o) => [o.id, o.pickup_complete]))
  );
  const [error, setError] = useState<string | null>(null);

  async function togglePickup(orderId: string, current: boolean) {
    const next = !current;
    setPickupToggles((prev) => ({ ...prev, [orderId]: next }));
    setError(null);
    const result = await toggleOrderPickupComplete({ orderId, pickupComplete: next });
    if (!result.success) {
      // Revert optimistic update on failure
      setPickupToggles((prev) => ({ ...prev, [orderId]: current }));
      setError(result.error);
    }
  }

  return (
    <tbody style={{ borderColor: "var(--admin-border)" }}>
      {error && (
        <tr>
          <td
            colSpan={6}
            className="px-3 py-2 text-sm"
            style={{ color: "var(--admin-danger)" }}
          >
            {error}
          </td>
        </tr>
      )}
      {orders.map((order) => (
        <tr
          key={order.id}
          className="transition-colors"
          style={{ borderTop: "1px solid var(--admin-border-light)" }}
        >
          <td className="px-3 py-2">
            <span
              className="font-mono text-sm"
              style={{ color: "var(--admin-text-muted)" }}
            >
              {order.id.slice(0, 8)}
            </span>
          </td>

          <td className="px-3 py-2">
            <div
              className="font-medium"
              style={{ color: "var(--admin-text-primary)" }}
            >
              {order.customer_name}
            </div>
            <div
              className="text-sm"
              style={{ color: "var(--admin-text-muted)" }}
            >
              {order.customer_email}
            </div>
          </td>

          <td className="px-3 py-2">
            <AdminBadge tone={statusToTone[order.status] ?? "neutral"}>
              {order.status ?? "pending"}
            </AdminBadge>
          </td>

          <td
            className="px-3 py-2 font-semibold"
            style={{ color: "var(--admin-text-primary)" }}
          >
            ${Number(order.subtotal).toFixed(2)}
          </td>

          <td className="px-3 py-2">
            <button
              type="button"
              onClick={() => togglePickup(order.id, pickupToggles[order.id])}
              className="transition-opacity hover:opacity-80"
            >
              <AdminBadge tone={pickupToggles[order.id] ? "success" : "neutral"} dot>
                {pickupToggles[order.id] ? "Picked up" : "Pending"}
              </AdminBadge>
            </button>
          </td>

          <td
            className="px-3 py-2 text-sm"
            style={{ color: "var(--admin-text-muted)" }}
          >
            {formatDate(new Date(order.created_at))}
          </td>
        </tr>
      ))}
    </tbody>
  );
}
