"use client"

import type React from "react"
import { useState, useRef, useEffect, useMemo } from "react"
import { Github, AlertTriangle } from "lucide-react"
import { Input } from "@/components/ui/shadcn-io/input"
import { ScrollArea } from "@/components/ui/shadcn-io/scroll-area"
import { Switch } from "@/components/ui/shadcn-io/switch"
import { ThemeToggle } from "@/components/theme-toggle"
import { SecurityIcon } from "@/components/retro-icons"
import { AgentControlPanel, type AgentState } from "@/components/agent-control-panel"
import { useAgentWebSocket } from "@/hooks/useAgentWebSocket"
import type { RunConfig } from "@/lib/agents/bandit-state"
import { cn } from "@/lib/utils"
import Convert from "ansi-to-html"

interface TerminalLine {
  type: "input" | "output" | "error" | "system"
  content: string
  timestamp: Date
  level?: number
  command?: string
}

interface ChatMessage {
  type: "user" | "agent" | "typing" | "thinking" | "tool_call"
  content: string
  timestamp: Date
  level?: number
  metadata?: {
    modelName?: string
    tokenCount?: number
    executionTime?: number
  }
}

const SCAN_LINES_OVERLAY =
  "absolute inset-0 pointer-events-none bg-[linear-gradient(transparent_50%,hsl(var(--primary)/0.03)_50%)] bg-[length:100%_4px] animate-scan-lines"

const GRID_PATTERN =
  "absolute inset-0 pointer-events-none opacity-[0.015] bg-[linear-gradient(hsl(var(--primary))_1px,transparent_1px),linear-gradient(90deg,hsl(var(--primary))_1px,transparent_1px)] bg-[size:20px_20px]"

