"use client";

import Link from "next/link";
import { startTransition, useEffect, useState } from "react";
import { AgentAvatar } from "@/components/agents/agent-avatar";
import { AgentFeed, AgentStatus } from "@/types/agent";

const statusClassMap = {
  working: "status-pill status-pill--working",
  idle: "status-pill status-pill--idle",
  warning: "status-pill status-pill--warning",
  offline: "status-pill status-pill--offline"
} as const;

type AgentsDashboardProps = {
  initialFeed: AgentFeed;
  initialStatus: "all" | AgentStatus;
};

function isAgentStatus(value: string): value is AgentStatus {
  return value === "working" || value === "idle" || value === "warning" || value === "offline";
}

function formatTimeLabel(value: string) {
  return new Date(value).toLocaleTimeString("zh-CN", {
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit"
  });
}

export function AgentsDashboard({ initialFeed, initialStatus }: AgentsDashboardProps) {
  const [feed, setFeed] = useState(initialFeed);

  useEffect(() => {
    let mounted = true;

    async function loadAgents() {
      const query = initialStatus === "all" ? "" : `?status=${initialStatus}`;
      const response = await fetch(`/api/agents${query}`, { cache: "no-store" });

      if (!response.ok) {
        throw new Error("Failed to load agents");
      }

      const data = (await response.json()) as AgentFeed;

      if (!mounted) {
        return;
      }

      startTransition(() => {
        setFeed(data);
      });
    }

    loadAgents().catch(() => undefined);
    const interval = window.setInterval(() => {
      loadAgents().catch(() => undefined);
    }, 10000);

    return () => {
      mounted = false;
      window.clearInterval(interval);
    };
  }, [initialStatus]);

  const agents = feed.agents;
  const counts = {
    working: agents.filter((agent) => agent.status === "working").length,
    idle: agents.filter((agent) => agent.status === "idle").length,
    warning: agents.filter((agent) => agent.status === "warning").length,
    offline: agents.filter((agent) => agent.status === "offline").length
  };

  return (
    <section className="agents-shell agents-shell--compact">
      <div className="agents-monitor-top">
        <div className="agents-monitor-source">
          <strong>{feed.source === "file" ? "已接入真实数据源" : "当前使用演示数据"}</strong>
          <span>
            来源 {feed.sourceLabel} · 最近刷新 {formatTimeLabel(feed.fetchedAt)}
          </span>
        </div>

        <div className="agents-monitor-controls">
          <div className="agents-monitor-summary" aria-label="Agent 状态统计">
            <div className="agents-monitor-summary__item">
              <strong>{agents.length}</strong>
              <span>全部</span>
            </div>
            <div className="agents-monitor-summary__item agents-monitor-summary__item--working">
              <strong>{counts.working}</strong>
              <span>工作中</span>
            </div>
            <div className="agents-monitor-summary__item agents-monitor-summary__item--idle">
              <strong>{counts.idle}</strong>
              <span>待命</span>
            </div>
            <div className="agents-monitor-summary__item agents-monitor-summary__item--warning">
              <strong>{counts.warning}</strong>
              <span>待确认</span>
            </div>
            <div className="agents-monitor-summary__item agents-monitor-summary__item--offline">
              <strong>{counts.offline}</strong>
              <span>离线</span>
            </div>
          </div>

        </div>
      </div>

      <div className="agents-worklist">
        {agents.map((agent) => (
          <Link className="agents-worklist__link" href={`/agents/${agent.id}`} key={agent.id}>
            <article className="agents-workitem">
              <div className="agents-workitem__head">
                <div className="agents-workitem__identity">
                  <AgentAvatar kind={agent.avatarKind} label={agent.name} />
                  <div>
                    <div className="agents-workitem__name-row">
                      <strong>{agent.name}</strong>
                      <span className={statusClassMap[agent.status]}>{agent.statusLabel}</span>
                    </div>
                    <div className="agents-workitem__role">{agent.role}</div>
                  </div>
                </div>

                <div className="agents-workitem__metrics">
                  <span>心跳 {agent.lastHeartbeat}</span>
                  <span>队列 {agent.queueDepth}</span>
                  <span>今日完成 {agent.todayCompleted}</span>
                </div>
              </div>

              <div className="agents-workitem__task">
                <div className="agents-workitem__label">当前任务</div>
                <div className="agents-workitem__value">{agent.currentTask}</div>
              </div>

              <div className="agents-workitem__meta">
                <span>任务ID {agent.taskId}</span>
                <span>阶段 {agent.taskStage}</span>
                <span>主机 {agent.host}</span>
                <span>Owner {agent.owner}</span>
                <span>运行时长 {agent.uptime}</span>
                <span>更新时间 {agent.updatedAt}</span>
              </div>

              <div className="agents-workitem__output">
                <div className="agents-workitem__label">最近输出</div>
                <div className="agents-workitem__value">{agent.lastOutput}</div>
                {agent.lastError ? <div className="agents-workitem__error">异常: {agent.lastError}</div> : null}
              </div>
            </article>
          </Link>
        ))}
      </div>
    </section>
  );
}
