/**
 * AgentTypeList Component
 *
 * Displays agent types in grid or list view with search, status, and category filters.
 * Shows icon, color accent, and category for each agent type.
 */

'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 { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
import { Bot, Plus, Search, Cpu, LayoutGrid, List } from 'lucide-react';
import { DynamicIcon } from '@/components/ui/dynamic-icon';
import type { AgentTypeResponse, AgentTypeCategory } from '@/lib/api/types/agentTypes';
import { CATEGORY_METADATA } from '@/lib/api/types/agentTypes';
import { AGENT_TYPE_CATEGORIES } from '@/lib/validations/agentType';

export type ViewMode = 'grid' | 'list';

interface AgentTypeListProps {
  agentTypes: AgentTypeResponse[];
  isLoading?: boolean;
  searchQuery: string;
  onSearchChange: (query: string) => void;
  statusFilter: string;
  onStatusFilterChange: (status: string) => void;
  categoryFilter: string;
  onCategoryFilterChange: (category: string) => void;
  viewMode: ViewMode;
  onViewModeChange: (mode: ViewMode) => 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>
  );
}

/**
 * Category badge with color
 */
function CategoryBadge({ category }: { category: AgentTypeCategory | null }) {
  if (!category) return null;

  const meta = CATEGORY_METADATA[category];
  if (!meta) return null;

  return (
    <Badge
      variant="outline"
      className="text-xs font-medium"
      style={{
        borderColor: meta.color,
        color: meta.color,
        backgroundColor: `${meta.color}10`,
      }}
    >
      {meta.label}
    </Badge>
  );
}

/**
 * Loading skeleton for agent type cards (grid view)
 */
function AgentTypeCardSkeleton() {
  return (
    <Card className="h-[220px] overflow-hidden">
      <div className="h-1 w-full bg-muted" />
      <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>
  );
}

/**
 * Loading skeleton for list view
 */
function AgentTypeListSkeleton() {
  return (
    <div className="flex items-center gap-4 rounded-lg border p-4">
      <Skeleton className="h-12 w-12 rounded-lg" />
      <div className="flex-1 space-y-2">
        <Skeleton className="h-5 w-48" />
        <Skeleton className="h-4 w-96" />
      </div>
      <Skeleton className="h-5 w-20" />
      <Skeleton className="h-5 w-16" />
    </div>
  );
}

/**
 * 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;
}

/**
 * Grid card view for agent type
 */
function AgentTypeGridCard({
  type,
  onSelect,
}: {
  type: AgentTypeResponse;
  onSelect: (id: string) => void;
}) {
  const agentColor = type.color || '#3B82F6';

  return (
    <Card
      className="cursor-pointer overflow-hidden transition-all hover:shadow-lg"
      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`}
      style={{
        borderTopColor: agentColor,
        borderTopWidth: '3px',
      }}
    >
      <CardHeader className="pb-3">
        <div className="flex items-start justify-between">
          <div
            className="flex h-11 w-11 items-center justify-center rounded-lg"
            style={{
              backgroundColor: `${agentColor}15`,
            }}
          >
            <DynamicIcon
              name={type.icon}
              className="h-5 w-5"
              style={{ color: agentColor }}
              fallback="bot"
            />
          </div>
          <div className="flex flex-col items-end gap-1">
            <AgentTypeStatusBadge isActive={type.is_active} />
            <CategoryBadge category={type.category} />
          </div>
        </div>
        <CardTitle className="mt-3 line-clamp-1">{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>
  );
}

/**
 * List row view for agent type
 */
function AgentTypeListRow({
  type,
  onSelect,
}: {
  type: AgentTypeResponse;
  onSelect: (id: string) => void;
}) {
  const agentColor = type.color || '#3B82F6';

  return (
    <div
      className="flex cursor-pointer items-center gap-4 rounded-lg border p-4 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`}
      style={{
        borderLeftColor: agentColor,
        borderLeftWidth: '4px',
      }}
    >
      {/* Icon */}
      <div
        className="flex h-12 w-12 shrink-0 items-center justify-center rounded-lg"
        style={{ backgroundColor: `${agentColor}15` }}
      >
        <DynamicIcon
          name={type.icon}
          className="h-6 w-6"
          style={{ color: agentColor }}
          fallback="bot"
        />
      </div>

      {/* Main content */}
      <div className="min-w-0 flex-1">
        <div className="flex items-center gap-2">
          <h3 className="font-semibold">{type.name}</h3>
          <CategoryBadge category={type.category} />
        </div>
        <p className="line-clamp-1 text-sm text-muted-foreground">
          {type.description || 'No description'}
        </p>
        <div className="mt-1 flex items-center gap-3 text-xs text-muted-foreground">
          <span className="flex items-center gap-1">
            <Cpu className="h-3 w-3" />
            {getModelDisplayName(type.primary_model)}
          </span>
          <span>{type.expertise.length} expertise areas</span>
          <span>{type.instance_count} instances</span>
        </div>
      </div>

      {/* Status */}
      <div className="shrink-0">
        <AgentTypeStatusBadge isActive={type.is_active} />
      </div>
    </div>
  );
}

