import React, { useState, useMemo, useEffect } from 'react';
import { X, Info, AlertTriangle, CheckCircle, LogIn } from 'lucide-react';
import { Machine } from '../types';
import { ProtocolHelper, ProtocolOption, OSInfo } from '../utils/protocolHelper';
import { InputSanitizer } from '../utils/sanitizer';
import { Button } from './shared/Button';

interface MachineCredentialsModalProps {
  isOpen: boolean;
  machine: Machine | null;
  onClose: () => void;
  onSubmit: (
    username: string, 
    password: string, 
    protocol: string, 
    sftpOptions?: { 
      enableSftp: boolean; 
      sftpRootDirectory: string;
    }
  ) => Promise<void>;
}

const MachineCredentialsModal: React.FC<MachineCredentialsModalProps> = ({ 
  isOpen, 
  machine, 
  onClose, 
  onSubmit 
}) => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [protocol, setProtocol] = useState('');
  const [port, setPort] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  
  // SFTP parameters for SSH
  const [enableSftp, setEnableSftp] = useState(true);
  const [sftpRootDirectory, setSftpRootDirectory] = useState('/');

  // Parse machine OS and get recommended protocols
  const osInfo: OSInfo = useMemo(() => {
    return machine ? ProtocolHelper.parseOS(machine.os) : { family: 'unknown' };
  }, [machine?.os]);

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

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

  const selectedProtocolInfo = useMemo(() => {
    return availableProtocols.find(p => p.value === protocol);
  }, [protocol, availableProtocols]);

  // Set default protocol and port when machine changes
  useEffect(() => {
    if (machine && availableProtocols.length > 0) {
      const defaultProtocol = ProtocolHelper.getDefaultProtocol(osInfo);
      setProtocol(defaultProtocol.value);
      setPort(defaultProtocol.defaultPort.toString());
    }
  }, [machine, osInfo, availableProtocols]);

  // Update port when protocol changes
  useEffect(() => {
    if (selectedProtocolInfo) {
      setPort(selectedProtocolInfo.defaultPort.toString());
    }
  }, [selectedProtocolInfo]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setIsLoading(true);
    setError(null);

    try {
      // Санитизируем данные перед отправкой
      const sanitizedUsername = InputSanitizer.sanitizeUsername(username);
      InputSanitizer.validatePassword(password);
      const sanitizedProtocol = InputSanitizer.sanitizeProtocol(protocol);
      const portNumber = InputSanitizer.validatePort(port);

      // Валидируем порт для выбранного протокола
      const portValidation = ProtocolHelper.validatePort(protocol, portNumber);
      if (!portValidation.valid) {
        throw new Error('Invalid port for selected protocol');
      }

      // Передаем SFTP параметры, если протокол SSH
      const sftpOptions = protocol === 'ssh' ? {
        enableSftp,
        sftpRootDirectory: sftpRootDirectory.trim() || '/'
      } : undefined;
      
      await onSubmit(sanitizedUsername, password, sanitizedProtocol, sftpOptions);
      
      // Clear form after successful connection
      setUsername('');
      setPassword('');
      onClose();
    } catch (err) {
      setError(err instanceof Error ? err.message : 'Connection failed');
    } finally {
      setIsLoading(false);
    }
  };

  if (!isOpen || !machine) return null;

  return (
    <div className="fixed inset-0 bg-black bg-opacity-60 flex items-center justify-center z-50 backdrop-blur-sm">
      <div className="bg-kaspersky-bg-card rounded-lg p-6 w-full max-w-md shadow-2xl border border-kaspersky-border select-none">
        <div className="flex justify-between items-center mb-4">
          <h2 className="text-2xl font-bold text-kaspersky-text-dark">
            Connect to {machine.name}
          </h2>
          <button
            onClick={onClose}
            className="text-kaspersky-text-light hover:text-kaspersky-danger transition-colors p-1 rounded-lg hover:bg-kaspersky-bg"
            disabled={isLoading}
          >
            <X size={24} />
          </button>
        </div>

        <div className="mb-4 p-4 bg-kaspersky-bg rounded-lg border border-kaspersky-border">
          <div className="flex items-center gap-3 mb-2">
            <span className="text-2xl">{osInfo.family === 'windows' ? '🖥️' : osInfo.family === 'linux' ? '🐧' : osInfo.family === 'macos' ? '🍎' : '💻'}</span>
            <div>
              <p className="text-sm font-semibold text-kaspersky-text-dark">{machine.name}</p>
              <p className="text-xs text-kaspersky-text-light">{machine.ip} • {machine.os}</p>
            </div>
          </div>
          
          {/* Compatibility info */}
          {compatibilityInfo.recommendations.length > 0 && (
            <div className="mt-3 p-3 bg-kaspersky-primary bg-opacity-10 border border-kaspersky-primary border-opacity-30 rounded-lg text-xs">
              <div className="flex items-center gap-1.5 mb-1">
                <CheckCircle size={14} className="text-kaspersky-primary" />
                <span className="font-semibold text-kaspersky-primary">Recommendation</span>
              </div>
              <p className="text-kaspersky-text-dark">{compatibilityInfo.recommendations[0]}</p>
            </div>
          )}
          
          {compatibilityInfo.warnings.length > 0 && (
            <div className="mt-2 p-3 bg-kaspersky-warning bg-opacity-10 border border-kaspersky-warning border-opacity-30 rounded-lg text-xs">
              <div className="flex items-center gap-1.5 mb-1">
                <AlertTriangle size={14} className="text-kaspersky-warning" />
                <span className="font-semibold text-kaspersky-warning">Warning</span>
              </div>
              <p className="text-kaspersky-text-dark">{compatibilityInfo.warnings[0]}</p>
            </div>
          )}
        </div>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label htmlFor="protocol" className="block text-sm font-semibold text-kaspersky-text-dark mb-2">
              Connection Protocol
            </label>
            <select
              id="protocol"
              value={protocol}
              onChange={(e) => setProtocol(e.target.value)}
              className="w-full px-4 py-2.5 bg-kaspersky-bg border-2 border-kaspersky-border rounded-lg text-kaspersky-text-dark focus:outline-none focus:border-kaspersky-primary focus:bg-white transition-all duration-200 select-text"
              disabled={isLoading}
            >
              {availableProtocols.map((protocolOption) => (
                <option key={protocolOption.value} value={protocolOption.value}>
                  {protocolOption.icon} {protocolOption.label}
                </option>
              ))}
            </select>
            
            {/* Protocol info */}
            {selectedProtocolInfo && (
              <div className="mt-2 p-3 bg-kaspersky-bg border border-kaspersky-border rounded-lg text-xs">
                <div className="flex items-center gap-1.5 mb-1">
                  <Info size={14} className="text-kaspersky-primary" />
                  <span className="font-semibold text-kaspersky-text-dark">Protocol Info</span>
                </div>
                <p className="text-kaspersky-text mb-1">{selectedProtocolInfo.description}</p>
                {selectedProtocolInfo.requirements && (
                  <div>
                    <span className="font-semibold text-kaspersky-text-dark">Requirements:</span>
                    <ul className="list-disc list-inside text-kaspersky-text mt-1">
                      {selectedProtocolInfo.requirements.map((req, index) => (
                        <li key={index}>{req}</li>
                      ))}
                    </ul>
                  </div>
                )}
              </div>
            )}
          </div>

          <div>
            <label htmlFor="port" className="block text-sm font-semibold text-kaspersky-text-dark mb-2">
              Port
            </label>
            <input
              type="number"
              id="port"
              value={port}
              onChange={(e) => setPort(e.target.value)}
              className="w-full px-4 py-2.5 bg-kaspersky-bg border-2 border-kaspersky-border rounded-lg text-kaspersky-text-dark focus:outline-none focus:border-kaspersky-primary focus:bg-white transition-all duration-200 select-text"
              required
              disabled={isLoading}
              min="1"
              max="65535"
              placeholder={selectedProtocolInfo?.defaultPort.toString()}
            />
            {selectedProtocolInfo && (
              <p className="text-xs text-kaspersky-text-light mt-1">
                Default port for {selectedProtocolInfo.label}: {selectedProtocolInfo.defaultPort}
              </p>
            )}
          </div>

          <div>
            <label htmlFor="machine-username" className="block text-sm font-semibold text-kaspersky-text-dark mb-2">
              Machine Username
            </label>
            <input
              type="text"
              id="machine-username"
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              className="w-full px-4 py-2.5 bg-kaspersky-bg border-2 border-kaspersky-border rounded-lg text-kaspersky-text-dark focus:outline-none focus:border-kaspersky-primary focus:bg-white transition-all duration-200 select-text"
              required
              disabled={isLoading}
              autoFocus
              placeholder="Administrator"
            />
          </div>

          <div>
            <label htmlFor="machine-password" className="block text-sm font-semibold text-kaspersky-text-dark mb-2">
              Machine Password
            </label>
            <input
              type="password"
              id="machine-password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="w-full px-4 py-2.5 bg-kaspersky-bg border-2 border-kaspersky-border rounded-lg text-kaspersky-text-dark focus:outline-none focus:border-kaspersky-primary focus:bg-white transition-all duration-200 select-text"
              required
              disabled={isLoading}
              placeholder="••••••••"
            />
          </div>

          {/* SFTP параметры - показываем только для SSH */}
          {protocol === 'ssh' && (
            <div className="space-y-3 p-4 bg-kaspersky-primary bg-opacity-10 border border-kaspersky-primary border-opacity-30 rounded-lg">
              <div className="flex items-center gap-2">
                <span className="text-sm font-semibold text-kaspersky-primary">📁 SFTP File Transfer</span>
              </div>
              
              <div className="flex items-center gap-3 p-3 bg-kaspersky-bg-card rounded-lg border border-kaspersky-border">
                <input
                  type="checkbox"
                  id="enable-sftp"
                  checked={enableSftp}
                  onChange={(e) => setEnableSftp(e.target.checked)}
                  className="w-5 h-5 text-kaspersky-primary bg-white border-2 border-kaspersky-border rounded focus:ring-2 focus:ring-kaspersky-primary cursor-pointer"
                  disabled={isLoading}
                />
                <label htmlFor="enable-sftp" className="text-sm font-medium text-kaspersky-text-dark cursor-pointer flex-1">
                  Enable file browser (download/upload with drag'n'drop)
                </label>
              </div>

              {enableSftp && (
                <div>
                  <label htmlFor="sftp-root-directory" className="block text-xs font-semibold text-kaspersky-text-dark mb-2">
                    Root Directory (optional)
                  </label>
                  <input
                    type="text"
                    id="sftp-root-directory"
                    value={sftpRootDirectory}
                    onChange={(e) => setSftpRootDirectory(e.target.value)}
                    className="w-full px-3 py-2 text-sm bg-kaspersky-bg border-2 border-kaspersky-border rounded-lg text-kaspersky-text-dark focus:outline-none focus:border-kaspersky-primary focus:bg-white transition-all duration-200 select-text"
                    disabled={isLoading}
                    placeholder="/"
                  />
                  <p className="text-xs text-kaspersky-text-light mt-1">
                    Restrict SFTP access to this directory (default: /)
                  </p>
                </div>
              )}
            </div>
          )}

          {error && (
            <div className="bg-kaspersky-danger bg-opacity-10 border border-kaspersky-danger text-kaspersky-danger px-4 py-3 rounded-lg text-sm font-medium animate-shake">
              {error}
            </div>
          )}

          <div className="flex gap-3 pt-2">
            <Button
              type="submit"
              variant="primary"
              fullWidth
              disabled={isLoading}
              isLoading={isLoading}
              leftIcon={!isLoading ? <LogIn size={18} /> : undefined}
            >
              {isLoading ? 'Connecting...' : 'Connect'}
            </Button>
            <Button
              type="button"
              variant="secondary"
              onClick={onClose}
              disabled={isLoading}
              leftIcon={<X size={18} />}
            >
              Cancel
            </Button>
          </div>
        </form>
      </div>
    </div>
  );
};

export default MachineCredentialsModal; 