"use client"

import React from "react"
import { Button } from "@/components/ui/shadcn-io/button"
import { 
  Select, 
  SelectContent, 
  SelectItem, 
  SelectTrigger, 
  SelectValue 
} from "@/components/ui/shadcn-io/select"
import { Badge } from "@/components/ui/shadcn-io/badge"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from "@/components/ui/command"
import { Slider } from "@/components/ui/slider"
import { Checkbox } from "@/components/ui/checkbox"
import { Play, Pause, Square, RotateCw, Check, ChevronsUpDown, Filter } from "lucide-react"
import { OPENROUTER_MODELS } from "@/lib/agents/llm-provider"
import type { RunConfig } from "@/lib/agents/bandit-state"
import { cn } from "@/lib/utils"

export interface AgentState {
  runId: string | null
  status: 'idle' | 'running' | 'paused' | 'complete' | 'failed'
  currentLevel: number
  modelProvider: string
  modelName: string
  streamingMode: 'selective' | 'all_events'
  isConnected: boolean
}

export interface AgentControlPanelProps {
  agentState: AgentState
  onStartRun: (config: Partial<RunConfig>) => void
  onPauseRun: () => void
  onResumeRun: () => void
  onStopRun: () => void
}

interface OpenRouterModel {
  id: string
  name: string
  contextLength: number
  promptPrice: string
  completionPrice: string
  description: string
}

