/**
 * Modal for adding new machine
 */

import React, { useState } from 'react';
import { X, Save, Plus } from 'lucide-react';
import { useMachineStore } from '../store/machineStore';
import { SavedMachineCreate } from '../services/saved-machines-api';
import { log } from '../utils/logger';
import { Button } from './shared/Button';

interface AddMachineModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess?: () => void;
}

export const AddMachineModal: React.FC<AddMachineModalProps> = ({
  isOpen,
  onClose,
  onSuccess
}) => {
  const { createSavedMachine, setShowSaveConfirmModal, setMachineToSave } = useMachineStore();
  
  const [formData, setFormData] = useState<SavedMachineCreate>({
    name: '',
    hostname: '',
    port: 3389,
    protocol: 'rdp',
    os: '',
    description: '',
    tags: [],
    is_favorite: false
  });
  
  const [tagInput, setTagInput] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [askToSave, setAskToSave] = useState(true);

  const handleInputChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>
  ) => {
    const { name, value, type } = e.target;
    
    setFormData(prev => ({
      ...prev,
      [name]: type === 'number' ? parseInt(value) : value
    }));
  };

  const handleCheckboxChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, checked } = e.target;
    setFormData(prev => ({
      ...prev,
      [name]: checked
    }));
  };

  const handleAddTag = () => {
    if (tagInput.trim() && !formData.tags?.includes(tagInput.trim())) {
      setFormData(prev => ({
        ...prev,
        tags: [...(prev.tags || []), tagInput.trim()]
      }));
      setTagInput('');
    }
  };

  const handleRemoveTag = (tagToRemove: string) => {
    setFormData(prev => ({
      ...prev,
      tags: prev.tags?.filter(tag => tag !== tagToRemove) || []
    }));
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    // Validation
    if (!formData.name.trim()) {
      setError('Название машины обязательно');
      return;
    }
    if (!formData.hostname.trim()) {
      setError('Хост обязателен');
      return;
    }
    if (formData.port < 1 || formData.port > 65535) {
      setError('Порт должен быть от 1 до 65535');
      return;
    }
    
    setError(null);
    
    // If "ask before saving" is selected
    if (askToSave) {
      setMachineToSave(formData);
      setShowSaveConfirmModal(true);
      onClose();
      return;
    }
    
    // Otherwise save immediately
    setLoading(true);
    try {
      log.info('AddMachineModal', 'Creating machine', { name: formData.name });
      
      await createSavedMachine(formData);
      
      log.info('AddMachineModal', 'Machine created successfully');
      
      // Reset form
      resetForm();
      
      if (onSuccess) {
        onSuccess();
      }
      onClose();
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : 'Не удалось создать машину';
      log.error('AddMachineModal', 'Failed to create machine', { error: errorMessage });
      setError(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  const resetForm = () => {
    setFormData({
      name: '',
      hostname: '',
      port: 3389,
      protocol: 'rdp',
      os: '',
      description: '',
      tags: [],
      is_favorite: false
    });
    setTagInput('');
    setError(null);
  };

  const handleClose = () => {
    resetForm();
    onClose();
  };

  if (!isOpen) return null;

  return (
    <div className="fixed inset-0 bg-black bg-opacity-60 flex items-center justify-center z-50 p-4 backdrop-blur-sm">
      <div className="bg-kaspersky-bg-card rounded-lg shadow-2xl max-w-2xl w-full max-h-[90vh] overflow-y-auto border border-kaspersky-border select-none">
        <div className="p-6">
          {/* Header */}
          <div className="flex items-center justify-between mb-6">
            <h2 className="text-2xl font-bold text-kaspersky-text-dark">Добавить машину</h2>
            <button
              onClick={handleClose}
              className="text-kaspersky-text-light hover:text-kaspersky-danger transition-colors p-1 rounded-lg hover:bg-kaspersky-bg"
              disabled={loading}
            >
              <X size={24} />
            </button>
          </div>

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

          {/* Form */}
          <form onSubmit={handleSubmit} className="space-y-4">
            {/* Name */}
            <div>
              <label htmlFor="name" className="block text-sm font-semibold text-kaspersky-text-dark mb-2">
                Название *
              </label>
              <input
                type="text"
                id="name"
                name="name"
                value={formData.name}
                onChange={handleInputChange}
                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"
                placeholder="Например: Production Server"
                required
                disabled={loading}
              />
            </div>

            {/* Hostname */}
            <div>
              <label htmlFor="hostname" className="block text-sm font-semibold text-kaspersky-text-dark mb-2">
                Хост (IP или домен) *
              </label>
              <input
                type="text"
                id="hostname"
                name="hostname"
                value={formData.hostname}
                onChange={handleInputChange}
                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"
                placeholder="192.168.1.100 или example.com"
                required
                disabled={loading}
              />
            </div>

            {/* Operating System */}
            <div>
              <label htmlFor="os" className="block text-sm font-semibold text-kaspersky-text-dark mb-2">
                Операционная система
              </label>
              <input
                type="text"
                id="os"
                name="os"
                value={formData.os}
                onChange={handleInputChange}
                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"
                placeholder="Windows Server 2019, Ubuntu 22.04, etc."
                disabled={loading}
              />
            </div>

            {/* Protocol and Port */}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label htmlFor="protocol" className="block text-sm font-semibold text-kaspersky-text-dark mb-2">
                  Протокол *
                </label>
                <select
                  id="protocol"
                  name="protocol"
                  value={formData.protocol}
                  onChange={handleInputChange}
                  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={loading}
                >
                  <option value="rdp">RDP</option>
                  <option value="ssh">SSH</option>
                  <option value="vnc">VNC</option>
                  <option value="telnet">Telnet</option>
                </select>
              </div>
              
              <div>
                <label htmlFor="port" className="block text-sm font-semibold text-kaspersky-text-dark mb-2">
                  Порт *
                </label>
                <input
                  type="number"
                  id="port"
                  name="port"
                  value={formData.port}
                  onChange={handleInputChange}
                  min="1"
                  max="65535"
                  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={loading}
                />
              </div>
            </div>

            {/* Description */}
            <div>
              <label htmlFor="description" className="block text-sm font-semibold text-kaspersky-text-dark mb-2">
                Описание
              </label>
              <textarea
                id="description"
                name="description"
                value={formData.description}
                onChange={handleInputChange}
                rows={3}
                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 resize-none transition-all duration-200 select-text"
                placeholder="Опциональное описание машины"
                disabled={loading}
              />
            </div>

            {/* Tags */}
            <div>
              <label className="block text-sm font-semibold text-kaspersky-text-dark mb-2">
                Теги
              </label>
              <div className="flex gap-2 mb-2">
                <input
                  type="text"
                  value={tagInput}
                  onChange={(e) => setTagInput(e.target.value)}
                  onKeyPress={(e) => e.key === 'Enter' && (e.preventDefault(), handleAddTag())}
                  className="flex-1 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"
                  placeholder="Введите тег и нажмите Enter"
                  disabled={loading}
                />
                <Button
                  type="button"
                  onClick={handleAddTag}
                  variant="secondary"
                  disabled={loading || !tagInput.trim()}
                  leftIcon={<Plus size={16} />}
                >
                  Добавить
                </Button>
              </div>
              {formData.tags && formData.tags.length > 0 && (
                <div className="flex flex-wrap gap-2">
                  {formData.tags.map((tag, index) => (
                    <span
                      key={index}
                      className="inline-flex items-center gap-1.5 px-3 py-1.5 bg-kaspersky-primary bg-opacity-10 text-kaspersky-primary rounded-lg text-sm font-medium border border-kaspersky-primary border-opacity-30"
                    >
                      {tag}
                      <button
                        type="button"
                        onClick={() => handleRemoveTag(tag)}
                        className="hover:text-kaspersky-danger transition-colors ml-1"
                        disabled={loading}
                      >
                        <X size={14} />
                      </button>
                    </span>
                  ))}
                </div>
              )}
            </div>

            {/* Is Favorite */}
            <div className="flex items-center gap-3 p-3 bg-kaspersky-bg rounded-lg border border-kaspersky-border">
              <input
                type="checkbox"
                id="is_favorite"
                name="is_favorite"
                checked={formData.is_favorite}
                onChange={handleCheckboxChange}
                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={loading}
              />
              <label htmlFor="is_favorite" className="text-sm font-medium text-kaspersky-text-dark cursor-pointer flex-1">
                ⭐ Добавить в избранное
              </label>
            </div>

            {/* Ask to save */}
            <div className="flex items-center gap-3 p-3 bg-kaspersky-bg rounded-lg border border-kaspersky-border">
              <input
                type="checkbox"
                id="askToSave"
                checked={askToSave}
                onChange={(e) => setAskToSave(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={loading}
              />
              <label htmlFor="askToSave" className="text-sm font-medium text-kaspersky-text-dark cursor-pointer flex-1">
                💬 Спросить подтверждение перед сохранением
              </label>
            </div>

            {/* Actions */}
            <div className="flex gap-3 pt-4">
              <Button
                type="submit"
                variant="primary"
                fullWidth
                disabled={loading}
                isLoading={loading}
                leftIcon={!loading ? <Save size={18} /> : undefined}
              >
                {loading ? 'Сохранение...' : 'Сохранить'}
              </Button>
              <Button
                type="button"
                variant="secondary"
                onClick={handleClose}
                disabled={loading}
                leftIcon={<X size={18} />}
              >
                Отмена
              </Button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

