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";

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="p-8">
      <div className="mb-6 flex items-center justify-between gap-3">
        <h2 className="text-xl font-bold">Agents</h2>
        <Link
          to="/agents/new"
          className="rounded bg-blue-600 px-4 py-2 text-sm text-white hover:bg-blue-700"
        >
          New agent
        </Link>
      </div>

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

      {error && (
        <div className="mb-4 rounded border border-red-200 bg-red-50 p-2 text-sm text-red-600">
          {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="flex items-start justify-between gap-4 rounded-lg border border-gray-200 bg-white p-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>

            <div className="flex shrink-0 items-center gap-2">
              <Link
                to={`/agents/${agent.id}/edit`}
                className="rounded bg-gray-200 px-3 py-1 text-xs text-gray-700 hover:bg-gray-300"
              >
                Edit
              </Link>
              {!agent.is_default && (
                <button
                  type="button"
                  onClick={() => setAgentToDelete(agent)}
                  className="rounded bg-red-100 px-3 py-1 text-xs text-red-700 hover:bg-red-200"
                >
                  Delete
                </button>
              )}
            </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>
  );
}
