import { useEffect, useRef, useState } from 'react';
import { Machine } from '../types';
import { log } from '../utils/logger';

interface GuacamoleViewerProps {
  machine: Machine;
  connectionUrl: string;
  enableSftp?: boolean;
  onError?: (error: Error) => void;
  onDisconnect?: () => void;
}

/**
 * GuacamoleViewer component
 * 
 * KNOWN BEHAVIOR: You may see "DELETE /guacamole/api/session 403 Forbidden" in DevTools.
 * This is EXPECTED and NOT an error:
 * 
 * - Guacamole Client checks localStorage for old sessions when loading
 * - It tries to clean up expired sessions via DELETE /guacamole/api/session
 * - Old session tokens are invalid, resulting in 403 Forbidden
 * - This is "best effort cleanup" and doesn't affect functionality
 * - We manage all connections properly through our API endpoints
 * 
 * This can be safely ignored - it's standard Guacamole Client behavior.
 */
function GuacamoleViewer({ machine, connectionUrl, enableSftp, onError, onDisconnect }: GuacamoleViewerProps) {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<Error | null>(null);
  const [isConsoleActive, setIsConsoleActive] = useState(false);
  const iframeRef = useRef<HTMLIFrameElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);

  // Effect for loading iframe (only on first initialization)
  useEffect(() => {
    const connectToGuacamole = async () => {
      try {
        setLoading(true);
        setError(null);

        log.info('guacamole-viewer', 'Initializing Guacamole session', {
          machineId: machine.id,
          machineName: machine.name,
          connectionUrl: connectionUrl
        });

        if (iframeRef.current) {
          // Load URL only if iframe is empty
          if (!iframeRef.current.src || iframeRef.current.src === 'about:blank') {
            log.debug('guacamole-viewer', 'Loading connection URL', {
              url: connectionUrl
            });
            iframeRef.current.src = connectionUrl;
          } else {
            log.debug('guacamole-viewer', 'iframe already loaded, keeping existing session');
            setLoading(false);
            return;
          }
        }

        // Add handler to track iframe loading
        const handleLoad = () => {
          setLoading(false);
          log.info('guacamole-viewer', 'Guacamole session loaded', {
            machineId: machine.id,
          });
          
          // Automatically activate console after loading
          setTimeout(() => {
            if (iframeRef.current) {
              iframeRef.current.focus();
              setIsConsoleActive(true);
            }
          }, 500);
        };

        const handleError = () => {
          const error = new Error('Failed to load Guacamole session');
          setError(error);
          setLoading(false);
          onError?.(error);
        };

        if (iframeRef.current) {
          iframeRef.current.addEventListener('load', handleLoad);
          iframeRef.current.addEventListener('error', handleError);

          return () => {
            iframeRef.current?.removeEventListener('load', handleLoad);
            iframeRef.current?.removeEventListener('error', handleError);
          };
        }
      } catch (err) {
        const error = err instanceof Error ? err : new Error('Unknown error occurred');
        log.error('guacamole-viewer', 'Connection failed', {
          machineId: machine.id,
          error: error.message
        });
        setError(error);
        onError?.(error);
        setLoading(false);
      }
    };

    connectToGuacamole();

    return () => {
      log.info('guacamole-viewer', 'Cleaning up connection', {
        machineId: machine.id
      });
      setIsConsoleActive(false);
    };
  }, [machine.id]);

  // Deactivate console on outside click
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (containerRef.current && !containerRef.current.contains(event.target as Node) && isConsoleActive) {
        setIsConsoleActive(false);
        if (iframeRef.current) {
          iframeRef.current.blur();
        }
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [isConsoleActive]);


  if (error) {
    return (
      <div className="flex-1 flex items-center justify-center bg-red-50 text-red-600 p-4 rounded-kaspersky">
        <div className="text-center">
          <p className="font-medium mb-2">Connection Error</p>
          <p className="text-sm mb-4">{error.message}</p>
          <div className="flex gap-2 justify-center">
            <button
              onClick={() => window.location.reload()}
              className="px-4 py-2 bg-red-600 text-white rounded-kaspersky hover:bg-red-700 transition-colors"
            >
              Retry
            </button>
            <button
              onClick={onDisconnect}
              className="px-4 py-2 bg-gray-600 text-white rounded-kaspersky hover:bg-gray-700 transition-colors"
            >
              Disconnect
            </button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="w-full h-full flex flex-col bg-kaspersky-bg">
      {/* Область для Guacamole - занимает всё пространство */}
      <div 
        ref={containerRef}
        className={`flex-1 relative bg-kaspersky-bg overflow-hidden ${
          isConsoleActive ? 'ring-2 ring-kaspersky-primary ring-opacity-50' : ''
        }`}
      >
        {loading && (
          <div className="absolute inset-0 flex items-center justify-center bg-kaspersky-bg bg-opacity-75 z-10">
            <div className="text-center">
              <div className="w-8 h-8 border-4 border-kaspersky-base border-t-transparent rounded-full animate-spin mx-auto"></div>
              <p className="mt-2 text-kaspersky-text">Connecting to {machine.name}...</p>
            </div>
          </div>
        )}
        
        {/* Прозрачный overlay для активации консоли при клике */}
        {!loading && !isConsoleActive && (
          <div 
            className="absolute inset-0 z-10 cursor-pointer"
            onClick={() => {
              if (iframeRef.current) {
                iframeRef.current.focus();
                setIsConsoleActive(true);
              }
            }}
            title="Click to activate console"
          />
        )}
        
        {/* Индикатор фокуса консоли с подсказками */}
        {!loading && (
          <div className="absolute top-4 left-1/2 transform -translate-x-1/2 z-20 pointer-events-none select-none">
            <div className="flex flex-col items-center gap-2">
              {/* Индикатор статуса консоли */}
            <div 
              className={`flex items-center gap-3 px-4 py-2 rounded-lg text-sm font-semibold transition-all duration-300 ${
                isConsoleActive 
                  ? 'bg-kaspersky-primary text-white shadow-kaspersky-lg' 
                  : 'bg-kaspersky-secondary bg-opacity-90 text-kaspersky-text-white'
              }`}
            >
              <div className={`w-3 h-3 rounded-full transition-all duration-300 ${
                isConsoleActive ? 'bg-kaspersky-danger animate-pulse' : 'bg-kaspersky-text-lighter'
              }`}></div>
              <span>{isConsoleActive ? 'Console Active' : 'Console Inactive'}</span>
              </div>
              
              {/* Подсказка с клавиатурными сочетаниями */}
              <div className="bg-kaspersky-secondary bg-opacity-75 backdrop-blur-sm text-kaspersky-text-white px-3 py-1.5 rounded-md text-xs font-medium">
                {enableSftp ? (
                  // Tooltip for SSH with SFTP
                  <div className="flex items-center gap-2">
                    <span className="opacity-75">Settings & SFTP:</span>
                    <kbd className="px-1.5 py-0.5 bg-kaspersky-base bg-opacity-50 rounded text-[10px] font-mono">
                      Ctrl+Shift+Alt
                    </kbd>
                  </div>
                ) : (
                  // Tooltip for settings only
                  <div className="flex items-center gap-2">
                    <span className="opacity-75">Settings:</span>
                    <kbd className="px-1.5 py-0.5 bg-kaspersky-base bg-opacity-50 rounded text-[10px] font-mono">
                      Ctrl+Shift+Alt
                    </kbd>
                  </div>
                )}
              </div>
            </div>
          </div>
        )}
        <iframe
          ref={iframeRef}
          className="w-full h-full border-0"
          title={`Remote Desktop - ${machine.name}`}
          allow="clipboard-read; clipboard-write; keyboard-map *; pointer-lock"
          sandbox="allow-same-origin allow-scripts allow-forms allow-popups allow-pointer-lock allow-modals allow-downloads"
          onFocus={() => setIsConsoleActive(true)}
          onBlur={() => setIsConsoleActive(false)}
        />
      </div>
    </div>
  );
}

export default GuacamoleViewer; 