import React, { useEffect, useRef, useState, useCallback } from 'react';
import { Terminal } from '@xterm/xterm';
import { FitAddon } from '@xterm/addon-fit';
import { WebLinksAddon } from '@xterm/addon-web-links';
import { X, Minimize2, Maximize2 } from 'lucide-react';
import { Button } from './button';
import '@xterm/xterm/css/xterm.css';

interface TerminalComponentProps {
  isOpen: boolean;
  onClose: () => void;
  title?: string;
  command?: string;
}

export function TerminalComponent({
  isOpen,
  onClose,
  title = 'Terminal',
  command,
}: TerminalComponentProps) {
  const terminalRef = useRef<HTMLDivElement>(null);
  const terminal = useRef<Terminal | null>(null);
  const fitAddon = useRef<FitAddon | null>(null);
  const [isMinimized, setIsMinimized] = useState(false);
  const [sessionId, setSessionId] = useState<string | null>(null);

  const initializeTerminal = useCallback(() => {
    if (!terminalRef.current || terminal.current) return;

    // Inicializar terminal com configurações aprimoradas
    terminal.current = new Terminal({
      cursorBlink: true,
      theme: {
        background: '#1e1e1e',
        foreground: '#ffffff',
        cursor: '#ffffff',
        selection: '#3390ff40',
        black: '#000000',
        red: '#e06c75',
        green: '#98c379',
        yellow: '#d19a66',
        blue: '#61afef',
        magenta: '#c678dd',
        cyan: '#56b6c2',
        white: '#abb2bf',
        brightBlack: '#5c6370',
        brightRed: '#e06c75',
        brightGreen: '#98c379',
        brightYellow: '#d19a66',
        brightBlue: '#61afef',
        brightMagenta: '#c678dd',
        brightCyan: '#56b6c2',
        brightWhite: '#ffffff',
      },
      fontSize: 14,
      fontFamily:
        '"JetBrains Mono", "Fira Code", "Consolas", "Monaco", monospace',
      rows: 30,
      cols: 100,
      scrollback: 1000,
      allowTransparency: false,
      convertEol: true,
    });

    // Adicionar addons
    fitAddon.current = new FitAddon();
    terminal.current.loadAddon(fitAddon.current);
    terminal.current.loadAddon(new WebLinksAddon());

    // Abrir terminal
    terminal.current.open(terminalRef.current);

    // Fit e focus
    setTimeout(() => {
      fitAddon.current?.fit();
      terminal.current?.focus();
    }, 100);

    // Iniciar sessão
    if (command) {
      startTerminalSession(command);
    }
  }, [command]);

  useEffect(() => {
    if (isOpen && terminalRef.current && !terminal.current) {
      initializeTerminal();

      // Redimensionar quando a janela muda
      const handleResize = () => {
        if (fitAddon.current && !isMinimized) {
          setTimeout(() => fitAddon.current?.fit(), 100);
        }
      };

      window.addEventListener('resize', handleResize);
      return () => window.removeEventListener('resize', handleResize);
    }
  }, [isOpen, initializeTerminal]);

  const startTerminalSession = async (cmd: string) => {
    try {
      console.log('Starting terminal session with command:', cmd);

      const response =
        await window.electron?.ipcRenderer.startTerminalSession(cmd);
      console.log('Terminal session response:', response);

      if (response.success) {
        setSessionId(response.sessionId);
        console.log('Terminal session started with ID:', response.sessionId);

        // Setup input handler for this session
        terminal.current?.onData((data) => {
          console.log('Sending data to terminal:', data);
          window.electron?.ipcRenderer.sendTerminalData(
            response.sessionId,
            data,
          );
        });

        // Escutar dados da sessão
        const unsubscribeData = window.electron?.ipcRenderer.onTerminalData(
          response.sessionId,
          (data: string) => {
            console.log('Terminal data received:', JSON.stringify(data));
            if (terminal.current) {
              terminal.current.write(data);
            } else {
              console.log('Terminal not ready, data lost:', data);
            }
          },
        );

        // Escutar quando a sessão termina
        const unsubscribeExit = window.electron?.ipcRenderer.onTerminalExit(
          response.sessionId,
          (code: number) => {
            console.log('Terminal session exited with code:', code);
            terminal.current?.write(
              `\r\n\r\nShell terminou (código: ${code})\r\n`,
            );
            terminal.current?.write(
              'Terminal fechado - clique no X para sair\r\n',
            );
            // Remove auto-close on any key - let user close manually
          },
        );

        // Cleanup function
        return () => {
          unsubscribeData?.();
          unsubscribeExit?.();
        };
      }
      console.error('Failed to start terminal session:', response.error);
      terminal.current?.write(
        `Erro ao iniciar terminal: ${response.error}\r\n`,
      );
    } catch (error) {
      console.error('Terminal session error:', error);
      terminal.current?.write(`Erro: ${error}\r\n`);
    }
  };

  const handleClose = () => {
    if (sessionId) {
      window.electron?.ipcRenderer.killTerminalSession(sessionId);
    }
    if (terminal.current) {
      terminal.current.dispose();
      terminal.current = null;
    }
    setSessionId(null);
    onClose();
  };

  const toggleMinimize = () => {
    setIsMinimized(!isMinimized);
    setTimeout(() => {
      if (fitAddon.current && !isMinimized) {
        fitAddon.current.fit();
      }
    }, 300);
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 z-50 bg-black/50 backdrop-blur-sm">
      <div
        className={`fixed bottom-4 left-4 right-4 bg-gray-900 border border-gray-700 rounded-lg shadow-2xl transition-all duration-300 ${
          isMinimized ? 'h-12' : 'h-96'
        }`}
        style={{ maxHeight: '80vh' }}
      >
        {/* Header */}
        <div className="flex items-center justify-between px-4 py-2 bg-gray-800 border-b border-gray-700 rounded-t-lg">
          <div className="flex items-center space-x-2">
            <div className="w-3 h-3 bg-red-500 rounded-full" />
            <div className="w-3 h-3 bg-yellow-500 rounded-full" />
            <div className="w-3 h-3 bg-green-500 rounded-full" />
            <span className="ml-2 text-sm text-gray-300 font-medium">
              {title}
            </span>
          </div>
          <div className="flex items-center space-x-1">
            <Button
              variant="ghost"
              size="icon"
              className="h-6 w-6 text-gray-400 hover:text-white hover:bg-gray-700"
              onClick={toggleMinimize}
            >
              {isMinimized ? (
                <Maximize2 className="h-3 w-3" />
              ) : (
                <Minimize2 className="h-3 w-3" />
              )}
            </Button>
            <Button
              variant="ghost"
              size="icon"
              className="h-6 w-6 text-gray-400 hover:text-white hover:bg-gray-700"
              onClick={handleClose}
            >
              <X className="h-3 w-3" />
            </Button>
          </div>
        </div>

        {/* Terminal */}
        {!isMinimized && (
          <div
            ref={terminalRef}
            className="w-full h-full p-2"
            style={{ height: 'calc(100% - 48px)' }}
          />
        )}
      </div>
    </div>
  );
}