export function TerminalChatInterface() {
  // Agent state
  const [runId, setRunId] = useState<string | null>(null)
  const [agentState, setAgentState] = useState<AgentState>({
    runId: null,
    status: 'idle',
    currentLevel: 0,
    modelProvider: 'openrouter',
    modelName: 'GPT-4o Mini',
    streamingMode: 'selective',
    isConnected: false,
  })

  // WebSocket integration
  const {
    connectionState,
    sendCommand,
    sendMessage,
    terminalLines: wsTerminalLines,
    chatMessages: wsChatMessages,
    setTerminalLines: setWsTerminalLines,
    setChatMessages: setWsChatMessages,
  } = useAgentWebSocket(runId)

  // Local state for UI
  const [currentCommand, setCurrentCommand] = useState("")
  const [chatInput, setChatInput] = useState("")
  const [commandHistory, setCommandHistory] = useState<string[]>([])
  const [historyIndex, setHistoryIndex] = useState(-1)
  const [sessionTime, setSessionTime] = useState("")
  const [focusedPanel, setFocusedPanel] = useState<"terminal" | "chat">("terminal")
  const [mounted, setMounted] = useState(false)
  const [manualMode, setManualMode] = useState(false)
  
  const terminalScrollRef = useRef<HTMLDivElement>(null)
  const chatScrollRef = useRef<HTMLDivElement>(null)
  const terminalInputRef = useRef<HTMLInputElement>(null)
  const chatInputRef = useRef<HTMLInputElement>(null)
  
  // ANSI to HTML converter
  const ansiConverter = useMemo(() => new Convert({
    fg: '#d4d4d4',
    bg: 'transparent',
    newline: false,
    escapeXML: true,
    stream: false,
  }), [])

  // Initialize terminal with welcome messages
  useEffect(() => {
    if (wsTerminalLines.length === 0) {
      setWsTerminalLines([
        { type: "output", content: "Bandit Runner Console v2.0 - LangGraph Edition", timestamp: new Date() },
        { type: "output", content: "System initialized. Configure and start a run to begin.", timestamp: new Date() },
        { type: "output", content: "", timestamp: new Date() },
      ])
    }
    if (wsChatMessages.length === 0) {
      setWsChatMessages([
        { type: "agent", content: "Agent ready. Configure your run settings above and click START.", timestamp: new Date() },
      ])
    }
  }, [])

  // Update agent connection status
  useEffect(() => {
    setAgentState(prev => ({
      ...prev,
      isConnected: connectionState === 'connected',
    }))
  }, [connectionState])

  useEffect(() => {
    setMounted(true)
    setSessionTime(new Date().toLocaleTimeString())
    terminalInputRef.current?.focus()
  }, [])

  useEffect(() => {
    if (terminalScrollRef.current) {
      const viewport = terminalScrollRef.current.querySelector('[data-radix-scroll-area-viewport]')
      if (viewport) {
        viewport.scrollTop = viewport.scrollHeight
      }
    }
  }, [wsTerminalLines])

  useEffect(() => {
    if (chatScrollRef.current) {
      const viewport = chatScrollRef.current.querySelector('[data-radix-scroll-area-viewport]')
      if (viewport) {
        viewport.scrollTop = viewport.scrollHeight
      }
    }
  }, [wsChatMessages])

  const formatTimestamp = (date: Date) => {
    return date.toLocaleTimeString("en-US", { hour12: false, hour: "2-digit", minute: "2-digit", second: "2-digit" })
  }

  // Agent control handlers
  const handleStartRun = async (config: Partial<RunConfig>) => {
    const newRunId = `run-${Date.now()}`
    
    try {
      const response = await fetch(`/api/agent/${newRunId}/start`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(config),
      })

      if (response.ok) {
        const data = await response.json()
        setRunId(newRunId)
        setAgentState(prev => ({
          ...prev,
          runId: newRunId,
          status: 'running',
          currentLevel: config.startLevel || 0,
          modelName: config.modelName || prev.modelName,
        }))
        
        setWsChatMessages(prev => [
          ...prev,
          {
            type: 'agent',
            content: `Run started with ${config.modelName}`,
            timestamp: new Date(),
          },
        ])
      }
    } catch (error) {
      console.error('Failed to start run:', error)
      setWsChatMessages(prev => [
        ...prev,
        {
          type: 'agent',
          content: `Error starting run: ${error instanceof Error ? error.message : 'Unknown error'}`,
          timestamp: new Date(),
        },
      ])
    }
  }

  const handlePauseRun = async () => {
    if (!runId) return

    try {
      await fetch(`/api/agent/${runId}/pause`, { method: 'POST' })
      setAgentState(prev => ({ ...prev, status: 'paused' }))
    } catch (error) {
      console.error('Failed to pause run:', error)
    }
  }

  const handleResumeRun = async () => {
    if (!runId) return

    try {
      await fetch(`/api/agent/${runId}/resume`, { method: 'POST' })
      setAgentState(prev => ({ ...prev, status: 'running' }))
    } catch (error) {
      console.error('Failed to resume run:', error)
    }
  }

  const handleStopRun = () => {
    setRunId(null)
    setAgentState(prev => ({ ...prev, status: 'idle', runId: null }))
  }

  const handleCommandSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    if (!currentCommand.trim()) return

    const command = currentCommand.trim()
    setCommandHistory((prev) => [...prev, command])
    setHistoryIndex(-1)

    // Add to local display
    setWsTerminalLines((prev) => [
      ...prev,
      { type: "input", content: `$ ${command}`, timestamp: new Date() },
    ])

    // Send to agent if connected
    if (agentState.status === 'running' || agentState.status === 'paused') {
      sendCommand(command)
    } else {
      // Manual mode
      setWsTerminalLines((prev) => [
        ...prev,
        {
          type: "system",
          content: `[MANUAL MODE] Start a run to execute commands via agent`,
          timestamp: new Date(),
        },
      ])
    }

    setCurrentCommand("")
  }

  const handleChatSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    if (!chatInput.trim()) return

    const message = chatInput.trim()
    setWsChatMessages((prev) => [
      ...prev,
      {
        type: "user",
        content: message,
        timestamp: new Date(),
      },
    ])

    setChatInput("")

    // Send to agent if connected
    if (agentState.status === 'running' || agentState.status === 'paused') {
      sendMessage(message)
    } else {
      // Configuration mode - show helpful response
      setWsChatMessages((prev) => [
        ...prev,
        {
          type: "agent",
          content: "Configure your run settings above and click START to begin.",
          timestamp: new Date(),
        },
      ])
    }
  }

  const handleCommandKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "ArrowUp") {
      e.preventDefault()
      if (commandHistory.length === 0) return
      const newIndex = historyIndex === -1 ? commandHistory.length - 1 : Math.max(0, historyIndex - 1)
      setHistoryIndex(newIndex)
      setCurrentCommand(commandHistory[newIndex])
    } else if (e.key === "ArrowDown") {
      e.preventDefault()
      if (historyIndex === -1) return
      const newIndex = historyIndex + 1
      if (newIndex >= commandHistory.length) {
        setHistoryIndex(-1)
        setCurrentCommand("")
      } else {
        setHistoryIndex(newIndex)
        setCurrentCommand(commandHistory[newIndex])
      }
    } else if (e.key === "Escape") {
      setFocusedPanel("chat")
      chatInputRef.current?.focus()
    }
  }

  const handleChatKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === "Escape") {
      setFocusedPanel("terminal")
      terminalInputRef.current?.focus()
    }
  }

  useEffect(() => {
    const handleGlobalKeyDown = (e: KeyboardEvent) => {
      if (e.key === "j" && e.ctrlKey) {
        e.preventDefault()
        setFocusedPanel("chat")
        chatInputRef.current?.focus()
      } else if (e.key === "k" && e.ctrlKey) {
        e.preventDefault()
        setFocusedPanel("terminal")
        terminalInputRef.current?.focus()
      }
    }

    window.addEventListener("keydown", handleGlobalKeyDown)
    return () => window.removeEventListener("keydown", handleGlobalKeyDown)
  }, [])

  return (
    <div className="h-screen w-full bg-background flex flex-col font-mono overflow-hidden p-3 sm:p-6 md:p-8">
      <div className="w-full max-w-[1900px] mx-auto flex flex-col h-full gap-4 sm:gap-6">
        {/* Header with corner accents */}
        <div className="relative flex-shrink-0">
          {/* Corner brackets */}
          <div className="absolute -left-1 -top-1 w-6 h-6 border-l-2 border-t-2 border-primary" />
          <div className="absolute -right-1 -top-1 w-6 h-6 border-r-2 border-t-2 border-primary" />
          <div className="absolute -left-1 -bottom-1 w-6 h-6 border-l-2 border-b-2 border-primary" />
          <div className="absolute -right-1 -bottom-1 w-6 h-6 border-r-2 border-b-2 border-primary" />
          
          <div className="border-l border-r border-border bg-card px-6 sm:px-8 py-3 sm:py-4">
            <div className="flex items-center justify-between gap-4">
              <div className="flex items-center gap-3 sm:gap-4">
                <div className="w-1 h-8 bg-primary" />
                <SecurityIcon className="w-5 h-5 sm:w-6 sm:h-6 text-primary hidden xs:block" />
                <div>
                  <div className="text-foreground text-sm sm:text-base font-bold tracking-wider">
                    BANDIT RUNNER
                  </div>
                  <div className="text-muted-foreground text-[10px] sm:text-xs">
                    Security Automation Console
                  </div>
                </div>
              </div>
              <div className="flex items-center gap-2 sm:gap-4 text-[10px] sm:text-xs">
                {mounted && (
                  <div className="hidden md:flex items-center gap-2">
                    <span className="text-muted-foreground">SESSION</span>
                    <span className="text-primary font-mono">{sessionTime}</span>
                  </div>
                )}
                <div className="flex items-center gap-1.5">
                  <div className="w-2 h-2 bg-accent-foreground" />
                  <span className="text-accent-foreground font-bold">ONLINE</span>
                </div>
                <a
                  href="https://git.biohazardvfx.com/Nicholai/bandit-runner"
                  target="_blank"
                  rel="noopener noreferrer"
                  className="w-8 h-8 flex items-center justify-center border border-border bg-card text-muted-foreground hover:text-primary hover:border-primary transition-colors"
                  title="View Repository"
                >
                  <Github className="w-4 h-4" />
                </a>
                <ThemeToggle />
              </div>
            </div>
          </div>
        </div>

        {/* Agent Control Panel */}
        <AgentControlPanel
          agentState={agentState}
          onStartRun={handleStartRun}
          onPauseRun={handlePauseRun}
          onResumeRun={handleResumeRun}
          onStopRun={handleStopRun}
        />

        {/* Main content area */}
        <div className="flex-1 grid grid-cols-1 lg:grid-cols-[1.2fr_0.8fr] gap-4 sm:gap-6 min-h-0">
          {/* Terminal Panel */}
          <div className="relative flex flex-col h-[55vh] lg:h-auto">
            {/* Corner accents */}
            <div className="absolute -left-1 -top-1 w-4 h-4 border-l-2 border-t-2 border-primary z-20" />
            <div className="absolute -right-1 -top-1 w-4 h-4 border-r-2 border-t-2 border-primary z-20" />
            
            <div className="flex-1 flex flex-col border border-border bg-card relative overflow-hidden">
              <div className={GRID_PATTERN} />
              <div className={SCAN_LINES_OVERLAY} />
              
              {/* Header */}
              <div className="relative z-10 flex items-center justify-between px-4 py-2 border-b border-border bg-muted/30">
                <div className="flex items-center gap-2">
                  <div className="w-1 h-4 bg-primary" />
                  <span className="text-foreground text-xs font-bold tracking-widest">TERMINAL</span>
                </div>
                <div className="flex gap-1.5">
                  <div className="w-3 h-3 border border-primary/40" />
                  <div className="w-3 h-3 border border-primary/40" />
                  <div className="w-3 h-3 border border-primary" />
                </div>
              </div>

              {/* Terminal content */}
              <ScrollArea ref={terminalScrollRef} className="flex-1 relative z-10 h-full">
                <div className="p-4 space-y-1">
                  {wsTerminalLines.map((line, idx) => (
                    <div
                      key={idx}
                      className={cn(
                        "text-xs md:text-sm leading-relaxed flex gap-3 font-mono",
                        line.type === "input" && "text-accent-foreground font-bold",
                        line.type === "output" && "text-foreground/80",
                        line.type === "error" && "text-destructive",
                        line.type === "system" && "text-primary/80",
                      )}
                    >
                      {line.content && (
                        <>
                          <span className="text-muted-foreground text-[10px] sm:text-xs flex-shrink-0 w-20">
                            {formatTimestamp(line.timestamp)}
                          </span>
                          <span 
                            className="flex-1"
                            dangerouslySetInnerHTML={{ 
                              __html: ansiConverter.toHtml(line.content)
                            }}
                          />
                        </>
                      )}
                    </div>
                  ))}
                </div>
              </ScrollArea>

              {/* Manual Mode Warning */}
              {manualMode && (
                <div className="border-t border-yellow-500/30 bg-yellow-500/10 px-3 py-2 flex items-center gap-2 text-yellow-500 relative z-10">
                  <AlertTriangle className="w-4 h-4" />
                  <span className="text-xs font-mono">
                    MANUAL MODE ACTIVE - Run disqualified from leaderboards
                  </span>
                </div>
              )}

              {/* Input area */}
              <div className="border-t border-border p-3 bg-muted/20 relative z-10">
                <form onSubmit={handleCommandSubmit} className="flex items-center gap-2">
                  <div className="flex items-center gap-2 text-primary">
                    <div className="w-1 h-4 bg-primary" />
                    <span className="text-sm">$</span>
                  </div>
                  <Input
                    ref={terminalInputRef}
                    value={currentCommand}
                    onChange={(e) => setCurrentCommand(e.target.value)}
                    onKeyDown={handleCommandKeyDown}
                    placeholder={manualMode ? "enter command..." : "read-only (enable manual mode to type)"}
                    disabled={!manualMode}
                    className="flex-1 bg-transparent border-0 text-foreground placeholder:text-muted-foreground focus-visible:ring-0 focus-visible:ring-offset-0 font-mono text-sm h-6 px-0 caret-primary disabled:opacity-50"
                  />
                </form>
              </div>

              {/* Footer */}
              <div className="border-t border-border px-3 py-1.5 bg-muted/30 relative z-10">
                <div className="flex items-center justify-between text-[10px] text-muted-foreground">
                  <div className="flex items-center gap-3">
                    <span className="hidden sm:inline">user@bandit-runner</span>
                    <div className="flex items-center gap-2">
                      <Switch
                        id="manual-mode"
                        checked={manualMode}
                        onCheckedChange={setManualMode}
                        className="scale-75"
                      />
                      <label htmlFor="manual-mode" className="cursor-pointer">
                        Manual Mode
                      </label>
                    </div>
                  </div>
                  <span>↑↓ history • ESC switch panels</span>
                </div>
              </div>
            </div>
          </div>

          {/* Agent Panel */}
          <div className="relative flex flex-col h-[40vh] lg:h-auto">
            {/* Corner accents */}
            <div className="absolute -left-1 -top-1 w-4 h-4 border-l-2 border-t-2 border-primary z-20" />
            <div className="absolute -right-1 -top-1 w-4 h-4 border-r-2 border-t-2 border-primary z-20" />
            
            <div className="flex-1 flex flex-col border border-border bg-card relative overflow-hidden">
              <div className={GRID_PATTERN} />
              <div className={SCAN_LINES_OVERLAY} />
              
              {/* Header */}
              <div className="relative z-10 flex items-center justify-between px-4 py-2 border-b border-border bg-muted/30">
                <div className="flex items-center gap-2">
                  <div className="w-1 h-4 bg-accent-foreground" />
                  <span className="text-foreground text-xs font-bold tracking-widest">AGENT</span>
                </div>
                <div className="flex gap-1.5">
                  <div className="w-3 h-3 border border-accent-foreground/40" />
                  <div className="w-3 h-3 border border-accent-foreground" />
                </div>
              </div>

              {/* Messages */}
              <ScrollArea ref={chatScrollRef} className="flex-1 relative z-10 h-full">
                <div className="p-4 space-y-4">
                  {wsChatMessages.map((msg, idx) => (
                    <div key={idx} className="space-y-1">
                      <div className="flex items-center gap-2 text-[10px]">
                        <span className="text-muted-foreground font-mono">
                          {formatTimestamp(msg.timestamp)}
                        </span>
                        <div className="h-px flex-1 bg-border" />
                        <span className={cn(
                          "font-bold px-2 py-0.5 border",
                          msg.type === "user" 
                            ? "text-accent-foreground border-accent-foreground/30" 
                            : "text-primary border-primary/30"
                        )}>
                          {msg.type === "user" ? "USER" : "AGENT"}
                        </span>
                      </div>
                      <div className={cn(
                        "text-xs md:text-sm leading-relaxed pl-4 border-l-2 font-mono",
                        msg.type === "user" 
                          ? "text-accent-foreground border-accent-foreground/30" 
                          : "text-foreground/80 border-primary/30"
                      )}>
                        {msg.content}
                      </div>
                    </div>
                  ))}
                  {wsChatMessages.some(msg => msg.type === 'thinking') && (
                    <div className="space-y-1">
                      <div className="flex items-center gap-2 text-[10px]">
                        <span className="text-muted-foreground font-mono">
                          {formatTimestamp(new Date())}
                        </span>
                        <div className="h-px flex-1 bg-border" />
                        <span className="text-primary border border-primary/30 font-bold px-2 py-0.5">
                          THINKING
                        </span>
                      </div>
                      <div className="text-xs md:text-sm text-foreground/60 pl-4 border-l-2 border-primary/30 flex items-center gap-2">
                        <span>Processing</span>
                        <span className="animate-cursor-blink text-primary">▊</span>
                      </div>
                    </div>
                  )}
                </div>
              </ScrollArea>

              {/* Input area */}
              <div className="border-t border-border p-3 bg-muted/20 relative z-10">
                <form onSubmit={handleChatSubmit} className="flex items-center gap-2 bg-background/40 px-3 py-2 border border-border/50">
                  <div className="flex items-center gap-2 text-primary">
                    <div className="w-1 h-4 bg-accent-foreground" />
                    <span className="text-sm">›</span>
                  </div>
                  <Input
                    ref={chatInputRef}
                    value={chatInput}
                    onChange={(e) => setChatInput(e.target.value)}
                    onKeyDown={handleChatKeyDown}
                    placeholder="message agent..."
                    className="flex-1 bg-transparent border-0 text-foreground placeholder:text-muted-foreground focus-visible:ring-0 focus-visible:ring-offset-0 font-mono text-sm h-6 px-0 caret-accent-foreground"
                  />
                </form>
              </div>

              {/* Footer */}
              <div className="border-t border-border px-3 py-1.5 bg-muted/30 relative z-10">
                <div className="flex items-center justify-between text-[10px] text-muted-foreground">
                  <span>Ctrl+K/J nav</span>
                  <span className="hidden sm:inline">{agentState.modelName || 'No Model'}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
