import { useEffect, useState } from "react";

import { useAuth } from "@/auth/AuthProvider";
import { fetchAdminQueue, type AdminQueueItem } from "@/api/orders";

export function AdminQueuePage() {
  const { token } = useAuth();
  const [rows, setRows] = useState<AdminQueueItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!token?.access_token) {
      return;
    }

    let cancelled = false;

    setLoading(true);
    setError(null);

    fetchAdminQueue(token.access_token)
      .then((response) => {
        if (!cancelled) {
          setRows(response);
        }
      })
      .catch((nextError: Error) => {
        if (!cancelled) {
          setError(nextError.message);
          setRows([]);
        }
      })
      .finally(() => {
        if (!cancelled) {
          setLoading(false);
        }
      });

    return () => {
      cancelled = true;
    };
  }, [token?.access_token]);

  return (
    <div className="space-y-6">
      <div className="rounded-[var(--admin-card-radius)] border border-[var(--admin-border)] bg-white p-6">
        <h1 className="text-lg font-bold">거래관리</h1>
        <p className="mt-2 text-sm text-[var(--admin-muted)]">
          총 <span className="font-semibold text-[#202939]">{loading ? "..." : rows.length}</span>건의 거래
        </p>
      </div>

      <div className="rounded-[var(--admin-card-radius)] border border-[var(--admin-border)] bg-white">
        <table className="w-full border-collapse text-sm">
          <thead className="bg-[#f8fafe] text-left text-[#516174]">
            <tr>
              {["주문ID", "상품", "고객", "상태", "SLA"].map((cell) => (
                <th key={cell} className="border-b border-r border-[var(--admin-border)] px-4 py-4 font-semibold last:border-r-0">
                  {cell}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {loading ? (
              <tr>
                <td className="border-b border-[var(--admin-border)] px-4 py-4 text-[var(--admin-muted)]" colSpan={5}>
                  거래 큐를 불러오는 중입니다.
                </td>
              </tr>
            ) : null}
            {error ? (
              <tr>
                <td className="border-b border-[var(--admin-border)] px-4 py-4 text-[var(--admin-danger)]" colSpan={5}>
                  {error}
                </td>
              </tr>
            ) : null}
            {!loading && !error && !rows.length ? (
              <tr>
                <td className="border-b border-[var(--admin-border)] px-4 py-4 text-[var(--admin-muted)]" colSpan={5}>
                  현재 표시할 거래가 없습니다.
                </td>
              </tr>
            ) : null}
            {rows.map((row) => (
              <tr key={row.order_id}>
                <td className="border-b border-r border-[var(--admin-border)] px-4 py-4 align-middle last:border-r-0">{row.order_id}</td>
                <td className="border-b border-r border-[var(--admin-border)] px-4 py-4 align-middle last:border-r-0">{row.product_name}</td>
                <td className="border-b border-r border-[var(--admin-border)] px-4 py-4 align-middle last:border-r-0">{row.customer_name}</td>
                <td
                  className={`border-b border-r border-[var(--admin-border)] px-4 py-4 align-middle last:border-r-0 ${
                    row.status === "Exception" ? "text-[var(--admin-danger)]" : ""
                  }`}
                >
                  {row.status}
                </td>
                <td className="border-b border-r border-[var(--admin-border)] px-4 py-4 align-middle last:border-r-0">{row.sla}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
