'use client';

/**
 * Project Agents Page
 *
 * Displays and manages agents assigned to a specific project.
 * Shows agent status, current tasks, and provides management controls.
 *
 * @module app/[locale]/(authenticated)/projects/[id]/agents/page
 */

import { use, useCallback } from 'react';
import { useRouter } from '@/lib/i18n/routing';
import { ArrowLeft, Bot, Plus, Settings2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { cn } from '@/lib/utils';

interface ProjectAgentsPageProps {
  params: Promise<{
    locale: string;
    id: string;
  }>;
}

type AgentStatus = 'working' | 'idle' | 'waiting' | 'error' | 'terminated';

interface MockAgent {
  id: string;
  name: string;
  role: string;
  status: AgentStatus;
  current_task: string;
  last_activity_at: string;
  avatar: string;
}

// Mock agents data - will be replaced with API calls
const mockAgents: MockAgent[] = [
  {
    id: 'agent-001',
    name: 'Product Owner',
    role: 'product_owner',
    status: 'working',
    current_task: 'Reviewing user story acceptance criteria',
    last_activity_at: new Date(Date.now() - 2 * 60 * 1000).toISOString(),
    avatar: 'PO',
  },
  {
    id: 'agent-002',
    name: 'Architect',
    role: 'architect',
    status: 'working',
    current_task: 'Designing API contract for checkout flow',
    last_activity_at: new Date(Date.now() - 5 * 60 * 1000).toISOString(),
    avatar: 'AR',
  },
  {
    id: 'agent-003',
    name: 'Backend Engineer',
    role: 'backend_engineer',
    status: 'idle',
    current_task: 'Waiting for architecture review',
    last_activity_at: new Date(Date.now() - 15 * 60 * 1000).toISOString(),
    avatar: 'BE',
  },
  {
    id: 'agent-004',
    name: 'Frontend Engineer',
    role: 'frontend_engineer',
    status: 'working',
    current_task: 'Implementing product catalog component',
    last_activity_at: new Date(Date.now() - 1 * 60 * 1000).toISOString(),
    avatar: 'FE',
  },
  {
    id: 'agent-005',
    name: 'QA Engineer',
    role: 'qa_engineer',
    status: 'waiting',
    current_task: 'Preparing test cases for Sprint 3',
    last_activity_at: new Date(Date.now() - 30 * 60 * 1000).toISOString(),
    avatar: 'QA',
  },
];

const statusColors = {
  working: 'bg-green-500',
  idle: 'bg-yellow-500',
  waiting: 'bg-blue-500',
  error: 'bg-red-500',
  terminated: 'bg-gray-500',
};

const statusLabels = {
  working: 'Working',
  idle: 'Idle',
  waiting: 'Waiting',
  error: 'Error',
  terminated: 'Terminated',
};

function formatTimeAgo(timestamp: string): string {
  const now = new Date();
  const then = new Date(timestamp);
  const diffMs = now.getTime() - then.getTime();
  const diffMins = Math.floor(diffMs / (1000 * 60));

  if (diffMins < 1) return 'Just now';
  if (diffMins < 60) return `${diffMins}m ago`;

  const diffHours = Math.floor(diffMins / 60);
  if (diffHours < 24) return `${diffHours}h ago`;

  const diffDays = Math.floor(diffHours / 24);
  return `${diffDays}d ago`;
}

export default function ProjectAgentsPage({ params }: ProjectAgentsPageProps) {
  const { id: projectId } = use(params);
  const router = useRouter();

  const handleBack = useCallback(() => {
    router.push(`/projects/${projectId}`);
  }, [router, projectId]);

  const handleAgentClick = useCallback(
    (agentId: string) => {
      router.push(`/projects/${projectId}/agents/${agentId}`);
    },
    [router, projectId]
  );

  const handleSpawnAgent = useCallback(() => {
    // TODO: Open spawn agent dialog
    console.log('Spawn agent clicked');
  }, []);

  const handleConfigureAgents = useCallback(() => {
    router.push('/agents');
  }, [router]);

  return (
    <div className="container mx-auto px-4 py-6">
      <div className="space-y-6">
        {/* Header */}
        <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
          <div className="flex items-center gap-4">
            <Button variant="ghost" size="icon" onClick={handleBack}>
              <ArrowLeft className="h-4 w-4" />
            </Button>
            <div>
              <h1 className="text-3xl font-bold">Project Agents</h1>
              <p className="text-muted-foreground">
                {mockAgents.length} agents assigned to this project
              </p>
            </div>
          </div>
          <div className="flex gap-2">
            <Button variant="outline" size="sm" onClick={handleConfigureAgents}>
              <Settings2 className="mr-2 h-4 w-4" aria-hidden="true" />
              Configure Agent Types
            </Button>
            <Button size="sm" onClick={handleSpawnAgent}>
              <Plus className="mr-2 h-4 w-4" aria-hidden="true" />
              Spawn Agent
            </Button>
          </div>
        </div>

        {/* Agent Grid */}
        <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
          {mockAgents.map((agent) => (
            <Card
              key={agent.id}
              className="cursor-pointer transition-shadow hover:shadow-md"
              onClick={() => handleAgentClick(agent.id)}
            >
              <CardHeader className="pb-3">
                <div className="flex items-start justify-between">
                  <div className="flex items-center gap-3">
                    <Avatar className="h-10 w-10">
                      <AvatarFallback className="bg-primary/10 text-primary">
                        {agent.avatar}
                      </AvatarFallback>
                    </Avatar>
                    <div>
                      <CardTitle className="text-base">{agent.name}</CardTitle>
                      <CardDescription className="text-xs capitalize">
                        {agent.role.replace(/_/g, ' ')}
                      </CardDescription>
                    </div>
                  </div>
                  <Badge
                    variant="outline"
                    className={cn(
                      'flex items-center gap-1.5',
                      agent.status === 'working' && 'border-green-200 text-green-700',
                      agent.status === 'idle' && 'border-yellow-200 text-yellow-700',
                      agent.status === 'waiting' && 'border-blue-200 text-blue-700',
                      agent.status === 'error' && 'border-red-200 text-red-700'
                    )}
                  >
                    <span
                      className={cn('h-2 w-2 rounded-full', statusColors[agent.status])}
                      aria-hidden="true"
                    />
                    {statusLabels[agent.status]}
                  </Badge>
                </div>
              </CardHeader>
              <CardContent>
                <div className="space-y-2">
                  <p className="text-sm text-muted-foreground line-clamp-2">{agent.current_task}</p>
                  <p className="text-xs text-muted-foreground">
                    Last active: {formatTimeAgo(agent.last_activity_at)}
                  </p>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>

        {/* Empty State */}
        {mockAgents.length === 0 && (
          <Card className="py-12 text-center">
            <CardContent>
              <Bot className="mx-auto h-12 w-12 text-muted-foreground/50" />
              <h3 className="mt-4 text-lg font-semibold">No agents assigned</h3>
              <p className="mt-2 text-sm text-muted-foreground">
                Spawn agents to start working on this project
              </p>
              <Button className="mt-4" onClick={handleSpawnAgent}>
                <Plus className="mr-2 h-4 w-4" aria-hidden="true" />
                Spawn First Agent
              </Button>
            </CardContent>
          </Card>
        )}
      </div>
    </div>
  );
}
