import { useEffect, memo, useMemo, useCallback, useState } from 'react'
import { Search, Plus } from 'lucide-react'
import { log } from '../utils/logger'
import { useMachineStore } from '../store/machineStore'
import SmartConnectionButton from './SmartConnectionButton'
import { ProtocolOption } from '../utils/protocolHelper'
import { Machine } from '../types'
import { Button } from './shared/Button'

interface SidebarProps {
  onConnect?: (machine: Machine, protocol?: ProtocolOption) => void;
  machineStatuses?: Map<string, Machine['status']>;
  onMachineSelected?: (machine: Machine) => void;
  machineConnections?: Map<string, any>;
  userRole?: string;
  onBulkSelectionChange?: (selectedMachineIds: string[]) => void;
}

function Sidebar({ onConnect, machineStatuses, onMachineSelected, machineConnections, userRole, onBulkSelectionChange }: SidebarProps = {}) {
  const { 
    machines, 
    selectedMachine, 
    selectMachine, 
    fetchMachines, 
    loading,
    searchQuery,
    setSearchQuery,
    filteredMachines,
    setShowAddMachineModal
  } = useMachineStore();

  // ========================================================================================
  // Bulk Selection State
  // ========================================================================================
  const [selectedMachineIds, setSelectedMachineIds] = useState<Set<string>>(new Set());
  const [isBulkMode, setIsBulkMode] = useState(false);

  // Memoized filtered machines (declared early to avoid usage before declaration)
  const memoizedFilteredMachines = useMemo(() => filteredMachines, [filteredMachines]);

  // Toggle bulk selection mode
  const toggleBulkMode = useCallback(() => {
    setIsBulkMode(prev => !prev);
    if (isBulkMode) {
      // Exiting bulk mode - clear selection
      setSelectedMachineIds(new Set());
      onBulkSelectionChange?.([]);
    }
  }, [isBulkMode, onBulkSelectionChange]);

  // Toggle individual machine selection
  const toggleMachineSelection = useCallback((machineId: string) => {
    setSelectedMachineIds(prev => {
      const newSelection = new Set(prev);
      if (newSelection.has(machineId)) {
        newSelection.delete(machineId);
      } else {
        newSelection.add(machineId);
      }
      onBulkSelectionChange?.(Array.from(newSelection));
      return newSelection;
    });
  }, [onBulkSelectionChange]);

  // Select all machines
  const selectAllMachines = useCallback(() => {
    const allIds = new Set(memoizedFilteredMachines.map(m => m.id));
    setSelectedMachineIds(allIds);
    onBulkSelectionChange?.(Array.from(allIds));
  }, [memoizedFilteredMachines, onBulkSelectionChange]);

  // Deselect all machines
  const deselectAllMachines = useCallback(() => {
    setSelectedMachineIds(new Set());
    onBulkSelectionChange?.([]);
  }, [onBulkSelectionChange]);

  // Memoized: are all machines selected?
  const allSelected = useMemo(() => {
    if (memoizedFilteredMachines.length === 0) return false;
    return memoizedFilteredMachines.every(m => selectedMachineIds.has(m.id));
  }, [memoizedFilteredMachines, selectedMachineIds]);

  // Clear selection when filteredMachines changes
  useEffect(() => {
    if (isBulkMode) {
      setSelectedMachineIds(new Set());
      onBulkSelectionChange?.([]);
    }
  }, [searchQuery]); // Reset selection on search change

  /**
   * Get machine status (from props or use default)
   */
  const getMachineStatus = useCallback(
    (machineId: string): Machine['status'] => {
    return machineStatuses?.get(machineId) || 'unknown';
    },
    [machineStatuses]
  );

  /**
   * Get status indicator color
   */
  const getStatusColor = useCallback((status: Machine['status']): string => {
    switch (status) {
      case 'running':
        return 'bg-kaspersky-success shadow-green-300 shadow-sm';
      case 'stopped':
        return 'bg-kaspersky-danger shadow-red-300 shadow-sm';
      case 'checking':
        return 'bg-kaspersky-warning shadow-yellow-300 shadow-sm animate-pulse';
      case 'error':
        return 'bg-kaspersky-warning shadow-yellow-300 shadow-sm';
      case 'unknown':
      default:
        return 'bg-gray-400 shadow-gray-300 shadow-sm';
    }
  }, []);

  /**
   * Debug log on component mount
   */
  useEffect(() => {
    log.info('sidebar', 'Component mounted');
    return () => {
      log.info('sidebar', 'Component unmounted');
    };
  }, []);

  /**
   * Debug log on machines change
   */
  useEffect(() => {
    log.info('sidebar', 'Machines updated', { 
      count: machines.length,
      machines: machines.map((m) => ({ id: m.id, name: m.name, status: m.status })),
    });
  }, [machines]);

  /**
   * Initial load and periodic refresh
   */
  useEffect(() => {
    log.info('sidebar', 'Starting initial fetch');
    fetchMachines();
    // Refresh machine list every 30 seconds
    const interval = setInterval(fetchMachines, 30000);
    return () => clearInterval(interval);
  }, [fetchMachines]);

  const handleSearch = useCallback(
    (event: React.ChangeEvent<HTMLInputElement>) => {
    setSearchQuery(event.target.value);
    },
    [setSearchQuery]
  );

  const handleConnect = useCallback(
    (machine: Machine, protocol?: ProtocolOption) => {
      selectMachine(machine);
      onConnect?.(machine, protocol);
    },
    [selectMachine, onConnect]
  );

  return (
    <div className="w-96 bg-white border-r border-kaspersky-border shadow-kaspersky select-none">
      <div className="p-4">
        <div className="relative">
          <input
            type="text"
            placeholder="Search machines..."
            value={searchQuery}
            onChange={handleSearch}
            className="w-full pl-10 pr-4 py-2 bg-kaspersky-bg text-kaspersky-text rounded-lg border-2 border-kaspersky-border focus:outline-none focus:border-kaspersky-primary focus:bg-white transition-all duration-300 select-text"
          />
          <div className="absolute left-3 top-1/2 transform -translate-y-1/2">
            <Search size={18} className="text-kaspersky-text-lighter" />
          </div>
        </div>

        {/* Add Machine Button */}
        <div className="mt-3">
          <Button
            variant="primary"
            size="md"
            fullWidth
            onClick={() => setShowAddMachineModal(true)}
            leftIcon={<Plus size={18} />}
          >
            Add Custom Machine
          </Button>
        </div>
      </div>

      {/* Bulk Selection Controls */}
      <div className="border-t border-kaspersky-border pt-3 px-4 pb-2">
        <div className="flex items-center justify-between">
          <button
            onClick={toggleBulkMode}
            className={`text-sm font-medium transition-colors ${
              isBulkMode 
                ? 'text-kaspersky-primary' 
                : 'text-kaspersky-text-light hover:text-kaspersky-text-dark'
            }`}
          >
            {isBulkMode ? '✓ Bulk Mode' : 'Bulk Select'}
          </button>
          
          {isBulkMode && memoizedFilteredMachines.length > 0 && (
            <div className="flex items-center gap-3">
              <span className="text-sm text-kaspersky-text-light">
                {selectedMachineIds.size} selected
              </span>
              <label className="flex items-center gap-2 cursor-pointer">
                <input
                  type="checkbox"
                  checked={allSelected}
                  onChange={() => allSelected ? deselectAllMachines() : selectAllMachines()}
                  className="w-4 h-4 text-kaspersky-primary bg-kaspersky-bg border-kaspersky-border rounded focus:ring-kaspersky-primary focus:ring-2"
                />
                <span className="text-sm text-kaspersky-text-light">All</span>
              </label>
            </div>
          )}
        </div>
      </div>

      <div className="overflow-y-auto h-[calc(100vh-11rem)]">
        {loading ? (
          <div className="flex items-center justify-center h-32">
            <div className="w-8 h-8 border-4 border-kaspersky-primary border-t-transparent rounded-full animate-spin"></div>
          </div>
        ) : (
          <div className="space-y-1 p-2">
            {memoizedFilteredMachines.map((machine) => (
              <div
                key={machine.id}
                className={`rounded-lg transition-all duration-200 ${
                  selectedMachine?.id === machine.id
                    ? 'bg-kaspersky-primary/10 border-2 border-kaspersky-primary shadow-kaspersky'
                    : 'hover:bg-kaspersky-bg border-2 border-transparent hover:shadow-sm'
                }`}
              >
                <div className="p-3">
                  <div className="flex items-center justify-between">
                    {/* Bulk Selection Checkbox */}
                    {isBulkMode && (
                      <label 
                        className="flex-shrink-0 mr-2 cursor-pointer"
                        onClick={(e) => e.stopPropagation()}
                      >
                        <input
                          type="checkbox"
                          checked={selectedMachineIds.has(machine.id)}
                          onChange={() => toggleMachineSelection(machine.id)}
                          className="w-4 h-4 text-kaspersky-primary bg-kaspersky-bg border-kaspersky-border rounded focus:ring-kaspersky-primary focus:ring-2"
                        />
                      </label>
                    )}
                    
                    <button
                      onClick={() => {
                        if (!isBulkMode) {
                          selectMachine(machine);
                          // Trigger availability check on machine click
                          if (onMachineSelected) {
                            onMachineSelected(machine);
                          }
                        } else {
                          // In bulk mode, clicking selects/deselects
                          toggleMachineSelection(machine.id);
                        }
                      }}
                      className="flex items-center text-left flex-1 min-w-0"
                    >
                      {!isBulkMode && (
                        <div
                          className={`w-3 h-3 rounded-full mr-3 flex-shrink-0 ${getStatusColor(getMachineStatus(machine.id))}`}
                          title={`Status: ${getMachineStatus(machine.id)}`}
                        />
                      )}
                      <div className="flex-1 min-w-0">
                        <div className="font-medium text-kaspersky-text-dark truncate">{machine.name}</div>
                        <div className="text-sm text-kaspersky-text-light">
                          <span className="truncate">{machine.ip}</span>
                        </div>
                      </div>
                    </button>
                    
                    {onConnect && !isBulkMode && (
                      <div className="ml-3 flex-shrink-0">
                        <SmartConnectionButton
                          machine={machine}
                          onConnect={handleConnect}
                          isConnected={machineConnections?.has(machine.id)}
                          userRole={userRole}
                          size="sm"
                          className="w-auto"
                        />
                      </div>
                    )}
                  </div>
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  )
}

export default memo(Sidebar) 