'use client';

import { useState } from 'react';
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 { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import { Separator } from '@/components/ui/separator';
import { Checkbox } from '@/components/ui/checkbox';
import {
  Bot,
  Plus,
  Search,
  Settings,
  ChevronRight,
  ArrowLeft,
  Copy,
  Trash2,
  Save,
  Eye,
  Edit,
  Sliders,
  Shield,
  MessageSquare,
  Cpu,
  Zap,
  Code,
  FileText,
  CheckCircle2,
  AlertTriangle,
} from 'lucide-react';

// Mock data for agent types
const mockAgentTypes = [
  {
    id: 'type-001',
    name: 'Product Owner',
    description: 'Manages product backlog, defines user stories, and prioritizes features',
    expertise: ['Requirements', 'User Stories', 'Prioritization', 'Stakeholder Management'],
    model: 'claude-opus-4-5-20251101',
    status: 'active',
    instanceCount: 3,
    lastModified: '2025-01-20',
  },
  {
    id: 'type-002',
    name: 'Software Architect',
    description: 'Designs system architecture, makes technology decisions, and ensures scalability',
    expertise: ['System Design', 'API Design', 'Database Architecture', 'Security'],
    model: 'claude-opus-4-5-20251101',
    status: 'active',
    instanceCount: 2,
    lastModified: '2025-01-18',
  },
  {
    id: 'type-003',
    name: 'Backend Engineer',
    description: 'Implements server-side logic, APIs, and database interactions',
    expertise: ['Python', 'FastAPI', 'PostgreSQL', 'Redis', 'Testing'],
    model: 'claude-sonnet-4-20250514',
    status: 'active',
    instanceCount: 5,
    lastModified: '2025-01-22',
  },
  {
    id: 'type-004',
    name: 'Frontend Engineer',
    description: 'Builds user interfaces using modern React and Next.js',
    expertise: ['React', 'Next.js', 'TypeScript', 'Tailwind CSS', 'Testing'],
    model: 'claude-sonnet-4-20250514',
    status: 'active',
    instanceCount: 4,
    lastModified: '2025-01-21',
  },
  {
    id: 'type-005',
    name: 'QA Engineer',
    description: 'Creates test plans, writes automated tests, and ensures quality',
    expertise: ['Test Planning', 'E2E Testing', 'Unit Testing', 'Bug Reporting'],
    model: 'claude-sonnet-4-20250514',
    status: 'draft',
    instanceCount: 0,
    lastModified: '2025-01-19',
  },
  {
    id: 'type-006',
    name: 'DevOps Engineer',
    description: 'Manages infrastructure, CI/CD pipelines, and deployment processes',
    expertise: ['Docker', 'Kubernetes', 'CI/CD', 'Monitoring', 'Security'],
    model: 'claude-sonnet-4-20250514',
    status: 'inactive',
    instanceCount: 1,
    lastModified: '2025-01-15',
  },
];

// Full agent type detail for editor
const mockAgentTypeDetail = {
  id: 'type-002',
  name: 'Software Architect',
  description: 'Designs system architecture, makes technology decisions, and ensures scalability. Works closely with the Product Owner to understand requirements and with Engineers to implement solutions.',
  expertise: ['System Design', 'API Design', 'Database Architecture', 'Security', 'Scalability'],
  model: {
    primary: 'claude-opus-4-5-20251101',
    failover: 'claude-sonnet-4-20250514',
  },
  parameters: {
    temperature: 0.7,
    maxTokens: 8192,
    topP: 0.95,
  },
  mcpPermissions: [
    { id: 'gitea', name: 'Gitea', enabled: true, scopes: ['read', 'write', 'issues'] },
    { id: 'knowledge', name: 'Knowledge Base', enabled: true, scopes: ['read', 'write'] },
    { id: 'filesystem', name: 'Filesystem', enabled: true, scopes: ['read', 'write'] },
    { id: 'slack', name: 'Slack', enabled: false, scopes: [] },
    { id: 'jira', name: 'Jira', enabled: false, scopes: [] },
  ],
  personalityPrompt: `You are a Senior Software Architect with 15+ years of experience designing scalable, maintainable systems. Your approach is:

1. **Pragmatic**: You favor proven solutions over cutting-edge unless there's a clear benefit
2. **Security-minded**: Security is a first-class concern, not an afterthought
3. **Documentation-focused**: You believe in architecture decision records (ADRs)
4. **Collaborative**: You seek input from engineers and stakeholders before making major decisions

When designing systems:
- Start with requirements and constraints
- Consider scalability, maintainability, and operational concerns
- Document decisions and their rationale
- Provide clear guidance for implementation teams

Your communication style is clear, structured, and respectful. You explain complex concepts simply and always justify your recommendations.`,
  status: 'active',
  instanceCount: 2,
  createdAt: '2025-01-10',
  lastModified: '2025-01-18',
};

// View states
type ViewState = 'list' | 'detail' | 'editor';

// Status badge for agent types
function AgentTypeStatusBadge({ status }: { status: string }) {
  const variants: Record<string, { label: string; className: string }> = {
    active: {
      label: 'Active',
      className: 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200',
    },
    draft: {
      label: 'Draft',
      className: 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200',
    },
    inactive: {
      label: 'Inactive',
      className: 'bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200',
    },
  };

  const variant = variants[status] || variants.inactive;

  return (
    <Badge className={variant.className} variant="outline">
      {variant.label}
    </Badge>
  );
}

// Agent Type List View
function AgentTypeListView({
  onSelect,
  onCreate,
}: {
  onSelect: (id: string) => void;
  onCreate: () => void;
}) {
  const [searchQuery, setSearchQuery] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');

  const filteredTypes = mockAgentTypes.filter((type) => {
    const matchesSearch =
      type.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      type.description.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesStatus = statusFilter === 'all' || type.status === statusFilter;
    return matchesSearch && matchesStatus;
  });

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="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="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) => setSearchQuery(e.target.value)}
            className="pl-9"
          />
        </div>
        <Select value={statusFilter} onValueChange={setStatusFilter}>
          <SelectTrigger className="w-full sm:w-40">
            <SelectValue placeholder="Status" />
          </SelectTrigger>
          <SelectContent>
            <SelectItem value="all">All Status</SelectItem>
            <SelectItem value="active">Active</SelectItem>
            <SelectItem value="draft">Draft</SelectItem>
            <SelectItem value="inactive">Inactive</SelectItem>
          </SelectContent>
        </Select>
      </div>

      {/* Agent Type Grid */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
        {filteredTypes.map((type) => (
          <Card
            key={type.id}
            className="cursor-pointer transition-all hover:border-primary hover:shadow-md"
            onClick={() => onSelect(type.id)}
          >
            <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 status={type.status} />
              </div>
              <CardTitle className="mt-3">{type.name}</CardTitle>
              <CardDescription className="line-clamp-2">{type.description}</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>
                  )}
                </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">{type.model.split('-').slice(1, 2).join(' ')}</span>
                  </div>
                  <div className="flex items-center gap-1">
                    <Bot className="h-3.5 w-3.5" />
                    <span className="text-xs">{type.instanceCount} instances</span>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {filteredTypes.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">Try adjusting your search or filters</p>
        </div>
      )}
    </div>
  );
}

