import React, { useState, useMemo } from 'react';
import { MoreVertical, Square, RotateCcw, Settings, Info, Wifi, Terminal, Monitor } from 'lucide-react';
import { Machine } from '../types';
import { ProtocolHelper, ProtocolOption, OSInfo } from '../utils/protocolHelper';

interface QuickActionsMenuProps {
  machine: Machine;
  isConnected?: boolean;
  onConnect: (protocol: ProtocolOption) => void;
  onDisconnect?: () => void;
  onRestart?: () => void;
  onPowerOff?: () => void;
  onSettings?: () => void;
  onInfo?: () => void;
  className?: string;
}

const QuickActionsMenu: React.FC<QuickActionsMenuProps> = ({
  machine,
  isConnected = false,
  onConnect,
  onDisconnect,
  onRestart,
  onPowerOff,
  onSettings,
  onInfo,
  className = ''
}) => {
  const [isOpen, setIsOpen] = useState(false);

  const osInfo: OSInfo = useMemo(() => {
    return ProtocolHelper.parseOS(machine.os);
  }, [machine.os]);

  const availableProtocols = useMemo(() => {
    return ProtocolHelper.getRecommendedProtocols(osInfo);
  }, [osInfo]);

  const isRunning = machine.status === 'running';

  const handleActionClick = (action: () => void) => {
    action();
    setIsOpen(false);
  };

  const handleProtocolConnect = (protocol: ProtocolOption) => {
    onConnect(protocol);
    setIsOpen(false);
  };

  // Close menu on outside click
  React.useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as Element;
      if (!target.closest('.quick-actions-menu')) {
        setIsOpen(false);
      }
    };

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

  return (
    <div className={`relative quick-actions-menu ${className}`}>
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="p-2 text-gray-500 hover:text-gray-700 hover:bg-gray-100 rounded-md transition-colors"
        title="Quick Actions"
      >
        <MoreVertical size={16} />
      </button>

      {isOpen && (
        <div className="absolute right-0 top-full mt-1 w-48 bg-white border border-gray-200 rounded-lg shadow-lg z-50 overflow-hidden">
          {/* Connection Actions */}
          {!isConnected && isRunning && (
            <div className="border-b border-gray-100">
              <div className="px-3 py-2 text-xs font-medium text-gray-500 uppercase tracking-wide">
                Connect via
              </div>
              {availableProtocols.map((protocol) => (
                <button
                  key={protocol.value}
                  onClick={() => handleProtocolConnect(protocol)}
                  className="w-full px-3 py-2 text-left text-sm hover:bg-gray-50 flex items-center gap-3"
                >
                  <span className="text-lg">{protocol.icon}</span>
                  <div className="font-medium text-gray-900">{protocol.label}</div>
                </button>
              ))}
            </div>
          )}

          {/* Disconnect Action */}
          {isConnected && onDisconnect && (
            <div className="border-b border-gray-100">
              <button
                onClick={() => handleActionClick(onDisconnect)}
                className="w-full px-3 py-2 text-left text-sm hover:bg-gray-50 flex items-center gap-3 text-red-600"
              >
                <Wifi size={16} />
                <span>Disconnect</span>
              </button>
            </div>
          )}

          {/* Quick Actions */}
          <div className="border-b border-gray-100">
            <div className="px-3 py-2 text-xs font-medium text-gray-500 uppercase tracking-wide">
              Quick Actions
            </div>
            
            {/* Remote Desktop shortcut */}
            {osInfo.family === 'windows' && (
              <button
                onClick={() => handleProtocolConnect(availableProtocols.find(p => p.value === 'rdp')!)}
                className="w-full px-3 py-2 text-left text-sm hover:bg-gray-50 flex items-center gap-3"
                disabled={!isRunning}
              >
                <Monitor size={16} className={isRunning ? 'text-blue-600' : 'text-gray-400'} />
                <span className={isRunning ? 'text-gray-900' : 'text-gray-400'}>
                  Remote Desktop
                </span>
              </button>
            )}

            {/* SSH Terminal shortcut */}
            {['linux', 'macos', 'unix'].includes(osInfo.family) && (
              <button
                onClick={() => handleProtocolConnect(availableProtocols.find(p => p.value === 'ssh')!)}
                className="w-full px-3 py-2 text-left text-sm hover:bg-gray-50 flex items-center gap-3"
                disabled={!isRunning}
              >
                <Terminal size={16} className={isRunning ? 'text-green-600' : 'text-gray-400'} />
                <span className={isRunning ? 'text-gray-900' : 'text-gray-400'}>
                  SSH Terminal
                </span>
              </button>
            )}
          </div>

          {/* Power Management */}
          <div className="border-b border-gray-100">
            <div className="px-3 py-2 text-xs font-medium text-gray-500 uppercase tracking-wide">
              Power Management
            </div>
            
            {onRestart && (
              <button
                onClick={() => handleActionClick(onRestart)}
                className="w-full px-3 py-2 text-left text-sm hover:bg-gray-50 flex items-center gap-3"
                disabled={!isRunning}
              >
                <RotateCcw size={16} className={isRunning ? 'text-orange-600' : 'text-gray-400'} />
                <span className={isRunning ? 'text-gray-900' : 'text-gray-400'}>
                  Restart
                </span>
              </button>
            )}

            {onPowerOff && (
              <button
                onClick={() => handleActionClick(onPowerOff)}
                className="w-full px-3 py-2 text-left text-sm hover:bg-gray-50 flex items-center gap-3"
                disabled={!isRunning}
              >
                <Square size={16} className={isRunning ? 'text-red-600' : 'text-gray-400'} />
                <span className={isRunning ? 'text-gray-900' : 'text-gray-400'}>
                  Power Off
                </span>
              </button>
            )}
          </div>

          {/* Settings and Info */}
          <div>
            {onSettings && (
              <button
                onClick={() => handleActionClick(onSettings)}
                className="w-full px-3 py-2 text-left text-sm hover:bg-gray-50 flex items-center gap-3"
              >
                <Settings size={16} className="text-gray-600" />
                <span>Settings</span>
              </button>
            )}

            {onInfo && (
              <button
                onClick={() => handleActionClick(onInfo)}
                className="w-full px-3 py-2 text-left text-sm hover:bg-gray-50 flex items-center gap-3"
              >
                <Info size={16} className="text-blue-600" />
                <span>Machine Info</span>
              </button>
            )}
          </div>

          {/* Machine status footer */}
          <div className="bg-gray-50 px-3 py-2 text-xs text-gray-500">
            Status: <span className={`font-medium ${
              machine.status === 'running' ? 'text-green-600' : 
              machine.status === 'stopped' ? 'text-red-600' : 'text-yellow-600'
            }`}>
              {machine.status}
            </span>
          </div>
        </div>
      )}
    </div>
  );
};

export default QuickActionsMenu; 