"use client";

import { useState } from "react";
import { useScopeEffect } from "@/lib/company-scope";
import { CompanyNameTag } from "@/components/shared/CompanyNameTag";
import { listAgentExecutions, reviewAgentExecution } from "@/lib/api-v2";
import { PageContainer, Badge} from "@/components/shared/PageContainer";
import { LoadingSpinner } from "@/components/shared/LoadingSpinner";
import { EmptyState } from "@/components/shared/EmptyState";
import { toast } from "sonner";

/** Agent 执行记录项。 */
interface AgentExecution {
  id: string;
  company_id?: string;
  agent_name: string;
  autonomy_level: string;
  output_summary: string;
  duration_ms?: number;
  review_status: string;
}

export default function AgentsPage() {
  const [items, setItems] = useState<AgentExecution[]>([]);
  const [isLoading, setIsLoading] = useState(true);

  const load = () => {
    listAgentExecutions()
      .then((resp) => setItems((resp.data as AgentExecution[]) ?? []))
      .catch(() => setItems([]))
      .finally(() => setIsLoading(false));
  };

  useScopeEffect(() => { load(); });

  const handleReview = async (id: string, status: string) => {
    try {
      await reviewAgentExecution(id, status);
      toast.success("审核完成");
      load();
    } catch {
      toast.error("审核失败");
    }
  };

  return (
    <PageContainer title="Agent 监控" description="L1-L4 分级自治执行 + 人工审核">
      {isLoading ? (
        <LoadingSpinner />
      ) : items.length === 0 ? (
        <EmptyState description="暂无 Agent 执行记录" />
      ) : (
        <div className="overflow-x-auto rounded-lg border border-gray-200">
          <table className="min-w-full divide-y divide-gray-200 text-sm">
            <thead className="bg-gray-50">
              <tr>
                <th className="px-4 py-2 text-left font-medium text-gray-500">企业</th>
                <th className="px-4 py-2 text-left font-medium text-gray-500">Agent</th>
                <th className="px-4 py-2 text-left font-medium text-gray-500">自治级别</th>
                <th className="px-4 py-2 text-left font-medium text-gray-500">输出摘要</th>
                <th className="px-4 py-2 text-left font-medium text-gray-500">耗时</th>
                <th className="px-4 py-2 text-left font-medium text-gray-500">审核状态</th>
                <th className="px-4 py-2 text-left font-medium text-gray-500">操作</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-100 bg-white">
              {items.map((item, i) => (
                <tr key={i}>
                  <td className="px-4 py-2"><CompanyNameTag companyId={item.company_id} /></td>
                  <td className="px-4 py-2 text-gray-900">{item.agent_name}</td>
                  <td className="px-4 py-2"><Badge color={item.autonomy_level === "L4" ? "red" : item.autonomy_level === "L3" ? "amber" : "blue"}>{item.autonomy_level}</Badge></td>
                  <td className="px-4 py-2 text-gray-600 max-w-xs truncate">{item.output_summary}</td>
                  <td className="px-4 py-2 text-gray-500">{item.duration_ms ? `${item.duration_ms}ms` : "-"}</td>
                  <td className="px-4 py-2">
                    <Badge color={item.review_status === "approved" ? "green" : item.review_status === "rejected" ? "red" : "amber"}>
                      {item.review_status}
                    </Badge>
                  </td>
                  <td className="px-4 py-2">
                    {item.review_status === "pending" && (
                      <div className="flex gap-1">
                        <button
                          onClick={() => handleReview(item.id, "approved")}
                          className="rounded bg-emerald-600 px-2 py-0.5 text-xs text-white hover:bg-emerald-700"
                        >
                          批准
                        </button>
                        <button
                          onClick={() => handleReview(item.id, "rejected")}
                          className="rounded bg-rose-600 px-2 py-0.5 text-xs text-white hover:bg-rose-700"
                        >
                          拒绝
                        </button>
                      </div>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </PageContainer>
  );
}
