/**
 * AgentTypeList Component
 *
 * Displays a grid of agent type cards with search and filter functionality.
 * Used on the main agent types page for browsing and selecting agent types.
 */

'use client';

import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Separator } from '@/components/ui/separator';
import { Skeleton } from '@/components/ui/skeleton';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Bot, Plus, Search, Cpu } from 'lucide-react';
import type { AgentTypeResponse } from '@/lib/api/types/agentTypes';

interface AgentTypeListProps {
  agentTypes: AgentTypeResponse[];
  isLoading?: boolean;
  searchQuery: string;
  onSearchChange: (query: string) => void;
  statusFilter: string;
  onStatusFilterChange: (status: string) => void;
  onSelect: (id: string) => void;
  onCreate: () => void;
  className?: string;
}

/**
 * Status badge component for agent types
 */
function AgentTypeStatusBadge({ isActive }: { isActive: boolean }) {
  if (isActive) {
    return (
      <Badge
        className="bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200"
        variant="outline"
      >
        Active
      </Badge>
    );
  }
  return (
    <Badge
      className="bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200"
      variant="outline"
    >
      Inactive
    </Badge>
  );
}

/**
 * Loading skeleton for agent type cards
 */
function AgentTypeCardSkeleton() {
  return (
    <Card className="h-[200px]">
      <CardHeader className="pb-3">
        <div className="flex items-start justify-between">
          <Skeleton className="h-10 w-10 rounded-lg" />
          <Skeleton className="h-5 w-16" />
        </div>
        <Skeleton className="mt-3 h-6 w-3/4" />
        <Skeleton className="mt-2 h-4 w-full" />
      </CardHeader>
      <CardContent>
        <div className="space-y-3">
          <div className="flex flex-wrap gap-1">
            <Skeleton className="h-5 w-16" />
            <Skeleton className="h-5 w-20" />
            <Skeleton className="h-5 w-14" />
          </div>
          <Separator />
          <div className="flex items-center justify-between">
            <Skeleton className="h-4 w-24" />
            <Skeleton className="h-4 w-20" />
          </div>
        </div>
      </CardContent>
    </Card>
  );
}

/**
 * Extract model display name from model ID
 */
function getModelDisplayName(modelId: string): string {
  const parts = modelId.split('-');
  if (parts.length >= 2) {
    return parts.slice(0, 2).join(' ').replace('claude', 'Claude');
  }
  /* istanbul ignore next -- fallback for short model IDs */
  return modelId;
}

export function AgentTypeList({
  agentTypes,
  isLoading = false,
  searchQuery,
  onSearchChange,
  statusFilter,
  onStatusFilterChange,
  onSelect,
  onCreate,
  className,
}: AgentTypeListProps) {
  return (
    <div className={className}>
      {/* Header */}
      <div className="mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-3xl font-bold">Agent Types</h1>
          <p className="text-muted-foreground">
            Configure templates for spawning AI agent instances
          </p>
        </div>
        <Button onClick={onCreate}>
          <Plus className="mr-2 h-4 w-4" />
          Create Agent Type
        </Button>
      </div>

      {/* Filters */}
      <div className="mb-6 flex flex-col gap-4 sm:flex-row">
        <div className="relative flex-1">
          <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
          <Input
            placeholder="Search agent types..."
            value={searchQuery}
            onChange={(e) => onSearchChange(e.target.value)}
            className="pl-9"
            aria-label="Search agent types"
          />
        </div>
        <Select value={statusFilter} onValueChange={onStatusFilterChange}>
          <SelectTrigger className="w-full sm:w-40" aria-label="Filter by status">
            <SelectValue placeholder="Status" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Status</SelectItem>
            <SelectItem value="active">Active</SelectItem>
            <SelectItem value="inactive">Inactive</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* Loading State */}
      {isLoading && (
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {[1, 2, 3, 4, 5, 6].map((i) => (
            <AgentTypeCardSkeleton key={i} />
          ))}
        </div>
      )}

      {/* Agent Type Grid */}
      {!isLoading && agentTypes.length > 0 && (
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {agentTypes.map((type) => (
            <Card
              key={type.id}
              className="cursor-pointer transition-all hover:border-primary hover:shadow-md"
              onClick={() => onSelect(type.id)}
              role="button"
              tabIndex={0}
              onKeyDown={(e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                  e.preventDefault();
                  onSelect(type.id);
                }
              }}
              aria-label={`View ${type.name} agent type`}
            >
              <CardHeader className="pb-3">
                <div className="flex items-start justify-between">
                  <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10">
                    <Bot className="h-5 w-5 text-primary" />
                  </div>
                  <AgentTypeStatusBadge isActive={type.is_active} />
                </div>
                <CardTitle className="mt-3">{type.name}</CardTitle>
                <CardDescription className="line-clamp-2">
                  {type.description || 'No description provided'}
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  {/* Expertise tags */}
                  <div className="flex flex-wrap gap-1">
                    {type.expertise.slice(0, 3).map((skill) => (
                      <Badge key={skill} variant="secondary" className="text-xs">
                        {skill}
                      </Badge>
                    ))}
                    {type.expertise.length > 3 && (
                      <Badge variant="outline" className="text-xs">
                        +{type.expertise.length - 3}
                      </Badge>
                    )}
                    {type.expertise.length === 0 && (
                      <span className="text-xs text-muted-foreground">No expertise defined</span>
                    )}
                  </div>

                  <Separator />

                  {/* Metadata */}
                  <div className="flex items-center justify-between text-sm text-muted-foreground">
                    <div className="flex items-center gap-1">
                      <Cpu className="h-3.5 w-3.5" />
                      <span className="text-xs">{getModelDisplayName(type.primary_model)}</span>
                    </div>
                    <div className="flex items-center gap-1">
                      <Bot className="h-3.5 w-3.5" />
                      <span className="text-xs">{type.instance_count} instances</span>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      {/* Empty State */}
      {!isLoading && agentTypes.length === 0 && (
        <div className="py-12 text-center">
          <Bot className="mx-auto h-12 w-12 text-muted-foreground" />
          <h3 className="mt-4 font-semibold">No agent types found</h3>
          <p className="text-muted-foreground">
            {searchQuery || statusFilter !== 'all'
              ? 'Try adjusting your search or filters'
              : 'Create your first agent type to get started'}
          </p>
          {!searchQuery && statusFilter === 'all' && (
            <Button onClick={onCreate} className="mt-4">
              <Plus className="mr-2 h-4 w-4" />
              Create Agent Type
            </Button>
          )}
        </div>
      )}
    </div>
  );
}
