import React, { useState, useEffect } from 'react';
import { X, Monitor, Clock, RefreshCw, XCircle, CheckSquare, Square } from 'lucide-react';
import type { ActiveConnection } from '../services/guacamole-api';

interface RestoreConnectionsModalProps {
  isOpen: boolean;
  connections: ActiveConnection[];
  onRestore: (connection: ActiveConnection) => void;
  onRestoreMultiple: (connections: ActiveConnection[]) => void;
  onClose: () => void;
  onSkip: () => void;
}

const RestoreConnectionsModal: React.FC<RestoreConnectionsModalProps> = ({
  isOpen,
  connections,
  onRestore,
  onRestoreMultiple,
  onClose,
  onSkip
}) => {
  const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());

  // Reset selection when modal closes
  useEffect(() => {
    if (!isOpen) {
      setSelectedIds(new Set());
    }
  }, [isOpen]);

  if (!isOpen) return null;

  const toggleSelection = (connectionId: string) => {
    setSelectedIds(prev => {
      const newSet = new Set(prev);
      if (newSet.has(connectionId)) {
        newSet.delete(connectionId);
      } else {
        newSet.add(connectionId);
      }
      return newSet;
    });
  };

  const selectAll = () => {
    setSelectedIds(new Set(connections.map(c => c.connection_id)));
  };

  const deselectAll = () => {
    setSelectedIds(new Set());
  };

  const handleRestoreSelected = () => {
    const selectedConnections = connections.filter(c => selectedIds.has(c.connection_id));
    if (selectedConnections.length > 0) {
      onRestoreMultiple(selectedConnections);
      setSelectedIds(new Set());
    }
  };

  const handleRestoreAll = () => {
    onRestoreMultiple(connections);
    setSelectedIds(new Set());
  };

  const getProtocolColor = (protocol: string) => {
    switch (protocol.toLowerCase()) {
      case 'rdp':
        return 'bg-blue-100 text-blue-700 border-blue-200';
      case 'ssh':
        return 'bg-green-100 text-green-700 border-green-200';
      case 'vnc':
        return 'bg-purple-100 text-purple-700 border-purple-200';
      default:
        return 'bg-gray-100 text-gray-700 border-gray-200';
    }
  };

  const formatTimeRemaining = (minutes: number): string => {
    if (minutes < 60) {
      return `${minutes} мин`;
    }
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    return mins > 0 ? `${hours}ч ${mins}м` : `${hours}ч`;
  };

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-2xl max-h-[80vh] flex flex-col select-none">
        {/* Header */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200">
          <div className="flex items-center gap-3">
            <div className="w-12 h-12 bg-kaspersky-primary/10 rounded-xl flex items-center justify-center">
              <RefreshCw className="text-kaspersky-primary" size={24} />
            </div>
            <div>
              <h2 className="text-2xl font-bold text-kaspersky-text-dark">
                Восстановить подключения
              </h2>
              <p className="text-sm text-kaspersky-text-light mt-1">
                У вас есть {connections.length} активных {connections.length === 1 ? 'подключение' : 'подключения'}
              </p>
            </div>
          </div>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600 transition-colors p-2 hover:bg-gray-100 rounded-lg"
          >
            <X size={24} />
          </button>
        </div>

        {/* Content */}
        <div className="flex-1 overflow-y-auto p-6">
          <div className="flex items-center justify-between mb-4">
            <p className="text-kaspersky-text">
              Выберите подключения для восстановления:
            </p>
            <div className="flex gap-2">
              <button
                onClick={selectAll}
                className="text-xs text-kaspersky-primary hover:text-kaspersky-primary-dark font-medium transition-colors"
              >
                Выбрать все
              </button>
              <span className="text-gray-300">|</span>
              <button
                onClick={deselectAll}
                className="text-xs text-kaspersky-text-light hover:text-kaspersky-text font-medium transition-colors"
              >
                Снять выбор
              </button>
            </div>
          </div>

          <div className="space-y-3">
            {connections.map((connection) => {
              const isSelected = selectedIds.has(connection.connection_id);
              return (
                <div
                  key={connection.connection_id}
                  className={`border-2 rounded-xl p-4 transition-all duration-200 hover:shadow-md cursor-pointer group ${
                    isSelected 
                      ? 'border-kaspersky-primary bg-kaspersky-primary/5' 
                      : 'border-kaspersky-border hover:border-kaspersky-primary'
                  }`}
                  onClick={() => toggleSelection(connection.connection_id)}
                >
                  <div className="flex items-start justify-between">
                    <div className="flex items-start gap-3 flex-1">
                      {/* Чекбокс */}
                      <div className="flex-shrink-0 pt-1">
                        <div className={`w-5 h-5 rounded border-2 flex items-center justify-center transition-all ${
                          isSelected 
                            ? 'bg-kaspersky-primary border-kaspersky-primary' 
                            : 'border-gray-300 group-hover:border-kaspersky-primary'
                        }`}>
                          {isSelected ? (
                            <CheckSquare size={16} className="text-white" strokeWidth={3} />
                          ) : (
                            <Square size={16} className="text-transparent" />
                          )}
                        </div>
                      </div>
                      
                      <div className="w-10 h-10 bg-kaspersky-bg rounded-lg flex items-center justify-center flex-shrink-0 group-hover:bg-kaspersky-primary/10 transition-colors">
                        <Monitor className="text-kaspersky-primary" size={20} />
                      </div>
                      <div className="flex-1 min-w-0">
                        <h3 className="font-semibold text-kaspersky-text-dark text-lg mb-1 truncate">
                          {connection.hostname}
                        </h3>
                        <div className="flex flex-wrap items-center gap-2 mb-2">
                          <span className={`px-2 py-1 rounded-md text-xs font-medium border ${getProtocolColor(connection.protocol)}`}>
                            {connection.protocol.toUpperCase()}
                          </span>
                          <span className="text-xs text-kaspersky-text-light flex items-center gap-1">
                            <Clock size={12} />
                            Осталось: {formatTimeRemaining(connection.remaining_minutes)}
                          </span>
                        </div>
                        <p className="text-xs text-kaspersky-text-lighter">
                          Создано: {new Date(connection.created_at).toLocaleString('ru-RU', {
                            day: '2-digit',
                            month: '2-digit',
                            hour: '2-digit',
                            minute: '2-digit'
                          })}
                        </p>
                      </div>
                    </div>
                    <button
                      onClick={(e) => {
                        e.stopPropagation();
                        onRestore(connection);
                      }}
                      className="ml-4 px-4 py-2 bg-kaspersky-primary hover:bg-kaspersky-primary-dark text-white rounded-lg transition-colors font-medium text-sm flex items-center gap-2 whitespace-nowrap"
                    >
                      <RefreshCw size={16} />
                      Восстановить
                    </button>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Footer */}
        <div className="flex items-center justify-between gap-3 p-6 border-t border-gray-200 bg-gray-50">
          <p className="text-sm text-kaspersky-text-light">
            {selectedIds.size > 0 
              ? `Выбрано: ${selectedIds.size} из ${connections.length}`
              : 'Выберите подключения или создайте новое'
            }
          </p>
          <div className="flex gap-3">
            <button
              onClick={onSkip}
              className="px-6 py-2.5 bg-white border-2 border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors font-medium flex items-center gap-2"
            >
              <XCircle size={18} />
              Создать новое
            </button>
            <button
              onClick={handleRestoreAll}
              className="px-6 py-2.5 bg-kaspersky-secondary hover:bg-kaspersky-secondary/90 text-white rounded-lg transition-colors font-medium flex items-center gap-2"
            >
              <RefreshCw size={18} />
              Восстановить всё
            </button>
            <button
              onClick={handleRestoreSelected}
              disabled={selectedIds.size === 0}
              className={`px-6 py-2.5 rounded-lg transition-colors font-medium flex items-center gap-2 ${
                selectedIds.size === 0
                  ? 'bg-gray-300 text-gray-500 cursor-not-allowed'
                  : 'bg-kaspersky-primary hover:bg-kaspersky-primary-dark text-white'
              }`}
            >
              <RefreshCw size={18} />
              Восстановить выбранные
            </button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default RestoreConnectionsModal;

