/**
 * AgentTypeDetail Component
 *
 * Displays detailed information about a single agent type.
 * Shows model configuration, permissions, personality, and instance stats.
 */

'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 { Separator } from '@/components/ui/separator';
import { Skeleton } from '@/components/ui/skeleton';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
  AlertDialogTrigger,
} from '@/components/ui/alert-dialog';
import {
  Bot,
  ArrowLeft,
  Copy,
  Edit,
  Trash2,
  FileText,
  Zap,
  MessageSquare,
  Shield,
  Cpu,
  CheckCircle2,
  AlertTriangle,
} from 'lucide-react';
import type { AgentTypeResponse } from '@/lib/api/types/agentTypes';
import { AVAILABLE_MCP_SERVERS } from '@/lib/validations/agentType';

interface AgentTypeDetailProps {
  agentType: AgentTypeResponse | null;
  isLoading?: boolean;
  onBack: () => void;
  onEdit: () => void;
  onDuplicate: () => void;
  onDeactivate: () => void;
  isDeactivating?: boolean;
  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 detail
 */
function AgentTypeDetailSkeleton() {
  return (
    <div className="space-y-6">
      <div className="flex items-center gap-4">
        <Skeleton className="h-10 w-10" />
        <div className="flex-1">
          <Skeleton className="h-8 w-64" />
          <Skeleton className="mt-2 h-4 w-48" />
        </div>
      </div>
      <div className="grid gap-6 lg:grid-cols-3">
        <div className="space-y-6 lg:col-span-2">
          <Card>
            <CardHeader>
              <Skeleton className="h-6 w-32" />
            </CardHeader>
            <CardContent>
              <Skeleton className="h-20 w-full" />
            </CardContent>
          </Card>
        </div>
        <div className="space-y-6">
          <Card>
            <CardHeader>
              <Skeleton className="h-6 w-32" />
            </CardHeader>
            <CardContent>
              <Skeleton className="h-40 w-full" />
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}

/**
 * Get model display name
 */
function getModelDisplayName(modelId: string): string {
  const modelNames: Record<string, string> = {
    'claude-opus-4-5-20251101': 'Claude Opus 4.5',
    'claude-sonnet-4-20250514': 'Claude Sonnet 4',
    'claude-3-5-sonnet-20241022': 'Claude 3.5 Sonnet',
  };
  return modelNames[modelId] || modelId;
}

export function AgentTypeDetail({
  agentType,
  isLoading = false,
  onBack,
  onEdit,
  onDuplicate,
  onDeactivate,
  isDeactivating = false,
  className,
}: AgentTypeDetailProps) {
  if (isLoading) {
    return <AgentTypeDetailSkeleton />;
  }

  if (!agentType) {
    return (
      <div className="py-12 text-center">
        <AlertTriangle className="mx-auto h-12 w-12 text-muted-foreground" />
        <h3 className="mt-4 font-semibold">Agent type not found</h3>
        <p className="text-muted-foreground">
          The requested agent type could not be found
        </p>
        <Button onClick={onBack} variant="outline" className="mt-4">
          <ArrowLeft className="mr-2 h-4 w-4" />
          Go Back
        </Button>
      </div>
    );
  }

  const modelParams = agentType.model_params as {
    temperature?: number;
    max_tokens?: number;
    top_p?: number;
  };

  return (
    <div className={className}>
      {/* Header */}
      <div className="mb-6 flex items-center gap-4">
        <Button variant="ghost" size="icon" onClick={onBack}>
          <ArrowLeft className="h-4 w-4" />
          <span className="sr-only">Go back</span>
        </Button>
        <div className="flex-1">
          <div className="flex items-center gap-3">
            <h1 className="text-3xl font-bold">{agentType.name}</h1>
            <AgentTypeStatusBadge isActive={agentType.is_active} />
          </div>
          <p className="text-muted-foreground">
            Last modified:{' '}
            {new Date(agentType.updated_at).toLocaleDateString('en-US', {
              year: 'numeric',
              month: 'long',
              day: 'numeric',
            })}
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="sm" onClick={onDuplicate}>
            <Copy className="mr-2 h-4 w-4" />
            Duplicate
          </Button>
          <Button size="sm" onClick={onEdit}>
            <Edit className="mr-2 h-4 w-4" />
            Edit
          </Button>
        </div>
      </div>

      <div className="grid gap-6 lg:grid-cols-3">
        {/* Main Content */}
        <div className="space-y-6 lg:col-span-2">
          {/* Description Card */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <FileText className="h-5 w-5" />
                Description
              </CardTitle>
            </CardHeader>
            <CardContent>
              <p className="text-muted-foreground">
                {agentType.description || 'No description provided'}
              </p>
            </CardContent>
          </Card>

          {/* Expertise Card */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Zap className="h-5 w-5" />
                Expertise Areas
              </CardTitle>
            </CardHeader>
            <CardContent>
              {agentType.expertise.length > 0 ? (
                <div className="flex flex-wrap gap-2">
                  {agentType.expertise.map((skill) => (
                    <Badge key={skill} variant="secondary">
                      {skill}
                    </Badge>
                  ))}
                </div>
              ) : (
                <p className="text-muted-foreground">No expertise areas defined</p>
              )}
            </CardContent>
          </Card>

          {/* Personality Prompt Card */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <MessageSquare className="h-5 w-5" />
                Personality Prompt
              </CardTitle>
            </CardHeader>
            <CardContent>
              <pre className="whitespace-pre-wrap rounded-lg bg-muted p-4 text-sm">
                {agentType.personality_prompt}
              </pre>
            </CardContent>
          </Card>

          {/* MCP Permissions Card */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Shield className="h-5 w-5" />
                MCP Permissions
              </CardTitle>
              <CardDescription>
                Model Context Protocol servers this agent can access
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-3">
                {AVAILABLE_MCP_SERVERS.map((server) => {
                  const isEnabled = agentType.mcp_servers.includes(server.id);
                  return (
                    <div
                      key={server.id}
                      className={`flex items-center justify-between rounded-lg border p-3 ${
                        isEnabled
                          ? 'border-primary/20 bg-primary/5'
                          : 'border-muted bg-muted/50'
                      }`}
                    >
                      <div className="flex items-center gap-3">
                        <div
                          className={`flex h-8 w-8 items-center justify-center rounded-full ${
                            isEnabled ? 'bg-primary/10' : 'bg-muted'
                          }`}
                        >
                          {isEnabled ? (
                            <CheckCircle2 className="h-4 w-4 text-primary" />
                          ) : (
                            <AlertTriangle className="h-4 w-4 text-muted-foreground" />
                          )}
                        </div>
                        <div>
                          <p className="font-medium">{server.name}</p>
                          <p className="text-xs text-muted-foreground">
                            {server.description}
                          </p>
                        </div>
                      </div>
                      <Badge variant={isEnabled ? 'default' : 'secondary'}>
                        {isEnabled ? 'Enabled' : 'Disabled'}
                      </Badge>
                    </div>
                  );
                })}
              </div>
            </CardContent>
          </Card>
        </div>

        {/* Sidebar */}
        <div className="space-y-6">
          {/* Model Configuration */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2 text-lg">
                <Cpu className="h-5 w-5" />
                Model Configuration
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-4">
              <div>
                <p className="text-sm text-muted-foreground">Primary Model</p>
                <p className="font-medium">
                  {getModelDisplayName(agentType.primary_model)}
                </p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground">Failover Model</p>
                <p className="font-medium">
                  {agentType.fallback_models.length > 0
                    ? getModelDisplayName(agentType.fallback_models[0])
                    : 'None configured'}
                </p>
              </div>
              <Separator />
              <div className="space-y-2">
                <div className="flex justify-between text-sm">
                  <span className="text-muted-foreground">Temperature</span>
                  <span className="font-medium">{modelParams.temperature ?? 0.7}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-muted-foreground">Max Tokens</span>
                  <span className="font-medium">
                    {(modelParams.max_tokens ?? 8192).toLocaleString()}
                  </span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-muted-foreground">Top P</span>
                  <span className="font-medium">{modelParams.top_p ?? 0.95}</span>
                </div>
              </div>
            </CardContent>
          </Card>

          {/* Instance Stats */}
          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2 text-lg">
                <Bot className="h-5 w-5" />
                Instances
              </CardTitle>
            </CardHeader>
            <CardContent>
              <div className="text-center">
                <p className="text-4xl font-bold text-primary">
                  {agentType.instance_count}
                </p>
                <p className="text-sm text-muted-foreground">Active instances</p>
              </div>
              <Button variant="outline" className="mt-4 w-full" size="sm" disabled>
                View Instances
              </Button>
            </CardContent>
          </Card>

          {/* Danger Zone */}
          <Card className="border-destructive/50">
            <CardHeader>
              <CardTitle className="flex items-center gap-2 text-lg text-destructive">
                <AlertTriangle className="h-5 w-5" />
                Danger Zone
              </CardTitle>
            </CardHeader>
            <CardContent className="space-y-3">
              <AlertDialog>
                <AlertDialogTrigger asChild>
                  <Button
                    variant="destructive"
                    className="w-full"
                    size="sm"
                    disabled={isDeactivating}
                  >
                    <Trash2 className="mr-2 h-4 w-4" />
                    {agentType.is_active ? 'Deactivate Type' : 'Delete Type'}
                  </Button>
                </AlertDialogTrigger>
                <AlertDialogContent>
                  <AlertDialogHeader>
                    <AlertDialogTitle>Are you sure?</AlertDialogTitle>
                    <AlertDialogDescription>
                      {agentType.is_active
                        ? `This will deactivate the "${agentType.name}" agent type. Existing instances will continue to work, but no new instances can be created from this type.`
                        : `This will permanently delete the "${agentType.name}" agent type. This action cannot be undone.`}
                    </AlertDialogDescription>
                  </AlertDialogHeader>
                  <AlertDialogFooter>
                    <AlertDialogCancel>Cancel</AlertDialogCancel>
                    <AlertDialogAction
                      onClick={onDeactivate}
                      className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                    >
                      {agentType.is_active ? 'Deactivate' : 'Delete'}
                    </AlertDialogAction>
                  </AlertDialogFooter>
                </AlertDialogContent>
              </AlertDialog>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}
