/**
 * TeamOrchestrator - Multi-Agent Team Orchestration UI
 *
 * Provides an interface for creating teams, assigning agents,
 * managing tasks, and monitoring collaboration workflows.
 *
 * @module components/TeamOrchestrator
 */

import { useState, useEffect } from 'react';
import { useTeamStore } from '../store/teamStore';
import { useGatewayStore } from '../store/gatewayStore';
import type {
  TeamMember,
  TeamTask,
  TeamMemberRole,
  TaskPriority,
  CollaborationPattern,
} from '../types/team';
import {
  Users, Plus, Trash2, X,
  Bot, Clock, AlertTriangle, CheckCircle,
  Play, UserPlus, FileText,
} from 'lucide-react';

// === Sub-Components ===

interface MemberCardProps {
  member: TeamMember;
  isSelected: boolean;
  onSelect: () => void;
  onRoleChange: (role: TeamMemberRole) => void;
  onRemove: () => void;
}

function MemberCard({ member, isSelected, onSelect, onRoleChange, onRemove }: MemberCardProps) {
  const [showRoleMenu, setShowRoleMenu] = useState(false);

  const roleColors: Record<TeamMemberRole, string> = {
    orchestrator: 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-300',
    developer: 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300',
    reviewer: 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300',
    tester: 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-300',
    architect: 'bg-indigo-100 text-indigo-700 dark:bg-indigo-900/30 dark:text-indigo-300',
    specialist: 'bg-pink-100 text-pink-700 dark:bg-pink-900/30 dark:text-pink-300',
  };

  const statusColors = {
    idle: 'bg-gray-400',
    running: 'bg-green-500 animate-pulse',
    paused: 'bg-yellow-500',
    error: 'bg-red-500',
  };

  return (
    <div
      className={`p-3 rounded-lg border cursor-pointer transition-all ${
        isSelected
          ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
          : 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
      }`}
      onClick={onSelect}
    >
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <div className={`w-2 h-2 rounded-full ${statusColors[member.status]}`} />
          <Bot className="w-4 h-4 text-gray-500" />
          <span className="font-medium text-gray-900 dark:text-white">{member.name}</span>
        </div>
        <div className="flex items-center gap-1">
          <button
            onClick={(e) => { e.stopPropagation(); setShowRoleMenu(!showRoleMenu); }}
            className={`px-2 py-0.5 rounded text-xs font-medium ${roleColors[member.role]}`}
          >
            {member.role}
          </button>
          <button
            onClick={(e) => { e.stopPropagation(); onRemove(); }}
            className="p-1 text-gray-400 hover:text-red-500"
          >
            <Trash2 className="w-3.5 h-3.5" />
          </button>
        </div>
      </div>

      {showRoleMenu && (
        <div className="mt-2 flex flex-wrap gap-1">
          {(['orchestrator', 'developer', 'reviewer', 'tester', 'architect', 'specialist'] as TeamMemberRole[]).map(role => (
            <button
              key={role}
              onClick={(e) => { e.stopPropagation(); onRoleChange(role); setShowRoleMenu(false); }}
              className={`px-2 py-0.5 rounded text-xs ${roleColors[role]} hover:opacity-80`}
            >
              {role}
            </button>
          ))}
        </div>
      )}

      <div className="mt-2 flex items-center gap-3 text-xs text-gray-500 dark:text-gray-400">
        <span>Workload: {member.workload}%</span>
        <span>Tasks: {member.currentTasks.length}</span>
      </div>
    </div>
  );
}

interface TaskCardProps {
  task: TeamTask;
  members: TeamMember[];
  isSelected: boolean;
  onSelect: () => void;
  onAssign: (memberId: string) => void;
  onStatusChange: (status: TeamTask['status']) => void;
}

