import React, { useMemo } from 'react';
import { Play, AlertCircle } from 'lucide-react';
import { Machine } from '../types';
import { ProtocolHelper, ProtocolOption, OSInfo } from '../utils/protocolHelper';

interface SmartConnectionButtonProps {
  machine: Machine;
  onConnect: (machine: Machine, suggestedProtocol?: ProtocolOption) => void;
  isConnected?: boolean;
  userRole?: string;
  className?: string;
  size?: 'sm' | 'md' | 'lg';
}

const SmartConnectionButton: React.FC<SmartConnectionButtonProps> = ({
  machine,
  onConnect,
  isConnected = false,
  userRole,
  className = '',
  size = 'md'
}) => {
  const osInfo: OSInfo = useMemo(() => {
    return ProtocolHelper.parseOS(machine.os);
  }, [machine.os]);

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

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

  const hasWarnings = compatibilityInfo.warnings.length > 0;
  const isGuestRole = userRole === 'GUEST';
  const isDisabled = isGuestRole && !isConnected; // Disable only for GUEST when not connected

  const sizeClasses = {
    sm: 'px-3 py-1.5 text-xs',
    md: 'px-3 py-2 text-sm',
    lg: 'px-4 py-3 text-base'
  };

  const iconSizes = {
    sm: 12,
    md: 16,
    lg: 20
  };

  const handleClick = () => {
    if (!isDisabled) {
      onConnect(machine, recommendedProtocol);
    }
  };

  return (
    <div className="relative">
      <button
        onClick={handleClick}
        disabled={isDisabled}
        className={`
          flex items-center gap-2
          min-w-[125px] 
          ${isDisabled 
            ? 'bg-gray-400 cursor-not-allowed opacity-60' 
            : isConnected 
              ? 'bg-green-600 hover:bg-green-700' 
              : 'bg-kaspersky-base hover:bg-kaspersky-dark'
          }
          text-white rounded-md transition-all duration-200
          font-medium
          ${sizeClasses[size]}
          ${hasWarnings && !isDisabled ? 'ring-2 ring-yellow-400 ring-opacity-50' : ''}
          ${className}
        `}
        title={
          isDisabled 
            ? 'Access denied: GUEST role cannot create connections. Contact your administrator.' 
            : isConnected 
              ? `Active session via ${recommendedProtocol.label}` 
              : `Connect via ${recommendedProtocol.label} (${recommendedProtocol.description})`
        }
      >
        <span className="text-lg w-6 flex justify-center">{recommendedProtocol.icon}</span>
        <Play size={iconSizes[size]} className={isConnected ? 'text-green-200' : ''} />
        <span className="flex-1 text-left">{isConnected ? 'Active' : 'Connect'}</span>
        {hasWarnings && !isConnected && <AlertCircle size={iconSizes[size]} className="text-yellow-300" />}
      </button>


    </div>
  );
};

export default SmartConnectionButton; 