import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { deleteAgent, listAgents } from "../../lib/api";
import { getErrorMessage } from "../../lib/errors";
import type { Agent } from "../../lib/types";
import ConfirmModal from "../ui/ConfirmModal";
import {
  buttonClass,
  cardContentClass,
  noticeClass,
  pageClass,
  pageTitleClass,
} from "../ui/primitives";

export default function AgentList() {
  const [agents, setAgents] = useState<Agent[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [agentToDelete, setAgentToDelete] = useState<Agent | null>(null);
  const [deleting, setDeleting] = useState(false);

  async function refresh() {
    setError(null);
    try {
      const result = await listAgents();
      setAgents(result);
    } catch (err: unknown) {
      setError(getErrorMessage(err));
    } finally {
      setLoading(false);
    }
  }

  useEffect(() => {
    void refresh();
  }, []);

  async function handleDelete() {
    if (!agentToDelete) return;
    setDeleting(true);
    setError(null);
    try {
      await deleteAgent(agentToDelete.id);
      setAgentToDelete(null);
      await refresh();
    } catch (err: unknown) {
      setError(getErrorMessage(err));
    } finally {
      setDeleting(false);
    }
  }

  function roleLabel(role: Agent["role"]): string {
    return role === "analyst" ? "Analyst" : "Developer";
  }

  function toolLabel(tool: Agent["tool"]): string {
    return tool === "codex" ? "Codex" : "Claude Code";
  }

  return (
    <div className={pageClass}>
      <div className="mb-6 flex items-center justify-between gap-3">
        <h2 className={pageTitleClass}>Agents</h2>
        <Link to="/agents/new" className={buttonClass({ variant: "primary" })}>
          New agent
        </Link>
      </div>

      {loading && <div className="text-sm text-gray-400">Loading...</div>}

      {error && (
        <div className={`mb-4 ${noticeClass("error", true)}`}>
          {error}
        </div>
      )}

      {!loading && agents.length === 0 && (
        <div className="text-sm text-gray-400">No agents configured.</div>
      )}

      <div className="space-y-3">
        {agents.map((agent) => (
          <div
            key={agent.id}
            className={`group relative transition hover:border-blue-300 hover:shadow-sm focus-within:border-blue-400 focus-within:ring-2 focus-within:ring-blue-100 ${cardContentClass}`}
          >
            <Link
              to={`/agents/${agent.id}/edit`}
              aria-label={`Edit ${agent.name}`}
              className="absolute inset-0 rounded-lg focus-visible:outline-none"
            />

            <div className="pointer-events-none relative z-10 flex items-start justify-between gap-4">
              <div className="min-w-0 flex-1">
                <div className="flex items-center gap-2">
                  <span className="text-sm font-medium">{agent.name}</span>
                  {agent.is_default && (
                    <span className="rounded-full bg-emerald-100 px-2 py-0.5 text-xs text-emerald-700">
                      Default
                    </span>
                  )}
                  <span className="rounded-full bg-gray-100 px-2 py-0.5 text-xs text-gray-600">
                    {roleLabel(agent.role)}
                  </span>
                  <span className="rounded-full bg-blue-50 px-2 py-0.5 text-xs text-blue-700">
                    {toolLabel(agent.tool)}
                  </span>
                </div>
                {agent.custom_prompt.trim() ? (
                  <p className="mt-2 line-clamp-3 text-xs text-gray-500">
                    {agent.custom_prompt}
                  </p>
                ) : (
                  <p className="mt-2 text-xs text-gray-400">No custom prompt.</p>
                )}
              </div>

              {!agent.is_default && (
                <div className="pointer-events-auto shrink-0">
                  <button
                    type="button"
                    onClick={() => setAgentToDelete(agent)}
                    className={buttonClass({ variant: "dangerSoft", size: "xs" })}
                  >
                    Delete
                  </button>
                </div>
              )}
            </div>
          </div>
        ))}
      </div>

      <ConfirmModal
        isOpen={agentToDelete !== null}
        title="Delete agent"
        message="Delete this agent? Trackers using it will be reassigned to the default agent for the same role."
        confirmLabel={deleting ? "Deleting..." : "Delete"}
        confirmDisabled={deleting}
        onCancel={() => {
          if (!deleting) setAgentToDelete(null);
        }}
        onConfirm={() => void handleDelete()}
      />
    </div>
  );
}
