/**
 * BulkSSHCommandModal Component
 *
 * Modal for executing SSH command on multiple machines.
 *
 * 2 credential modes:
 * 1. 'global' - Single credentials for all machines (enter manually)
 * 2. 'custom' - Individual credentials for each machine
 *
 * Passwords are NOT saved and transmitted via HTTPS
 */

import { useState, useEffect } from 'react';
import { Terminal, X, Users, User } from 'lucide-react';
import { Button } from './shared/Button';
import { Machine } from '../types';

type CredentialsMode = 'global' | 'custom';

interface GlobalCredentials {
  username: string;
  password: string;
}

interface CustomCredentials {
  [machineId: string]: {
    username: string;
    password: string;
  };
}

interface BulkSSHCommandModalProps {
  isOpen: boolean;
  selectedMachines: Machine[];
  onClose: () => void;
  onExecute: (command: string, mode: CredentialsMode, globalCreds?: GlobalCredentials, customCreds?: CustomCredentials) => void;
  userRole?: string;
}

export function BulkSSHCommandModal({
  isOpen,
  selectedMachines,
  onClose,
  onExecute,
  userRole
}: BulkSSHCommandModalProps) {
  
  const [command, setCommand] = useState('');
  const [credentialsMode, setCredentialsMode] = useState<CredentialsMode>('global');
  const [globalCredentials, setGlobalCredentials] = useState<GlobalCredentials>({
    username: '',
    password: ''
  });
  const [customCredentials, setCustomCredentials] = useState<CustomCredentials>({});

  // Command whitelist for USER role
  const isUserRole = userRole === 'USER';
  const allowedCommands = [
    'uptime',
    'df -h',
    'free -m',
    'top -bn1',
    'systemctl status',
    'docker ps',
    'ps aux',
    'ls -la',
    'cat /etc/os-release',
    'hostname'
  ];

  // Check if command is allowed
  const isCommandAllowed = !isUserRole || allowedCommands.some(cmd => 
    command.trim().startsWith(cmd)
  );

  // Initialize custom credentials for machines
  useEffect(() => {
    if (credentialsMode === 'custom') {
      const initialCreds: CustomCredentials = {};
      selectedMachines.forEach(machine => {
        if (!customCredentials[machine.id]) {
          initialCreds[machine.id] = { username: '', password: '' };
        }
      });
      setCustomCredentials(prev => ({ ...prev, ...initialCreds }));
    }
  }, [credentialsMode, selectedMachines]);

  // Handle execute
  const handleExecute = () => {
    if (!command.trim()) {
      return;
    }

    if (!isCommandAllowed) {
      return;
    }

    if (credentialsMode === 'global') {
      if (!globalCredentials.username || !globalCredentials.password) {
        return;
      }
      onExecute(command, 'global', globalCredentials);
    } else {
      // custom mode
      // Validate all machines have credentials
      const allHaveCreds = selectedMachines.every(m => 
        customCredentials[m.id]?.username && customCredentials[m.id]?.password
      );
      if (!allHaveCreds) {
        return;
      }
      onExecute(command, 'custom', undefined, customCredentials);
    }
  };

  // Handle custom credential change
  const handleCustomCredChange = (machineId: string, field: 'username' | 'password', value: string) => {
    setCustomCredentials(prev => ({
      ...prev,
      [machineId]: {
        ...prev[machineId],
        [field]: value
      }
    }));
  };

  // Copy global credentials to all machines
  const copyToAllMachines = () => {
    if (!globalCredentials.username || !globalCredentials.password) {
      return;
    }
    
    const newCreds: CustomCredentials = {};
    selectedMachines.forEach(machine => {
      newCreds[machine.id] = {
        username: globalCredentials.username,
        password: globalCredentials.password
      };
    });
    setCustomCredentials(newCreds);
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-[100]">
      <div className="bg-kaspersky-bg-card rounded-lg shadow-2xl border border-kaspersky-border max-w-3xl w-full mx-4 max-h-[90vh] flex flex-col select-none">
        
        {/* Header */}
        <div className="p-6 border-b border-kaspersky-border">
          <div className="flex items-center justify-between">
            <div className="flex items-center gap-3">
              <div className="w-12 h-12 bg-kaspersky-primary bg-opacity-10 rounded-full flex items-center justify-center">
                <Terminal className="w-6 h-6 text-kaspersky-primary" />
              </div>
              <div>
                <h2 className="text-xl font-bold text-kaspersky-text-dark">Execute SSH Command</h2>
                <p className="text-sm text-kaspersky-text-light">
                  Run command on {selectedMachines.length} machine{selectedMachines.length !== 1 ? 's' : ''}
                </p>
              </div>
            </div>
            <button
              onClick={onClose}
              className="text-kaspersky-text-light hover:text-kaspersky-text-dark transition-colors"
            >
              <X size={24} />
            </button>
          </div>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-6 space-y-6">
          
          {/* Command Input */}
          <div>
            <label className="block text-sm font-semibold text-kaspersky-text-dark mb-2">
              Command *
            </label>
            <input
              type="text"
              value={command}
              onChange={e => setCommand(e.target.value)}
              placeholder={isUserRole ? "e.g. uptime, df -h, free -m" : "e.g. systemctl restart nginx"}
              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 font-mono select-text"
            />
            
            {/* Command validation message */}
            {isUserRole && !isCommandAllowed && command.trim() && (
              <p className="mt-2 text-sm text-kaspersky-danger">
                ⚠️ This command is not in the whitelist. Allowed: {allowedCommands.join(', ')}
              </p>
            )}
            
            {isUserRole && (
              <p className="mt-2 text-sm text-kaspersky-text-light">
                ℹ️ USER role: Only whitelist commands allowed
              </p>
            )}
          </div>

          {/* Credentials Mode Selector */}
          <div>
            <label className="block text-sm font-semibold text-kaspersky-text-dark mb-3">
              Credentials Mode *
            </label>
            
            <div className="grid grid-cols-2 gap-3">
              {/* Mode 1: Global */}
              <button
                onClick={() => setCredentialsMode('global')}
                className={`p-4 rounded-lg border-2 transition-all ${
                  credentialsMode === 'global'
                    ? 'border-kaspersky-primary bg-kaspersky-primary bg-opacity-10'
                    : 'border-kaspersky-border bg-kaspersky-bg hover:border-kaspersky-primary hover:border-opacity-50'
                }`}
              >
                <div className="flex flex-col items-center gap-2">
                  <Users size={24} className={credentialsMode === 'global' ? 'text-kaspersky-primary' : 'text-kaspersky-text-light'} />
                  <span className="text-sm font-medium text-kaspersky-text-dark">Global</span>
                  <span className="text-xs text-kaspersky-text-light text-center">
                    Same for all machines
                  </span>
                </div>
              </button>

              {/* Mode 2: Custom */}
              <button
                onClick={() => setCredentialsMode('custom')}
                className={`p-4 rounded-lg border-2 transition-all ${
                  credentialsMode === 'custom'
                    ? 'border-kaspersky-primary bg-kaspersky-primary bg-opacity-10'
                    : 'border-kaspersky-border bg-kaspersky-bg hover:border-kaspersky-primary hover:border-opacity-50'
                }`}
              >
                <div className="flex flex-col items-center gap-2">
                  <User size={24} className={credentialsMode === 'custom' ? 'text-kaspersky-primary' : 'text-kaspersky-text-light'} />
                  <span className="text-sm font-medium text-kaspersky-text-dark">Custom</span>
                  <span className="text-xs text-kaspersky-text-light text-center">
                    Per-machine credentials
                  </span>
                </div>
              </button>
            </div>
          </div>

          {/* Global Credentials Input */}
          {credentialsMode === 'global' && (
            <div className="bg-kaspersky-bg border border-kaspersky-border rounded-lg p-4 space-y-3">
              <h4 className="font-semibold text-kaspersky-text-dark">Global Credentials</h4>
              <p className="text-sm text-kaspersky-text-light">
                These credentials will be used for all {selectedMachines.length} machines
              </p>
              
              <div className="space-y-3">
                <div>
                  <label className="block text-sm font-medium text-kaspersky-text-dark mb-1">Username</label>
                  <input
                    type="text"
                    value={globalCredentials.username}
                    onChange={e => setGlobalCredentials(prev => ({ ...prev, username: e.target.value }))}
                    placeholder="root"
                    className="w-full px-3 py-2 bg-white border border-kaspersky-border rounded-lg text-kaspersky-text-dark focus:outline-none focus:border-kaspersky-primary select-text"
                  />
                </div>
                
                <div>
                  <label className="block text-sm font-medium text-kaspersky-text-dark mb-1">Password</label>
                  <input
                    type="password"
                    value={globalCredentials.password}
                    onChange={e => setGlobalCredentials(prev => ({ ...prev, password: e.target.value }))}
                    placeholder="••••••••"
                    className="w-full px-3 py-2 bg-white border border-kaspersky-border rounded-lg text-kaspersky-text-dark focus:outline-none focus:border-kaspersky-primary select-text"
                  />
                </div>
              </div>
            </div>
          )}

          {/* Custom Credentials Input */}
          {credentialsMode === 'custom' && (
            <div className="bg-kaspersky-bg border border-kaspersky-border rounded-lg p-4 space-y-3">
              <div className="flex items-center justify-between">
                <h4 className="font-semibold text-kaspersky-text-dark">Custom Credentials Per Machine</h4>
                <Button
                  onClick={copyToAllMachines}
                  variant="secondary"
                  size="sm"
                  disabled={!globalCredentials.username || !globalCredentials.password}
                >
                  Copy from Global
                </Button>
              </div>
              
              {/* Quick global fill (helper) */}
              <div className="bg-yellow-50 border border-yellow-200 rounded p-3 space-y-2">
                <p className="text-xs text-yellow-800 font-medium">Quick Fill (optional)</p>
                <div className="grid grid-cols-2 gap-2">
                  <input
                    type="text"
                    value={globalCredentials.username}
                    onChange={e => setGlobalCredentials(prev => ({ ...prev, username: e.target.value }))}
                    placeholder="Username"
                    className="px-2 py-1 text-sm bg-white border border-yellow-300 rounded select-text"
                  />
                  <input
                    type="password"
                    value={globalCredentials.password}
                    onChange={e => setGlobalCredentials(prev => ({ ...prev, password: e.target.value }))}
                    placeholder="Password"
                    className="px-2 py-1 text-sm bg-white border border-yellow-300 rounded select-text"
                  />
                </div>
              </div>
              
              {/* Machine credentials list */}
              <div className="max-h-60 overflow-y-auto space-y-3">
                {selectedMachines.map(machine => (
                  <div key={machine.id} className="bg-white border border-kaspersky-border rounded p-3 space-y-2">
                    <div className="font-medium text-sm text-kaspersky-text-dark">{machine.name}</div>
                    <div className="grid grid-cols-2 gap-2">
                      <input
                        type="text"
                        value={customCredentials[machine.id]?.username || ''}
                        onChange={e => handleCustomCredChange(machine.id, 'username', e.target.value)}
                        placeholder="Username"
                        className="px-2 py-1 text-sm bg-kaspersky-bg border border-kaspersky-border rounded focus:outline-none focus:border-kaspersky-primary select-text"
                      />
                      <input
                        type="password"
                        value={customCredentials[machine.id]?.password || ''}
                        onChange={e => handleCustomCredChange(machine.id, 'password', e.target.value)}
                        placeholder="Password"
                        className="px-2 py-1 text-sm bg-kaspersky-bg border border-kaspersky-border rounded focus:outline-none focus:border-kaspersky-primary select-text"
                      />
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>

        {/* Footer */}
        <div className="p-6 border-t border-kaspersky-border flex justify-between items-center">
          <div className="text-sm text-kaspersky-text-light">
            {credentialsMode === 'global' && `Same credentials for all ${selectedMachines.length} machines`}
            {credentialsMode === 'custom' && `Custom credentials for each machine`}
          </div>
          
          <div className="flex gap-2">
            <Button
              onClick={onClose}
              variant="secondary"
              leftIcon={<X size={18} />}
            >
              Cancel
            </Button>
            <Button
              onClick={handleExecute}
              variant="primary"
              leftIcon={<Terminal size={18} />}
              disabled={!command.trim() || !isCommandAllowed || 
                (credentialsMode === 'global' && (!globalCredentials.username || !globalCredentials.password)) ||
                (credentialsMode === 'custom' && !selectedMachines.every(m => customCredentials[m.id]?.username && customCredentials[m.id]?.password))
              }
            >
              Execute on {selectedMachines.length} Machine{selectedMachines.length !== 1 ? 's' : ''}
            </Button>
          </div>
        </div>
      </div>
    </div>
  );
}