function TaskCard({ task, members, isSelected, onSelect, onAssign, onStatusChange: _onStatusChange }: TaskCardProps) {
  const [showAssignMenu, setShowAssignMenu] = useState(false);

  const priorityColors: Record<TaskPriority, string> = {
    critical: 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300',
    high: 'bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-300',
    medium: 'bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-300',
    low: 'bg-gray-100 text-gray-700 dark:bg-gray-900/30 dark:text-gray-300',
  };

  const statusIcons: Record<TeamTask['status'], React.ReactNode> = {
    pending: <Clock className="w-4 h-4 text-gray-400" />,
    assigned: <UserPlus className="w-4 h-4 text-blue-400" />,
    in_progress: <Play className="w-4 h-4 text-green-400" />,
    review: <FileText className="w-4 h-4 text-yellow-400" />,
    blocked: <AlertTriangle className="w-4 h-4 text-red-400" />,
    completed: <CheckCircle className="w-4 h-4 text-green-500" />,
    failed: <X className="w-4 h-4 text-red-500" />,
  };

  const assignee = members.find(m => m.id === task.assigneeId);

  return (
    <div
      className={`p-3 rounded-lg border cursor-pointer transition-all ${
        isSelected
          ? 'border-blue-500 bg-blue-50 dark:bg-blue-900/20'
          : 'border-gray-200 dark:border-gray-700 hover:border-gray-300 dark:hover:border-gray-600'
      }`}
      onClick={onSelect}
    >
      <div className="flex items-start justify-between gap-2">
        <div className="flex-1">
          <div className="flex items-center gap-2">
            {statusIcons[task.status]}
            <span className="font-medium text-gray-900 dark:text-white">{task.title}</span>
          </div>
          {task.description && (
            <p className="mt-1 text-xs text-gray-500 dark:text-gray-400 line-clamp-2">
              {task.description}
            </p>
          )}
        </div>
        <span className={`px-2 py-0.5 rounded text-xs font-medium ${priorityColors[task.priority]}`}>
          {task.priority}
        </span>
      </div>

      <div className="mt-2 flex items-center justify-between">
        <div className="flex items-center gap-2">
          <button
            onClick={(e) => { e.stopPropagation(); setShowAssignMenu(!showAssignMenu); }}
            className={`px-2 py-1 rounded text-xs border ${
              assignee
                ? 'border-blue-200 bg-blue-50 text-blue-700 dark:border-blue-800 dark:bg-blue-900/30 dark:text-blue-300'
                : 'border-gray-200 text-gray-500 hover:border-gray-300 dark:border-gray-700 dark:text-gray-400'
            }`}
          >
            {assignee ? assignee.name : 'Assign...'}
          </button>
          <span className="text-xs text-gray-400">{task.type}</span>
        </div>
        {task.estimate && (
          <span className="text-xs text-gray-400">{task.estimate}pts</span>
        )}
      </div>

      {showAssignMenu && (
        <div className="mt-2 flex flex-wrap gap-1">
          {members.map(member => (
            <button
              key={member.id}
              onClick={(e) => { e.stopPropagation(); onAssign(member.id); setShowAssignMenu(false); }}
              className="px-2 py-1 rounded text-xs border border-gray-200 dark:border-gray-700 hover:bg-gray-100 dark:hover:bg-gray-800"
            >
              {member.name}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

// === Main Component ===

interface TeamOrchestratorProps {
  isOpen: boolean;
  onClose: () => void;
}

export function TeamOrchestrator({ isOpen, onClose }: TeamOrchestratorProps) {
  const [view, setView] = useState<'teams' | 'tasks' | 'members'>('teams');
  const [isCreating, setIsCreating] = useState(false);
  const [newTeamName, setNewTeamName] = useState('');
  const [newTeamPattern, setNewTeamPattern] = useState<CollaborationPattern>('sequential');

  const {
    teams,
    activeTeam,
    metrics,
    error,
    selectedTaskId,
    selectedMemberId,
    loadTeams,
    createTeam,
    deleteTeam,
    setActiveTeam,
    addTask,
    updateTaskStatus,
    assignTask,
    addMember,
    removeMember,
    updateMemberRole,
    setSelectedTask,
    setSelectedMember,
  } = useTeamStore();

  const { clones } = useGatewayStore();

  useEffect(() => {
    if (isOpen) {
      loadTeams();
    }
  }, [isOpen, loadTeams]);

  const handleCreateTeam = async () => {
    if (!newTeamName.trim()) return;
    const team = await createTeam({
      name: newTeamName.trim(),
      pattern: newTeamPattern,
      memberAgents: [],
    });
    if (team) {
      setActiveTeam(team);
      setNewTeamName('');
      setIsCreating(false);
    }
  };

  const handleAddMember = async (agentId: string) => {
    if (!activeTeam) return;
    await addMember(activeTeam.id, agentId, 'developer');
  };

  const handleAddTask = async () => {
    if (!activeTeam) return;
    await addTask({
      teamId: activeTeam.id,
      title: `Task ${activeTeam.tasks.length + 1}`,
      priority: 'medium',
      type: 'implementation',
    });
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50">
      <div className="bg-white dark:bg-gray-900 rounded-xl shadow-2xl w-[90vw] h-[85vh] flex flex-col overflow-hidden">
        {/* Header */}
        <div className="px-6 py-4 border-b border-gray-200 dark:border-gray-700 flex items-center justify-between">
          <div className="flex items-center gap-3">
            <Users className="w-6 h-6 text-blue-500" />
            <h2 className="text-xl font-bold text-gray-900 dark:text-white">Team Orchestrator</h2>
          </div>
          <div className="flex items-center gap-2">
            {metrics && (
              <div className="flex items-center gap-4 mr-4 text-sm text-gray-500 dark:text-gray-400">
                <span>Completed: {metrics.tasksCompleted}</span>
                <span>Pass Rate: {metrics.passRate.toFixed(0)}%</span>
                <span>Efficiency: {metrics.efficiency.toFixed(0)}%</span>
              </div>
            )}
            <button onClick={onClose} className="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg">
              <X className="w-5 h-5 text-gray-500" />
            </button>
          </div>
        </div>

        {/* Content */}
        <div className="flex-1 flex overflow-hidden">
          {/* Sidebar - Team List */}
          <div className="w-64 border-r border-gray-200 dark:border-gray-700 p-4 overflow-y-auto">
            <div className="flex items-center justify-between mb-4">
              <h3 className="font-semibold text-gray-900 dark:text-white">Teams</h3>
              <button
                onClick={() => setIsCreating(true)}
                className="p-1 hover:bg-gray-100 dark:hover:bg-gray-800 rounded"
              >
                <Plus className="w-4 h-4 text-gray-500" />
              </button>
            </div>

            {isCreating && (
              <div className="mb-4 p-3 bg-gray-50 dark:bg-gray-800 rounded-lg">
                <input
                  type="text"
                  value={newTeamName}
                  onChange={(e) => setNewTeamName(e.target.value)}
                  placeholder="Team name..."
                  className="w-full px-2 py-1 text-sm border rounded dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                />
                <select
                  value={newTeamPattern}
                  onChange={(e) => setNewTeamPattern(e.target.value as CollaborationPattern)}
                  className="w-full mt-2 px-2 py-1 text-sm border rounded dark:bg-gray-700 dark:border-gray-600 dark:text-white"
                >
                  <option value="sequential">Sequential</option>
                  <option value="parallel">Parallel</option>
                  <option value="pipeline">Pipeline</option>
                  <option value="review_loop">Dev↔QA Loop</option>
                </select>
                <div className="mt-2 flex gap-2">
                  <button
                    onClick={handleCreateTeam}
                    className="flex-1 px-2 py-1 text-xs bg-blue-500 text-white rounded hover:bg-blue-600"
                  >
                    Create
                  </button>
                  <button
                    onClick={() => setIsCreating(false)}
                    className="flex-1 px-2 py-1 text-xs border rounded hover:bg-gray-100 dark:hover:bg-gray-700"
                  >
                    Cancel
                  </button>
                </div>
              </div>
            )}

            <div className="space-y-2">
              {teams.map(team => (
                <div
                  key={team.id}
                  onClick={() => setActiveTeam(team)}
                  className={`p-3 rounded-lg cursor-pointer transition-all ${
                    activeTeam?.id === team.id
                      ? 'bg-blue-50 dark:bg-blue-900/30 border border-blue-200 dark:border-blue-800'
                      : 'hover:bg-gray-50 dark:hover:bg-gray-800'
                  }`}
                >
                  <div className="flex items-center justify-between">
                    <span className="font-medium text-gray-900 dark:text-white">{team.name}</span>
                    <button
                      onClick={(e) => { e.stopPropagation(); deleteTeam(team.id); }}
                      className="p-1 text-gray-400 hover:text-red-500"
                    >
                      <Trash2 className="w-3.5 h-3.5" />
                    </button>
                  </div>
                  <div className="mt-1 flex items-center gap-2 text-xs text-gray-500">
                    <Users className="w-3 h-3" />
                    <span>{team.members.length} members</span>
                    <span>·</span>
                    <span>{team.tasks.length} tasks</span>
                  </div>
                  <div className="mt-1">
                    <span className="px-1.5 py-0.5 text-xs bg-gray-100 dark:bg-gray-700 rounded">
                      {team.pattern}
                    </span>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Main Content */}
          {activeTeam ? (
            <div className="flex-1 flex flex-col overflow-hidden">
              {/* View Tabs */}
              <div className="px-6 py-3 border-b border-gray-200 dark:border-gray-700 flex items-center gap-4">
                <button
                  onClick={() => setView('tasks')}
                  className={`px-3 py-1.5 rounded-lg text-sm font-medium ${
                    view === 'tasks'
                      ? 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300'
                      : 'text-gray-500 hover:text-gray-700 dark:text-gray-400'
                  }`}
                >
                  Tasks
                </button>
                <button
                  onClick={() => setView('members')}
                  className={`px-3 py-1.5 rounded-lg text-sm font-medium ${
                    view === 'members'
                      ? 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300'
                      : 'text-gray-500 hover:text-gray-700 dark:text-gray-400'
                  }`}
                >
                  Members
                </button>
              </div>

              {/* Tasks View */}
              {view === 'tasks' && (
                <div className="flex-1 p-6 overflow-y-auto">
                  <div className="flex items-center justify-between mb-4">
                    <h3 className="font-semibold text-gray-900 dark:text-white">Tasks</h3>
                    <button
                      onClick={handleAddTask}
                      className="flex items-center gap-1 px-3 py-1.5 text-sm bg-blue-500 text-white rounded-lg hover:bg-blue-600"
                    >
                      <Plus className="w-4 h-4" />
                      Add Task
                    </button>
                  </div>

                  <div className="space-y-3">
                    {activeTeam.tasks.length === 0 ? (
                      <div className="text-center py-8 text-gray-500 dark:text-gray-400">
                        No tasks yet. Click "Add Task" to create one.
                      </div>
                    ) : (
                      activeTeam.tasks.map(task => (
                        <TaskCard
                          key={task.id}
                          task={task}
                          members={activeTeam.members}
                          isSelected={selectedTaskId === task.id}
                          onSelect={() => setSelectedTask(task.id)}
                          onAssign={(memberId) => assignTask(activeTeam.id, task.id, memberId)}
                          onStatusChange={(status) => updateTaskStatus(activeTeam.id, task.id, status)}
                        />
                      ))
                    )}
                  </div>
                </div>
              )}

              {/* Members View */}
              {view === 'members' && (
                <div className="flex-1 p-6 overflow-y-auto">
                  <div className="flex items-center justify-between mb-4">
                    <h3 className="font-semibold text-gray-900 dark:text-white">Members</h3>
                    <div className="flex items-center gap-2">
                      <select
                        className="px-3 py-1.5 text-sm border rounded-lg dark:bg-gray-800 dark:border-gray-700 dark:text-white"
                        onChange={(e) => handleAddMember(e.target.value)}
                        value=""
                      >
                        <option value="">Add Agent...</option>
                        {clones.map(clone => (
                          <option key={clone.id} value={clone.id}>
                            {clone.name || clone.nickname || clone.id}
                          </option>
                        ))}
                      </select>
                    </div>
                  </div>

                  <div className="grid grid-cols-2 gap-4">
                    {activeTeam.members.length === 0 ? (
                      <div className="col-span-2 text-center py-8 text-gray-500 dark:text-gray-400">
                        No members yet. Select an agent to add.
                      </div>
                    ) : (
                      activeTeam.members.map(member => (
                        <MemberCard
                          key={member.id}
                          member={member}
                          isSelected={selectedMemberId === member.id}
                          onSelect={() => setSelectedMember(member.id)}
                          onRoleChange={(role) => updateMemberRole(activeTeam.id, member.id, role)}
                          onRemove={() => removeMember(activeTeam.id, member.id)}
                        />
                      ))
                    )}
                  </div>
                </div>
              )}
            </div>
          ) : (
            <div className="flex-1 flex items-center justify-center text-gray-500 dark:text-gray-400">
              <div className="text-center">
                <Users className="w-12 h-12 mx-auto mb-4 text-gray-300 dark:text-gray-600" />
                <p>Select or create a team to get started</p>
              </div>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="px-6 py-3 border-t border-gray-200 dark:border-gray-700 flex items-center justify-between text-sm text-gray-500 dark:text-gray-400">
          <span>{teams.length} teams total</span>
          {error && <span className="text-red-500">{error}</span>}
        </div>
      </div>
    </div>
  );
}
