import { cn } from '@/lib/utils';
import { Activity, Bot, Cpu, Pause, UserX } from 'lucide-react';
import type React from 'react';

export interface AgentPhaseAssignment {
  agentId: string;
  agentName: string;
  agentStatus: 'idle' | 'running' | 'paused' | 'error';
  phaseId: string;
  phaseName: string;
  taskId?: string | undefined;
  taskTitle?: string | undefined;
  startedAt: number;
}

export interface PhaseAgentsMonitorProps {
  assignments: AgentPhaseAssignment[];
  /** Agent counts per phase */
  phaseAgentCounts: Array<{ phaseId: string; phaseName: string; count: number; status: string }>;
  /** Total agent count */
  totalAgents: number;
  /** Active running agent count */
  activeAgents: number;
  /** Remove agent from phase */
  onReleaseAgent?: (agentId: string, phaseId: string) => void;
  /** Assign agent to phase */
  onAssignAgent?: (agentId: string, phaseId: string) => void;
  className?: string | undefined;
}

const AGENT_STATUS_CONFIG: Record<
  AgentPhaseAssignment['agentStatus'],
  { icon: React.ReactNode; color: string; label: string }
> = {
  idle: { icon: <Pause className="w-3 h-3" />, color: 'text-muted-foreground', label: 'Idle' },
  running: { icon: <Activity className="w-3 h-3" />, color: 'text-[hsl(var(--success))]', label: 'Running' },
  paused: { icon: <Pause className="w-3 h-3" />, color: 'text-[hsl(var(--warning))]', label: 'Paused' },
  error: { icon: <Cpu className="w-3 h-3" />, color: 'text-destructive', label: 'Error' },
};

function formatDuration(ms: number): string {
  const m = Math.floor(ms / 60000);
  if (m < 60) return `${m}m`;
  const h = Math.floor(m / 60);
  const rem = m % 60;
  return rem > 0 ? `${h}h ${rem}m` : `${h}h`;
}

/**
 * PhaseAgentsMonitor — Shows which agents are working on each phase.
 *
 * Differs from the fleet monitor: phase-based grouping and agent assignment/release.
 */
export function PhaseAgentsMonitor({
  assignments,
  phaseAgentCounts,
  totalAgents,
  activeAgents,
  onReleaseAgent,
  className,
}: PhaseAgentsMonitorProps): React.ReactElement {
  return (
    <div className={cn('flex flex-col h-full w-64 border-l border-border bg-card', className)}>
      {/* Header */}
      <div className="p-4 border-b border-border">
        <div className="flex items-center justify-between mb-2">
          <h2 className="text-sm font-semibold text-foreground flex items-center gap-1.5">
            <Bot className="w-4 h-4" />
            Agents
          </h2>
        </div>
        <div className="flex gap-3 text-xs">
          <div>
            <span className="text-muted-foreground">Total:</span>{' '}
            <span className="font-medium">{totalAgents}</span>
          </div>
          <div>
            <span className="text-muted-foreground">Active:</span>{' '}
            <span className="font-medium text-[hsl(var(--success))]">{activeAgents}</span>
          </div>
        </div>
      </div>

      {/* Phase Agent Counts */}
      <div className="p-3 border-b border-border">
        <h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2">
          By Phase
        </h3>
        <div className="space-y-1.5">
          {phaseAgentCounts.map((pac) => (
            <div
              key={pac.phaseId}
              className="flex items-center justify-between text-xs rounded px-2 py-1 bg-muted/50"
            >
              <span className="truncate max-w-[120px]">{pac.phaseName}</span>
              <div className="flex items-center gap-1.5">
                <span className="font-medium">{pac.count}</span>
                <span
                  className={cn(
                    'led',
                    pac.status === 'running' ? 'text-[hsl(var(--success))] led-pulse' :
                    pac.status === 'completed' ? 'text-muted-foreground' :
                    'text-[hsl(var(--warning))]',
                  )}
                />
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Active Assignments */}
      <div className="flex-1 overflow-y-auto p-3">
        <h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2">
          Active Assignments
        </h3>
        <div className="space-y-2">
          {assignments.map((a) => {
            const status = AGENT_STATUS_CONFIG[a.agentStatus];
            return (
              <div
                key={`${a.agentId}-${a.phaseId}`}
                className="rounded-lg border border-border p-2.5 bg-background"
              >
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-1.5">
                    <Bot className="w-3.5 h-3.5 text-muted-foreground" />
                    <span className="text-xs font-medium">{a.agentName}</span>
                  </div>
                  <span className={cn('flex items-center gap-1', status.color)}>
                    {status.icon}
                    <span className="text-[10px]">{status.label}</span>
                  </span>
                </div>

                <div className="mt-1.5 text-[11px] text-muted-foreground">
                  <div className="truncate">{a.phaseName}</div>
                  {a.taskTitle && (
                    <div className="truncate mt-0.5 text-primary">→ {a.taskTitle}</div>
                  )}
                  <div className="mt-1">
                    {formatDuration(Date.now() - a.startedAt)}
                  </div>
                </div>

                {/* Actions */}
                <div className="flex gap-1 mt-2">
                  {onReleaseAgent && (
                    <button
                      type="button"
                      onClick={() => onReleaseAgent(a.agentId, a.phaseId)}
                      className="flex items-center gap-1 px-2 py-0.5 text-[10px] rounded bg-destructive/15 text-destructive hover:bg-destructive/25 transition-colors"
                    >
                      <UserX className="w-3 h-3" />
                      Release
                    </button>
                  )}
                </div>
              </div>
            );
          })}

          {assignments.length === 0 && (
            <div className="text-center text-xs text-muted-foreground py-4">
              No active agent assignments
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