// Agent Type Detail View
function AgentTypeDetailView({
  onBack,
  onEdit,
}: {
  onBack: () => void;
  onEdit: () => void;
}) {
  const type = mockAgentTypeDetail;

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-4">
        <Button variant="ghost" size="icon" onClick={onBack}>
          <ArrowLeft className="h-4 w-4" />
        </Button>
        <div className="flex-1">
          <div className="flex items-center gap-3">
            <h1 className="text-3xl font-bold">{type.name}</h1>
            <AgentTypeStatusBadge status={type.status} />
          </div>
          <p className="text-muted-foreground">Last modified: {type.lastModified}</p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" size="sm">
            <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">{type.description}</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>
              <div className="flex flex-wrap gap-2">
                {type.expertise.map((skill) => (
                  <Badge key={skill} variant="secondary">
                    {skill}
                  </Badge>
                ))}
              </div>
            </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">
                {type.personalityPrompt}
              </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">
                {type.mcpPermissions.map((perm) => (
                  <div
                    key={perm.id}
                    className={`flex items-center justify-between rounded-lg border p-3 ${
                      perm.enabled ? '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 ${
                          perm.enabled ? 'bg-primary/10' : 'bg-muted'
                        }`}
                      >
                        {perm.enabled ? (
                          <CheckCircle2 className="h-4 w-4 text-primary" />
                        ) : (
                          <AlertTriangle className="h-4 w-4 text-muted-foreground" />
                        )}
                      </div>
                      <div>
                        <p className="font-medium">{perm.name}</p>
                        <p className="text-xs text-muted-foreground">
                          {perm.enabled ? perm.scopes.join(', ') : 'Not enabled'}
                        </p>
                      </div>
                    </div>
                    <Badge variant={perm.enabled ? 'default' : 'secondary'}>
                      {perm.enabled ? '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">{type.model.primary}</p>
              </div>
              <div>
                <p className="text-sm text-muted-foreground">Failover Model</p>
                <p className="font-medium">{type.model.failover}</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">{type.parameters.temperature}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-muted-foreground">Max Tokens</span>
                  <span className="font-medium">{type.parameters.maxTokens.toLocaleString()}</span>
                </div>
                <div className="flex justify-between text-sm">
                  <span className="text-muted-foreground">Top P</span>
                  <span className="font-medium">{type.parameters.topP}</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">{type.instanceCount}</p>
                <p className="text-sm text-muted-foreground">Active instances</p>
              </div>
              <Button variant="outline" className="mt-4 w-full" size="sm">
                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">
              <Button variant="outline" className="w-full" size="sm">
                Deactivate Type
              </Button>
              <Button variant="destructive" className="w-full" size="sm">
                <Trash2 className="mr-2 h-4 w-4" />
                Delete Type
              </Button>
            </CardContent>
          </Card>
        </div>
      </div>
    </div>
  );
}

// Agent Type Editor View
function AgentTypeEditorView({
  onBack,
  onSave,
  isNew = false,
}: {
  onBack: () => void;
  onSave: () => void;
  isNew?: boolean;
}) {
  const [activeTab, setActiveTab] = useState('basic');

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="flex items-center gap-4">
        <Button variant="ghost" size="icon" onClick={onBack}>
          <ArrowLeft className="h-4 w-4" />
        </Button>
        <div className="flex-1">
          <h1 className="text-3xl font-bold">
            {isNew ? 'Create Agent Type' : 'Edit Agent Type'}
          </h1>
          <p className="text-muted-foreground">
            {isNew
              ? 'Define a new agent type template'
              : 'Modify agent type configuration'}
          </p>
        </div>
        <div className="flex gap-2">
          <Button variant="outline" onClick={onBack}>
            Cancel
          </Button>
          <Button onClick={onSave}>
            <Save className="mr-2 h-4 w-4" />
            {isNew ? 'Create' : 'Save Changes'}
          </Button>
        </div>
      </div>

      {/* Editor Tabs */}
      <Tabs value={activeTab} onValueChange={setActiveTab}>
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="basic">
            <FileText className="mr-2 h-4 w-4" />
            Basic Info
          </TabsTrigger>
          <TabsTrigger value="model">
            <Cpu className="mr-2 h-4 w-4" />
            Model
          </TabsTrigger>
          <TabsTrigger value="permissions">
            <Shield className="mr-2 h-4 w-4" />
            Permissions
          </TabsTrigger>
          <TabsTrigger value="personality">
            <MessageSquare className="mr-2 h-4 w-4" />
            Personality
          </TabsTrigger>
        </TabsList>

        {/* Basic Info Tab */}
        <TabsContent value="basic" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>Basic Information</CardTitle>
              <CardDescription>
                Define the agent type name, description, and expertise areas
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              <div className="grid gap-4 md:grid-cols-2">
                <div className="space-y-2">
                  <Label htmlFor="name">Name</Label>
                  <Input
                    id="name"
                    placeholder="e.g., Software Architect"
                    defaultValue={!isNew ? mockAgentTypeDetail.name : ''}
                  />
                </div>
                <div className="space-y-2">
                  <Label htmlFor="status">Status</Label>
                  <Select defaultValue={!isNew ? mockAgentTypeDetail.status : 'draft'}>
                    <SelectTrigger id="status">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="active">Active</SelectItem>
                      <SelectItem value="draft">Draft</SelectItem>
                      <SelectItem value="inactive">Inactive</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              <div className="space-y-2">
                <Label htmlFor="description">Description</Label>
                <Textarea
                  id="description"
                  placeholder="Describe what this agent type does..."
                  rows={3}
                  defaultValue={!isNew ? mockAgentTypeDetail.description : ''}
                />
              </div>

              <div className="space-y-2">
                <Label>Expertise Areas</Label>
                <p className="text-sm text-muted-foreground">
                  Add skills and areas of expertise (comma-separated)
                </p>
                <Input
                  placeholder="e.g., System Design, API Design, Security"
                  defaultValue={!isNew ? mockAgentTypeDetail.expertise.join(', ') : ''}
                />
                <div className="flex flex-wrap gap-2 pt-2">
                  {(!isNew ? mockAgentTypeDetail.expertise : []).map((skill) => (
                    <Badge key={skill} variant="secondary" className="gap-1">
                      {skill}
                      <button className="ml-1 rounded-full hover:bg-muted">
                        <span className="sr-only">Remove {skill}</span>
                        &times;
                      </button>
                    </Badge>
                  ))}
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* Model Configuration Tab */}
        <TabsContent value="model" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>Model Selection</CardTitle>
              <CardDescription>
                Choose the AI models that power this agent type
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              <div className="grid gap-4 md:grid-cols-2">
                <div className="space-y-2">
                  <Label htmlFor="primary-model">Primary Model</Label>
                  <Select
                    defaultValue={!isNew ? mockAgentTypeDetail.model.primary : ''}
                  >
                    <SelectTrigger id="primary-model">
                      <SelectValue placeholder="Select model" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="claude-opus-4-5-20251101">
                        Claude Opus 4.5
                      </SelectItem>
                      <SelectItem value="claude-sonnet-4-20250514">
                        Claude Sonnet 4
                      </SelectItem>
                      <SelectItem value="claude-3-5-sonnet-20241022">
                        Claude 3.5 Sonnet
                      </SelectItem>
                    </SelectContent>
                  </Select>
                  <p className="text-xs text-muted-foreground">
                    Main model used for this agent
                  </p>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="failover-model">Failover Model</Label>
                  <Select
                    defaultValue={!isNew ? mockAgentTypeDetail.model.failover : ''}
                  >
                    <SelectTrigger id="failover-model">
                      <SelectValue placeholder="Select model" />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="claude-opus-4-5-20251101">
                        Claude Opus 4.5
                      </SelectItem>
                      <SelectItem value="claude-sonnet-4-20250514">
                        Claude Sonnet 4
                      </SelectItem>
                      <SelectItem value="claude-3-5-sonnet-20241022">
                        Claude 3.5 Sonnet
                      </SelectItem>
                    </SelectContent>
                  </Select>
                  <p className="text-xs text-muted-foreground">
                    Backup model if primary is unavailable
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>

          <Card>
            <CardHeader>
              <CardTitle className="flex items-center gap-2">
                <Sliders className="h-5 w-5" />
                Model Parameters
              </CardTitle>
              <CardDescription>
                Fine-tune the model behavior
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-6">
              <div className="grid gap-6 md:grid-cols-3">
                <div className="space-y-2">
                  <Label htmlFor="temperature">Temperature</Label>
                  <Input
                    id="temperature"
                    type="number"
                    step="0.1"
                    min="0"
                    max="2"
                    defaultValue={!isNew ? mockAgentTypeDetail.parameters.temperature : 0.7}
                  />
                  <p className="text-xs text-muted-foreground">
                    0 = deterministic, 2 = creative
                  </p>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="max-tokens">Max Tokens</Label>
                  <Input
                    id="max-tokens"
                    type="number"
                    step="1024"
                    min="1024"
                    max="32768"
                    defaultValue={!isNew ? mockAgentTypeDetail.parameters.maxTokens : 8192}
                  />
                  <p className="text-xs text-muted-foreground">
                    Maximum response length
                  </p>
                </div>
                <div className="space-y-2">
                  <Label htmlFor="top-p">Top P</Label>
                  <Input
                    id="top-p"
                    type="number"
                    step="0.05"
                    min="0"
                    max="1"
                    defaultValue={!isNew ? mockAgentTypeDetail.parameters.topP : 0.95}
                  />
                  <p className="text-xs text-muted-foreground">
                    Nucleus sampling threshold
                  </p>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* MCP Permissions Tab */}
        <TabsContent value="permissions" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>MCP Server Permissions</CardTitle>
              <CardDescription>
                Configure which MCP servers this agent can access and with what permissions
              </CardDescription>
            </CardHeader>
            <CardContent className="space-y-4">
              {mockAgentTypeDetail.mcpPermissions.map((perm) => (
                <div
                  key={perm.id}
                  className="rounded-lg border p-4 space-y-3"
                >
                  <div className="flex items-center justify-between">
                    <div className="flex items-center gap-3">
                      <Checkbox
                        id={`perm-${perm.id}`}
                        defaultChecked={perm.enabled}
                      />
                      <Label htmlFor={`perm-${perm.id}`} className="font-medium">
                        {perm.name}
                      </Label>
                    </div>
                  </div>
                  {perm.enabled && (
                    <div className="ml-7 space-y-2">
                      <p className="text-sm text-muted-foreground">Scopes:</p>
                      <div className="flex flex-wrap gap-2">
                        {['read', 'write', 'issues', 'branches', 'prs'].map((scope) => (
                          <div key={scope} className="flex items-center gap-1">
                            <Checkbox
                              id={`scope-${perm.id}-${scope}`}
                              defaultChecked={perm.scopes.includes(scope)}
                            />
                            <Label
                              htmlFor={`scope-${perm.id}-${scope}`}
                              className="text-sm font-normal"
                            >
                              {scope}
                            </Label>
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
              ))}
            </CardContent>
          </Card>
        </TabsContent>

        {/* Personality Prompt Tab */}
        <TabsContent value="personality" className="space-y-6">
          <Card>
            <CardHeader>
              <CardTitle>Personality Prompt</CardTitle>
              <CardDescription>
                Define the agent&apos;s personality, behavior, and communication style.
                This prompt shapes how the agent approaches tasks and interacts.
              </CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                <Textarea
                  placeholder="You are a..."
                  rows={15}
                  className="font-mono text-sm"
                  defaultValue={!isNew ? mockAgentTypeDetail.personalityPrompt : ''}
                />
                <div className="flex items-center gap-4 text-sm text-muted-foreground">
                  <span>Character count: {mockAgentTypeDetail.personalityPrompt.length}</span>
                  <Separator orientation="vertical" className="h-4" />
                  <Button variant="ghost" size="sm">
                    <Eye className="mr-2 h-4 w-4" />
                    Preview
                  </Button>
                  <Button variant="ghost" size="sm">
                    <Code className="mr-2 h-4 w-4" />
                    Use Template
                  </Button>
                </div>
              </div>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}

export default function AgentConfigurationPrototype() {
  const [view, setView] = useState<ViewState>('list');
  const [_selectedId, setSelectedId] = useState<string | null>(null);
  const [isCreating, setIsCreating] = useState(false);

  const handleSelectType = (id: string) => {
    setSelectedId(id);
    setView('detail');
  };

  const handleCreate = () => {
    setIsCreating(true);
    setView('editor');
  };

  const handleEdit = () => {
    setIsCreating(false);
    setView('editor');
  };

  const handleBack = () => {
    if (view === 'editor') {
      setView(isCreating ? 'list' : 'detail');
    } else {
      setView('list');
      setSelectedId(null);
    }
  };

  const handleSave = () => {
    // In real implementation, this would save to API
    setView('list');
    setSelectedId(null);
    setIsCreating(false);
  };

  return (
    <div className="min-h-screen bg-background">
      {/* Navigation Bar */}
      <nav className="border-b bg-card">
        <div className="container mx-auto flex h-14 items-center justify-between px-4">
          <div className="flex items-center gap-4">
            <span className="font-semibold text-primary">Syndarix</span>
            <Separator orientation="vertical" className="h-6" />
            <span className="text-sm text-muted-foreground">Configuration</span>
            <ChevronRight className="h-4 w-4 text-muted-foreground" />
            <span className="text-sm font-medium">Agent Types</span>
          </div>
          <div className="flex items-center gap-2">
            <Button variant="ghost" size="icon">
              <Settings className="h-4 w-4" />
            </Button>
          </div>
        </div>
      </nav>

      <div className="container mx-auto px-4 py-6">
        {view === 'list' && (
          <AgentTypeListView onSelect={handleSelectType} onCreate={handleCreate} />
        )}
        {view === 'detail' && (
          <AgentTypeDetailView onBack={handleBack} onEdit={handleEdit} />
        )}
        {view === 'editor' && (
          <AgentTypeEditorView
            onBack={handleBack}
            onSave={handleSave}
            isNew={isCreating}
          />
        )}
      </div>
    </div>
  );
}
