'use client'

/**
 * AWOOOI Omni-Terminal
 * ==========================
 * Phase 19 - AI 代理人協作終端
 *
 * 快捷鍵: CMD+J (避免與瀏覽器 CMD+K 衝突)
 *
 * 響應式設計 (Phase 19.R):
 * - Mobile (<640px): 全螢幕 overlay
 * - Tablet (640-1024px): 底部 80% 寬度
 * - Desktop (>1024px): 底部居中 max-w-4xl
 *
 * @see ADR-031 Omni-Terminal SSE Architecture
 * @see lib/constants/z-index.ts
 * @see lib/constants/shortcuts.ts
 *
 * @author Claude Code (首席架構師)
 * @version 2.1.0 - 響應式設計
 * @date 2026-03-28 (台北時間)
 */

import React, { useEffect, useRef, useState } from 'react'
import { useTranslations } from 'next-intl'
import {
  useTerminalStore,
  useIsConnected,
  useTerminalMessages,
  useIsTerminalOpen,
  type TerminalMessage,
} from '@/stores/terminal.store'
import { GenUIRenderer, isRegistered } from '@/components/genui'
import { Z_INDEX } from '@/lib/constants/z-index'
import { SHORTCUTS, matchShortcut } from '@/lib/constants/shortcuts'