export function AgentControlPanel({
  agentState,
  onStartRun,
  onPauseRun,
  onResumeRun,
  onStopRun,
}: AgentControlPanelProps) {
  const [selectedModel, setSelectedModel] = React.useState<string>('openai/gpt-4o-mini')
  const [targetLevel, setTargetLevel] = React.useState(5)
  const [streamingMode, setStreamingMode] = React.useState<'selective' | 'all_events'>('selective')
  const [availableModels, setAvailableModels] = React.useState<OpenRouterModel[]>([])
  const [modelsLoading, setModelsLoading] = React.useState(true)
  
  // Search and filter state
  const [modelSearchOpen, setModelSearchOpen] = React.useState(false)
  const [searchQuery, setSearchQuery] = React.useState("")
  const [selectedProvider, setSelectedProvider] = React.useState<string>("all")
  const [maxPrice, setMaxPrice] = React.useState<number[]>([50])
  const [minContextLength, setMinContextLength] = React.useState(false)

  // Fetch available models from OpenRouter on mount
  React.useEffect(() => {
    async function fetchModels() {
      try {
        const response = await fetch('/api/models')
        if (response.ok) {
          const data = await response.json()
          setAvailableModels(data.models || [])
        }
      } catch (error) {
        console.error('Failed to fetch models:', error)
        // Fallback to hardcoded models
        setAvailableModels([
          { id: 'openai/gpt-4o-mini', name: 'GPT-4o Mini', contextLength: 128000, promptPrice: '0.15', completionPrice: '0.60', description: 'Fast and affordable' },
          { id: 'openai/gpt-4o', name: 'GPT-4o', contextLength: 128000, promptPrice: '2.50', completionPrice: '10.00', description: 'Most capable' },
          { id: 'anthropic/claude-3-5-sonnet', name: 'Claude 3.5 Sonnet', contextLength: 200000, promptPrice: '3.00', completionPrice: '15.00', description: 'Excellent reasoning' },
          { id: 'anthropic/claude-3-haiku', name: 'Claude 3 Haiku', contextLength: 200000, promptPrice: '0.25', completionPrice: '1.25', description: 'Fast and accurate' },
        ])
      } finally {
        setModelsLoading(false)
      }
    }
    fetchModels()
  }, [])

  // Filter models based on search and filters
  const filteredModels = React.useMemo(() => {
    return availableModels.filter(model => {
      // Search filter
      const matchesSearch = !searchQuery || 
        model.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
        model.id.toLowerCase().includes(searchQuery.toLowerCase())
      
      // Provider filter
      const provider = model.id.split('/')[0]
      const matchesProvider = selectedProvider === 'all' || provider === selectedProvider
      
      // Price filter (use completion price as it's usually higher)
      const price = parseFloat(model.completionPrice)
      const matchesPrice = price <= maxPrice[0]
      
      // Context length filter (>100k tokens)
      const matchesContext = !minContextLength || model.contextLength >= 100000
      
      return matchesSearch && matchesProvider && matchesPrice && matchesContext
    })
  }, [availableModels, searchQuery, selectedProvider, maxPrice, minContextLength])

  // Extract unique providers
  const providers = React.useMemo(() => {
    const uniqueProviders = new Set(availableModels.map(m => m.id.split('/')[0]))
    return Array.from(uniqueProviders).sort()
  }, [availableModels])

  // Get selected model display name
  const selectedModelName = availableModels.find(m => m.id === selectedModel)?.name || selectedModel

  const handleStart = () => {
    // selectedModel is already the full OpenRouter ID (e.g., "openai/gpt-4o-mini")
    // Always start at level 0
    onStartRun({
      modelProvider: 'openrouter',
      modelName: selectedModel,
      startLevel: 0,
      endLevel: targetLevel,
      maxRetries: 3,
      streamingMode,
    })
  }

  const getStatusBadge = () => {
    switch (agentState.status) {
      case 'idle':
        return <Badge variant="secondary" className="font-mono">IDLE</Badge>
      case 'running':
        return <Badge variant="default" className="font-mono animate-pulse">RUNNING</Badge>
      case 'paused':
        return <Badge variant="outline" className="font-mono border-yellow-500 text-yellow-500">PAUSED</Badge>
      case 'complete':
        return <Badge variant="outline" className="font-mono border-green-500 text-green-500">COMPLETE</Badge>
      case 'failed':
        return <Badge variant="destructive" className="font-mono">FAILED</Badge>
    }
  }

  return (
    <div className="relative flex-shrink-0">
      {/* Corner brackets */}
      <div className="absolute -left-1 -top-1 w-4 h-4 border-l-2 border-t-2 border-primary z-10" />
      <div className="absolute -right-1 -top-1 w-4 h-4 border-r-2 border-t-2 border-primary z-10" />
      
      <div className="border border-border bg-card px-4 py-3">
        <div className="flex flex-col sm:flex-row items-start sm:items-center gap-3 sm:gap-4">
          {/* Status and Level */}
          <div className="flex items-center gap-3">
            <div className="w-1 h-8 bg-accent-foreground" />
            <div className="flex flex-col gap-1">
              <div className="flex items-center gap-2">
                {getStatusBadge()}
                <span className="text-xs text-muted-foreground font-mono">
                  LEVEL {agentState.currentLevel}
                </span>
              </div>
            </div>
          </div>

          {/* Divider */}
          <div className="hidden sm:block h-8 w-px bg-border" />

          {/* Configuration Controls */}
          <div className="flex flex-wrap items-center gap-2 text-xs font-mono">
            {/* Model Selection with Search */}
            <Popover open={modelSearchOpen} onOpenChange={setModelSearchOpen}>
              <PopoverTrigger asChild>
                <Button
                  variant="outline"
                  role="combobox"
                  aria-expanded={modelSearchOpen}
                  className="w-[250px] h-8 justify-between font-mono text-xs"
                  disabled={agentState.status === 'running' || modelsLoading}
                >
                  <span className="truncate">{modelsLoading ? "Loading..." : selectedModelName}</span>
                  <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-[400px] p-0" align="start">
                <Command>
                  <CommandInput 
                    placeholder="Search models..." 
                    value={searchQuery}
                    onValueChange={setSearchQuery}
                  />
                  <div className="p-2 border-b">
                    <div className="flex flex-col gap-2">
                      {/* Provider Filter */}
                      <div className="flex items-center gap-2">
                        <Filter className="w-3 h-3" />
                        <Select value={selectedProvider} onValueChange={setSelectedProvider}>
                          <SelectTrigger className="h-7 text-xs">
                            <SelectValue placeholder="Provider" />
                          </SelectTrigger>
                          <SelectContent>
                            <SelectItem value="all">All Providers</SelectItem>
                            {providers.map(p => (
                              <SelectItem key={p} value={p}>{p}</SelectItem>
                            ))}
                          </SelectContent>
                        </Select>
                      </div>
                      
                      {/* Price Filter */}
                      <div className="flex flex-col gap-1">
                        <div className="flex justify-between text-[10px] text-muted-foreground">
                          <span>Max Price: ${maxPrice[0]}/1M tokens</span>
                        </div>
                        <Slider 
                          value={maxPrice} 
                          onValueChange={setMaxPrice}
                          max={100}
                          step={5}
                          className="w-full"
                        />
                      </div>
                      
                      {/* Context Length Filter */}
                      <div className="flex items-center gap-2">
                        <Checkbox
                          id="context-filter"
                          checked={minContextLength}
                          onCheckedChange={(checked) => setMinContextLength(checked as boolean)}
                        />
                        <label htmlFor="context-filter" className="text-xs cursor-pointer">
                          Context ≥ 100k tokens
                        </label>
                      </div>
                    </div>
                  </div>
                  <CommandList>
                    <CommandEmpty>No models found.</CommandEmpty>
                    <CommandGroup>
                      {filteredModels.map((model) => (
                        <CommandItem
                          key={model.id}
                          value={model.id}
                          onSelect={(value) => {
                            setSelectedModel(value)
                            setModelSearchOpen(false)
                          }}
                        >
                          <Check
                            className={cn(
                              "mr-2 h-4 w-4",
                              selectedModel === model.id ? "opacity-100" : "opacity-0"
                            )}
                          />
                          <div className="flex flex-col flex-1">
                            <span className="font-semibold">{model.name}</span>
                            <span className="text-[10px] text-muted-foreground">
                              ${model.promptPrice}/${model.completionPrice} • {model.contextLength.toLocaleString()} ctx
                            </span>
                          </div>
                        </CommandItem>
                      ))}
                    </CommandGroup>
                  </CommandList>
                </Command>
              </PopoverContent>
            </Popover>

            {/* Target Level */}
            <div className="flex items-center gap-2">
              <span className="text-muted-foreground">TARGET LEVEL:</span>
              <Select 
                value={String(targetLevel)} 
                onValueChange={(v) => setTargetLevel(Number(v))}
                disabled={agentState.status === 'running'}
              >
                <SelectTrigger className="w-[60px] h-8 font-mono text-xs">
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  {Array.from({ length: 34 }, (_, i) => (
                    <SelectItem key={i} value={String(i)}>{i}</SelectItem>
                  ))}
                </SelectContent>
              </Select>
            </div>

            {/* Streaming Mode */}
            <Select 
              value={streamingMode} 
              onValueChange={(v) => setStreamingMode(v as 'selective' | 'all_events')}
              disabled={agentState.status === 'running'}
            >
              <SelectTrigger className="w-[120px] h-8 font-mono text-xs">
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="selective">Selective</SelectItem>
                <SelectItem value="all_events">All Events</SelectItem>
              </SelectContent>
            </Select>
          </div>

          {/* Divider */}
          <div className="hidden lg:block h-8 w-px bg-border" />

          {/* Action Buttons */}
          <div className="flex items-center gap-2">
            {agentState.status === 'idle' && (
              <Button 
                size="sm" 
                onClick={handleStart}
                className="h-8 font-mono text-xs gap-1.5"
              >
                <Play className="w-3.5 h-3.5" />
                START
              </Button>
            )}
            
            {agentState.status === 'running' && (
              <Button 
                size="sm" 
                variant="outline"
                onClick={onPauseRun}
                className="h-8 font-mono text-xs gap-1.5"
              >
                <Pause className="w-3.5 h-3.5" />
                PAUSE
              </Button>
            )}
            
            {agentState.status === 'paused' && (
              <>
                <Button 
                  size="sm" 
                  onClick={onResumeRun}
                  className="h-8 font-mono text-xs gap-1.5"
                >
                  <Play className="w-3.5 h-3.5" />
                  RESUME
                </Button>
                <Button 
                  size="sm" 
                  variant="outline"
                  onClick={onStopRun}
                  className="h-8 font-mono text-xs gap-1.5"
                >
                  <Square className="w-3.5 h-3.5" />
                  STOP
                </Button>
              </>
            )}

            {(agentState.status === 'complete' || agentState.status === 'failed') && (
              <Button 
                size="sm" 
                variant="outline"
                onClick={() => window.location.reload()}
                className="h-8 font-mono text-xs gap-1.5"
              >
                <RotateCw className="w-3.5 h-3.5" />
                NEW RUN
              </Button>
            )}

            {/* Connection Indicator */}
            <div className="flex items-center gap-1.5 pl-2 border-l border-border">
              <div className={`w-2 h-2 ${agentState.isConnected ? 'bg-green-500 animate-pulse' : 'bg-muted-foreground'}`} />
              <span className="text-[10px] text-muted-foreground hidden xl:inline">
                {agentState.isConnected ? 'CONNECTED' : 'DISCONNECTED'}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