export function AgentTypeList({
  agentTypes,
  isLoading = false,
  searchQuery,
  onSearchChange,
  statusFilter,
  onStatusFilterChange,
  categoryFilter,
  onCategoryFilterChange,
  viewMode,
  onViewModeChange,
  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 sm:items-center">
        <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>

        {/* Category Filter */}
        <Select value={categoryFilter} onValueChange={onCategoryFilterChange}>
          <SelectTrigger className="w-full sm:w-44" aria-label="Filter by category">
            <SelectValue placeholder="All Categories" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Categories</SelectItem>
            {AGENT_TYPE_CATEGORIES.map((cat) => (
              <SelectItem key={cat.value} value={cat.value}>
                {cat.label}
              </SelectItem>
            ))}
          </SelectContent>
        </Select>

        {/* Status Filter */}
        <Select value={statusFilter} onValueChange={onStatusFilterChange}>
          <SelectTrigger className="w-full sm:w-36" 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>

        {/* View Mode Toggle */}
        <ToggleGroup
          type="single"
          value={viewMode}
          onValueChange={(value: string) => value && onViewModeChange(value as ViewMode)}
          className="hidden sm:flex"
        >
          <ToggleGroupItem value="grid" aria-label="Grid view" size="sm">
            <LayoutGrid className="h-4 w-4" />
          </ToggleGroupItem>
          <ToggleGroupItem value="list" aria-label="List view" size="sm">
            <List className="h-4 w-4" />
          </ToggleGroupItem>
        </ToggleGroup>
      </div>

      {/* Loading State - Grid */}
      {isLoading && viewMode === 'grid' && (
        <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>
      )}

      {/* Loading State - List */}
      {isLoading && viewMode === 'list' && (
        <div className="space-y-3">
          {[1, 2, 3, 4, 5, 6].map((i) => (
            <AgentTypeListSkeleton key={i} />
          ))}
        </div>
      )}

      {/* Agent Type Grid View */}
      {!isLoading && agentTypes.length > 0 && viewMode === 'grid' && (
        <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
          {agentTypes.map((type) => (
            <AgentTypeGridCard key={type.id} type={type} onSelect={onSelect} />
          ))}
        </div>
      )}

      {/* Agent Type List View */}
      {!isLoading && agentTypes.length > 0 && viewMode === 'list' && (
        <div className="space-y-3">
          {agentTypes.map((type) => (
            <AgentTypeListRow key={type.id} type={type} onSelect={onSelect} />
          ))}
        </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' || categoryFilter !== 'all'
              ? 'Try adjusting your search or filters'
              : 'Create your first agent type to get started'}
          </p>
          {!searchQuery && statusFilter === 'all' && categoryFilter === 'all' && (
            <Button onClick={onCreate} className="mt-4">
              <Plus className="mr-2 h-4 w-4" />
              Create Agent Type
            </Button>
          )}
        </div>
      )}
    </div>
  );
}
