import React, { useEffect, useRef } from 'react';
import { Terminal } from 'xterm';
import { FitAddon } from 'xterm-addon-fit';
import { io } from 'socket.io-client';
import 'xterm/css/xterm.css';

const TerminalComponent = ({ containerId }) => {
    const terminalRef = useRef(null);
    const socketRef = useRef(null);
    const termRef = useRef(null);

    useEffect(() => {
        // Initialize Socket
        // Use relative path if proxied, or absolute for dev
        // Since we are proxying /api, we might need to be careful with socket.io path
        // Default socket.io path is /socket.io
        // If nginx proxies /socket.io -> backend:8001/socket.io, it should work.
        socketRef.current = io({
            path: '/socket.io',
        });

        // Initialize xterm
        const term = new Terminal({
            cursorBlink: true,
            theme: {
                background: '#1e1e1e',
                foreground: '#f0f0f0',
            },
            fontFamily: 'Menlo, Monaco, "Courier New", monospace',
            fontSize: 14,
        });

        const fitAddon = new FitAddon();
        term.loadAddon(fitAddon);

        if (terminalRef.current) {
            term.open(terminalRef.current);
            fitAddon.fit();
            termRef.current = term;
        }

        // Attach to container
        socketRef.current.emit('attach-terminal', containerId);

        // Handle Socket Events
        socketRef.current.on('terminal-output', (data) => {
            term.write(data);
        });

        // Handle Terminal Input
        term.onData((data) => {
            socketRef.current.emit('terminal-input', data);
        });

        // Handle Resize
        const handleResize = () => {
            fitAddon.fit();
            if (terminalRef.current) {
                const { cols, rows } = term;
                socketRef.current.emit('resize-terminal', { cols, rows });
            }
        };

        window.addEventListener('resize', handleResize);

        // Initial resize
        setTimeout(() => handleResize(), 100);

        return () => {
            window.removeEventListener('resize', handleResize);
            if (socketRef.current) socketRef.current.disconnect();
            if (termRef.current) termRef.current.dispose();
        };
    }, [containerId]);

    return (
        <div
            ref={terminalRef}
            style={{
                width: '100%',
                height: '100%',
                backgroundColor: '#1e1e1e',
                borderRadius: '8px',
                overflow: 'hidden',
                padding: '0.5rem'
            }}
        />
    );
};

export default TerminalComponent;
