import { useState, type FormEvent } from 'react';
import { Users, X } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import type { UseAgentPanelType } from './useAgentPanel';

type AgentIdentityBarProps = { panel: UseAgentPanelType };

/**
 * One line above the transcript saying which agent this panel is, or offering to make it one.
 *
 * It renders only on a real dashboard — see `useAgentPanel`. A named panel is a *different thing* from
 * an anonymous chat: it keeps one session forever, it is addressable by its peers, and work can arrive
 * in it while nobody is looking. That is worth a line of chrome, because otherwise the only way to tell
 * the two apart is to notice that the conversation did not reset.
 */
export const AgentIdentityBar = ({ panel }: AgentIdentityBarProps) => {
  const [naming, setNaming] = useState(false);
  const [name, setName] = useState('');
  const [error, setError] = useState<string | null>(null);

  if (!panel.addressable || panel.isLoading) return null;

  const submit = async (ev: FormEvent) => {
    ev.preventDefault();
    setError(null);
    try {
      await panel.claim.mutateAsync({ name: name.trim().toLowerCase() });
      setNaming(false);
      setName('');
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    }
  };

  if (naming) {
    return (
      <form onSubmit={submit} className="flex items-center gap-1.5 border-b px-2 py-1.5">
        <Users className="text-muted-foreground h-3.5 w-3.5 shrink-0" />
        <Input
          autoFocus
          value={name}
          onChange={(ev) => setName(ev.target.value)}
          placeholder="frontend"
          className="h-6 flex-1 text-xs"
          onKeyDown={(ev) => {
            if (ev.key === 'Escape') setNaming(false);
          }}
        />
        <Button type="submit" size="sm" className="h-6 px-2 text-xs" disabled={!name.trim() || panel.claim.isPending}>
          {panel.claim.isPending ? 'Naming…' : 'Name'}
        </Button>
        <Button
          type="button"
          size="sm"
          variant="ghost"
          className="h-6 w-6 p-0"
          onClick={() => setNaming(false)}
          aria-label="Cancel"
        >
          <X className="h-3 w-3" />
        </Button>
        {error ? <span className="text-destructive max-w-[50%] truncate text-xs">{error}</span> : null}
      </form>
    );
  }

  if (panel.orphaned) {
    return (
      <div className="text-muted-foreground flex items-center gap-1.5 border-b px-2 py-1.5 text-xs">
        <Users className="h-3.5 w-3.5 shrink-0" />
        <span className="flex-1 truncate">This panel's agent no longer exists.</span>
        <Button size="sm" variant="ghost" className="h-6 px-2 text-xs" onClick={panel.release}>
          Forget it
        </Button>
      </div>
    );
  }

  if (!panel.agent) {
    return (
      <div className="flex items-center gap-1.5 border-b px-2 py-1.5">
        <Button
          size="sm"
          variant="ghost"
          className="text-muted-foreground h-6 px-1.5 text-xs"
          onClick={() => setNaming(true)}
        >
          <Users className="mr-1 h-3.5 w-3.5" />
          Name this agent
        </Button>
      </div>
    );
  }

  const peers = panel.agents.filter((a) => a.id !== panel.agent!.id);

  return (
    <div className="flex items-center gap-1.5 border-b px-2 py-1.5 text-xs">
      <span className="bg-primary h-1.5 w-1.5 shrink-0 rounded-full" aria-hidden />
      <span className="font-medium">{panel.agent.name}</span>
      <span
        className="text-muted-foreground flex-1 truncate"
        title={peers.length ? `Peers: ${peers.map((p) => p.name).join(', ')}` : undefined}
      >
        {peers.length === 0
          ? 'no peers yet'
          : peers.length === 1
            ? `1 peer: ${peers[0]!.name}`
            : `${peers.length} peers`}
      </span>
    </div>
  );
};