export const OmniTerminal = () => {
  const t = useTranslations('omniTerminal')
  // Use optimized selectors for better re-render performance
  const isOpen = useIsTerminalOpen()
  const messages = useTerminalMessages()
  const isConnected = useIsConnected()
  const { sendIntent, toggleTerminal, openTerminal } = useTerminalStore()

  const [inputValue, setInputValue] = useState('')
  const inputRef = useRef<HTMLInputElement>(null)
  const scrollRef = useRef<HTMLDivElement>(null)

  // 快捷鍵處理 (Phase 19 - 完整鍵盤支援)
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      // CMD+J: Toggle Terminal (全局)
      if (matchShortcut(e, SHORTCUTS.TOGGLE_TERMINAL)) {
        e.preventDefault()
        toggleTerminal()
        return
      }

      // Escape: 關閉 Terminal (當 Terminal 開啟時)
      if (e.key === 'Escape' && isOpen) {
        e.preventDefault()
        toggleTerminal()
        return
      }

      // '/': Quick open (非輸入框時，Terminal 關閉時)
      if (e.key === '/' && !isOpen && document.activeElement?.tagName !== 'INPUT') {
        e.preventDefault()
        openTerminal()
      }
    }
    window.addEventListener('keydown', handleKeyDown)
    return () => window.removeEventListener('keydown', handleKeyDown)
  }, [toggleTerminal, openTerminal, isOpen])

  // Focus input when opened
  useEffect(() => {
    if (isOpen && inputRef.current) {
      inputRef.current.focus()
    }
  }, [isOpen])

  // Auto-scroll to bottom
  useEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.scrollTop = scrollRef.current.scrollHeight
    }
  }, [messages])

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    if (!inputValue.trim()) return
    
    sendIntent(inputValue)
    setInputValue('')
  }

  if (!isOpen) {
    return (
      <button
        onClick={openTerminal}
        className="fixed bottom-4 right-4 px-3 py-2 sm:px-4 bg-white/70 backdrop-blur-[20px] border border-gray-200 rounded-md shadow-sm text-nothing-black hover:bg-white transition-all flex items-center gap-2 group"
        style={{ zIndex: Z_INDEX.OMNI_TERMINAL }}
        aria-label="Open Omni-Terminal"
      >
        <span className="w-2 h-2 rounded-full bg-[#4A90D9] animate-pulse"></span>
        <span className="font-['VT323'] text-base sm:text-lg">
          <span className="hidden sm:inline">Omni-Terminal </span>[⌘J]
        </span>
      </button>
    )
  }

  const renderMessageContent = (msg: TerminalMessage) => {
    // GenUI rendering: Handle render_ui type messages
    if (msg.type === 'render_ui' && msg.payload) {
      const component = msg.payload.component as string | undefined
      const props = msg.payload.props as Record<string, unknown> | undefined

      if (component && props && isRegistered(component)) {
        return (
          <GenUIRenderer
            component={component}
            props={props}
            position="inline"
          />
        )
      }

      return (
        <div className="text-gray-500 italic">
          [GenUI: Unknown Component {component ?? 'undefined'}]
        </div>
      )
    }

    // Tool call display
    if (msg.type === 'tool_call' && msg.payload) {
      const tool = msg.payload.tool as string | undefined
      const status = msg.payload.status as string | undefined
      const result = msg.payload.result as Record<string, unknown> | undefined

      return (
        <div className={`font-mono text-sm ${status === 'completed' ? 'text-green-600' : status === 'failed' ? 'text-red-600' : 'text-yellow-600'}`}>
          <span className="opacity-70">[{tool ?? 'unknown'}]</span>{' '}
          <span className="font-bold">{status ?? 'executing'}</span>
          {result && (
            <span className="text-gray-500 ml-2">
              {JSON.stringify(result).slice(0, 100)}
            </span>
          )}
        </div>
      )
    }

    // Thought display
    if (msg.type === 'thought' && msg.payload) {
      const agent = msg.payload.agent as string | undefined

      return (
        <div className="text-purple-600">
          <span className="opacity-50">[{agent ?? 'AI'}]</span> {msg.content}
        </div>
      )
    }

    return (
      <span className={msg.role === 'assistant' ? 'text-[#4A90D9]' : 'text-nothing-black'}>
        {msg.content}
      </span>
    )
  }

  return (
    <>
      {/* Backdrop overlay for mobile - 點擊可關閉 */}
      <div
        className="fixed inset-0 bg-black/20 backdrop-blur-sm sm:hidden"
        style={{ zIndex: Z_INDEX.OMNI_TERMINAL - 1 }}
        onClick={toggleTerminal}
        aria-hidden="true"
      />

      <div
        className="fixed inset-x-0 bottom-0 flex justify-center px-2 pb-2 sm:px-4 sm:pb-4"
        style={{ zIndex: Z_INDEX.OMNI_TERMINAL }}
      >
        {/* Responsive container:
            - Mobile: 底部彈出 (不再全螢幕!)
            - Tablet: 90% width
            - Desktop: max-w-4xl centered */}
        <div
          className="w-full sm:w-[90%] lg:max-w-4xl bg-white/95 backdrop-blur-[20px] border border-gray-200 rounded-xl shadow-2xl overflow-hidden flex flex-col transition-all"
          style={{ maxHeight: '70vh', minHeight: '200px' }}
          role="dialog"
          aria-label="Omni-Terminal"
          aria-modal="true"
        >

        {/* Terminal Header */}
        <div className="flex justify-between items-center px-3 sm:px-4 py-2 border-b border-gray-200 bg-white/40">
          <div className="flex items-center gap-2 sm:gap-3">
            <span className="font-['VT323'] text-base sm:text-lg text-[#4A90D9]">
              <span className="hidden sm:inline">AWOOOI // </span>OMNI-TERMINAL
            </span>
            <div className="flex items-center gap-1 opacity-60">
               <span className={`w-2 h-2 rounded-full ${isConnected ? 'bg-green-500' : 'bg-gray-400'}`}></span>
               <span className="text-xs uppercase font-mono hidden sm:inline">{isConnected ? t('sseLive') : t('offline')}</span>
            </div>
          </div>
          <button
            onClick={toggleTerminal}
            className="text-gray-500 hover:text-black font-mono px-2 py-1"
            aria-label="Close terminal"
          >
            [x]
          </button>
        </div>

        {/* Messages / GenUI Canvas */}
        <div
          ref={scrollRef}
          className="flex-1 overflow-y-auto p-3 sm:p-4 font-['VT323'] text-lg sm:text-xl space-y-3 sm:space-y-4"
          role="log"
          aria-live="polite"
        >
          {messages.map((msg, i) => (
            <div key={`${msg.id}-${i}`} className="flex flex-col">
              <div className="flex gap-2">
                <span className="opacity-50 select-none text-sm sm:text-base shrink-0">
                  {msg.role === 'system' ? '[SYS]' : msg.role === 'user' ? '$' : '[AI]'}
                </span>
                <div className="flex-1 break-words whitespace-pre-wrap">
                  {renderMessageContent(msg)}
                </div>
              </div>
            </div>
          ))}
        </div>

        {/* Input Bar */}
        <div className="p-3 sm:p-4 border-t border-gray-200 bg-white/40">
          <form onSubmit={handleSubmit} className="flex gap-2 items-center">
            <span className="text-[#4A90D9] font-['VT323'] text-xl sm:text-2xl select-none">{'>'}</span>
            <input
              ref={inputRef}
              type="text"
              value={inputValue}
              onChange={(e) => setInputValue(e.target.value)}
              placeholder={t('inputPlaceholder')}
              className="flex-1 bg-transparent border-none outline-none font-['VT323'] text-xl sm:text-2xl text-nothing-black placeholder-gray-400"
              autoComplete="off"
              spellCheck="false"
              aria-label="Terminal input"
            />
          </form>
          </div>
        </div>
      </div>
    </>
  )
}
