import { useState, useEffect, useRef } from 'react'
import { useMutation } from '@tanstack/react-query'
import { Terminal, RefreshCw, Trash2, Command } from 'lucide-react'
import { Button } from '@/components/ui/button'
import apiClient from '@/api/client'

interface CommandHistory {
  command: string
  output: string
  timestamp: Date
  error?: boolean
  service?: string
}

export default function TerminalConsole() {
  const [commandHistory, setCommandHistory] = useState<CommandHistory[]>([])
  const [currentCommand, setCurrentCommand] = useState('')
  const [isExecuting, setIsExecuting] = useState(false)
  const [selectedService, setSelectedService] = useState<string>('system')
  const terminalRef = useRef<HTMLDivElement>(null)
  const inputRef = useRef<HTMLInputElement>(null)

  // Auto-scroll to bottom when new output is added
  useEffect(() => {
    if (terminalRef.current) {
      terminalRef.current.scrollTop = terminalRef.current.scrollHeight
    }
  }, [commandHistory])

  // Focus input on mount
  useEffect(() => {
    if (inputRef.current) {
      inputRef.current.focus()
    }
  }, [])

  const executeCommand = useMutation({
    mutationFn: async (cmd: string) => {
      const response = await apiClient.post('/system/execute', {
        command: cmd,
        service: selectedService,
      })
      return response.data
    },
    onSuccess: (data, command) => {
      setCommandHistory((prev) => [
        ...prev,
        {
          command,
          output: data.output || data.error || 'Command executed',
          timestamp: new Date(),
          error: !!data.error,
          service: selectedService,
        },
      ])
      setCurrentCommand('')
      setIsExecuting(false)
      setTimeout(() => {
        if (inputRef.current) {
          inputRef.current.focus()
        }
      }, 100)
    },
    onError: (error: any) => {
      setCommandHistory((prev) => [
        ...prev,
        {
          command: currentCommand,
          output: error?.response?.data?.error || error?.response?.data?.output || error.message || 'Error executing command',
          timestamp: new Date(),
          error: true,
          service: selectedService,
        },
      ])
      setCurrentCommand('')
      setIsExecuting(false)
      setTimeout(() => {
        if (inputRef.current) {
          inputRef.current.focus()
        }
      }, 100)
    },
  })

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    const cmd = currentCommand.trim()
    if (!cmd || isExecuting) return

    setIsExecuting(true)
    executeCommand.mutate(cmd)
  }

  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    // Handle Ctrl+L to clear
    if (e.ctrlKey && e.key === 'l') {
      e.preventDefault()
      if (confirm('Clear terminal history?')) {
        setCommandHistory([])
      }
    }
    // Handle Up arrow for command history (future enhancement)
    if (e.key === 'ArrowUp') {
      e.preventDefault()
      // TODO: Implement command history navigation
    }
  }

  const handleClear = () => {
    if (confirm('Clear terminal history?')) {
      setCommandHistory([])
    }
  }

  const getServiceCommands = (service: string) => {
    const commands: Record<string, string[]> = {
      system: [
        'ls -la',
        'df -h',
        'free -h',
        'systemctl status scst',
        'scstadmin -list_target',
        'scstadmin -list_device',
        'ip addr show',
        'journalctl -u calypso-api -n 50',
        'ps aux | grep calypso',
        'netstat -tulpn | grep 8080',
      ],
      scst: [
        'scstadmin -list_target',
        'scstadmin -list_device',
        'scstadmin -list_handler',
        'scstadmin -list_driver',
        'scstadmin -list_group',
        'scstadmin -list',
        'cat /etc/scst.conf',
        'systemctl status scst',
        'systemctl status iscsi-scst',
      ],
      storage: [
        'zfs list',
        'zpool status',
        'zpool list',
        'lsblk',
        'df -h',
        'zfs get all',
        'zpool get all',
      ],
      backup: [
        'bconsole -c "list jobs"',
        'bconsole -c "list clients"',
        'bconsole -c "list pools"',
        'systemctl status bacula-director',
        'systemctl status bacula-sd',
        'systemctl status bacula-fd',
      ],
      tape: [
        'lsscsi -g',
        'mtx -f /dev/sgX status',
        'sg_inq /dev/sgX',
        'systemctl status mhvtl',
      ],
    }
    return commands[service] || []
  }

  return (
    <div className="flex-1 overflow-y-auto p-8">
      <div className="max-w-[1400px] mx-auto flex flex-col gap-6 h-full">
        {/* Header */}
        <div className="flex flex-wrap justify-between items-end gap-4">
          <div className="flex flex-col gap-2">
            <h1 className="text-white text-3xl font-extrabold leading-tight tracking-tight flex items-center gap-3">
              <Terminal className="text-primary" size={32} />
              Terminal Console
            </h1>
            <p className="text-text-secondary text-base font-normal">
              Execute shell commands and manage all appliance services
            </p>
          </div>
          <div className="flex items-center gap-2">
            <Button
              variant="outline"
              onClick={handleClear}
              className="flex items-center gap-2"
            >
              <Trash2 size={16} />
              <span>Clear</span>
            </Button>
          </div>
        </div>

        {/* Service Selector */}
        <div className="flex items-center gap-4 p-4 bg-card-dark border border-border-dark rounded-lg">
          <span className="text-text-secondary text-sm font-medium">Service:</span>
          <div className="flex gap-2 flex-wrap">
            {['system', 'scst', 'storage', 'backup', 'tape'].map((service) => (
              <button
                key={service}
                onClick={() => setSelectedService(service)}
                className={`px-3 py-1.5 rounded-lg text-xs font-medium transition-colors ${
                  selectedService === service
                    ? 'bg-primary text-white'
                    : 'bg-[#0f161d] text-text-secondary hover:text-white hover:bg-white/5'
                }`}
              >
                {service.charAt(0).toUpperCase() + service.slice(1)}
              </button>
            ))}
          </div>
        </div>

        {/* Terminal */}
        <div className="flex-1 flex flex-col bg-[#0a0f14] border border-border-dark rounded-lg overflow-hidden min-h-[600px]">
          {/* Terminal Output */}
          <div
            ref={terminalRef}
            className="flex-1 overflow-y-auto p-4 custom-scrollbar"
            style={{ minHeight: '400px' }}
          >
            {commandHistory.length === 0 ? (
              <div className="text-text-secondary">
                <div className="mb-4 flex items-center gap-2">
                  <Terminal className="text-primary" size={20} />
                  <span className="text-white font-semibold">Terminal Console</span>
                  <span className="text-xs px-2 py-0.5 bg-primary/20 text-primary rounded">
                    {selectedService}
                  </span>
                </div>
                <div className="mb-2">Type commands below to execute shell commands</div>
                <div className="text-xs opacity-70 mt-4">
                  <div className="font-semibold mb-2">Common commands for {selectedService}:</div>
                  <div className="ml-4 space-y-1">
                    {getServiceCommands(selectedService).map((cmd, idx) => (
                      <div key={idx}>
                        • <span className="text-primary font-mono">{cmd}</span>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            ) : (
              commandHistory.map((item, idx) => (
                <div key={idx} className="mb-6">
                  <div className="text-primary mb-2 font-mono text-sm flex items-center gap-2">
                    <span className="text-text-secondary">$</span>
                    <span className="text-white">{item.command}</span>
                    {item.service && (
                      <span className="text-xs px-1.5 py-0.5 bg-primary/20 text-primary rounded">
                        {item.service}
                      </span>
                    )}
                    <span className="text-text-secondary text-xs ml-auto">
                      {new Date(item.timestamp).toLocaleTimeString()}
                    </span>
                  </div>
                  <div
                    className={`font-mono text-xs leading-relaxed whitespace-pre overflow-x-auto ${
                      item.error ? 'text-red-400' : 'text-green-400'
                    }`}
                    style={{
                      fontFamily: 'ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',
                      lineHeight: '1.6',
                      tabSize: 2,
                    }}
                  >
                    {item.output}
                  </div>
                </div>
              ))
            )}
            {isExecuting && (
              <div className="text-text-secondary flex items-center gap-2">
                <RefreshCw size={16} className="animate-spin" />
                <span>Executing command...</span>
              </div>
            )}
          </div>

          {/* Terminal Input */}
          <div className="flex-none border-t border-border-dark bg-[#161f29]">
            <form onSubmit={handleSubmit} className="flex items-center">
              <div className="px-4 flex items-center gap-2">
                <span className="text-primary font-mono text-sm">$</span>
                <span className="text-xs text-text-secondary px-1.5 py-0.5 bg-primary/20 text-primary rounded">
                  {selectedService}
                </span>
              </div>
              <input
                ref={inputRef}
                type="text"
                value={currentCommand}
                onChange={(e) => setCurrentCommand(e.target.value)}
                onKeyDown={handleKeyDown}
                disabled={isExecuting}
                placeholder={`Enter ${selectedService} command...`}
                className="flex-1 bg-transparent text-white font-mono text-sm py-3 focus:outline-none disabled:opacity-50"
              />
              <button
                type="submit"
                disabled={!currentCommand.trim() || isExecuting}
                className="px-4 py-3 text-primary hover:text-white disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                <Command size={16} className={isExecuting ? 'animate-spin' : ''} />
              </button>
            </form>
          </div>
        </div>

        {/* Footer */}
        <div className="flex-none px-6 py-3 border-t border-border-dark bg-[#141d26] flex items-center justify-between text-xs text-text-secondary">
          <div className="flex items-center gap-4">
            <span>Terminal Console - Command Execution</span>
            <span>• {commandHistory.length} commands executed</span>
          </div>
          <div>
            Press <kbd className="px-1.5 py-0.5 bg-[#0a0f14] border border-border-dark rounded text-xs">Ctrl+L</kbd> to clear
          </div>
        </div>
      </div>
    </div>
  )
}
