'use client';

import { useState, useCallback, useRef, useEffect } from 'react';
import { useProcesses } from '@/lib/hooks/useSupervisor';
import { ProcessCard } from '@/components/process/ProcessCard';
import { GroupView } from '@/components/groups/GroupView';
import { GroupSelector } from '@/components/groups/GroupSelector';
import { BatchActions } from '@/components/process/BatchActions';
import { ProcessFilters } from '@/components/process/ProcessFilters';
import { RefreshCw, AlertCircle, CheckSquare, Keyboard } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useKeyboardShortcuts } from '@/lib/hooks/useKeyboardShortcuts';
import { KeyboardShortcutsHelp } from '@/components/ui/KeyboardShortcutsHelp';
import { ConnectionStatus } from '@/components/ui/ConnectionStatus';
import { useEventSource } from '@/lib/hooks/useEventSource';
import type { ProcessInfo } from '@/lib/supervisor/types';

export default function ProcessesPage() {
  const [viewMode, setViewMode] = useState<'flat' | 'grouped'>('flat');
  const [selectedProcesses, setSelectedProcesses] = useState<Set<string>>(new Set());
  const [filteredProcesses, setFilteredProcesses] = useState<ProcessInfo[]>([]);
  const [showShortcutsHelp, setShowShortcutsHelp] = useState(false);
  const [focusedIndex, setFocusedIndex] = useState<number>(-1);
  const [realtimeEnabled, setRealtimeEnabled] = useState(true);
  const searchInputRef = useRef<HTMLInputElement>(null);
  const { data: processes, isLoading, isError, refetch } = useProcesses();

  // Real-time updates via Server-Sent Events
  const { status: connectionStatus, reconnectAttempts, reconnect } = useEventSource(
    '/api/supervisor/events',
    {
      enabled: realtimeEnabled && !isLoading && !isError,
      onMessage: (message) => {
        if (message.event === 'process-update') {
          // Invalidate and refetch process data
          refetch();
        }
      },
      onConnect: () => {
        console.log('SSE connected');
      },
      onDisconnect: () => {
        console.log('SSE disconnected');
      },
    }
  );

  const handleFilterChange = useCallback((filtered: ProcessInfo[]) => {
    setFilteredProcesses(filtered);
  }, []);

  const handleSelectionChange = (processId: string, selected: boolean) => {
    setSelectedProcesses((prev) => {
      const newSet = new Set(prev);
      if (selected) {
        newSet.add(processId);
      } else {
        newSet.delete(processId);
      }
      return newSet;
    });
  };

  const handleSelectAll = () => {
    const displayedProcesses = filteredProcesses.length > 0 ? filteredProcesses : (processes || []);
    if (displayedProcesses) {
      if (selectedProcesses.size === displayedProcesses.length) {
        setSelectedProcesses(new Set());
      } else {
        setSelectedProcesses(new Set(displayedProcesses.map((p) => `${p.group}:${p.name}`)));
      }
    }
  };

  const handleClearSelection = () => {
    setSelectedProcesses(new Set());
  };

  // Get displayedProcesses for keyboard navigation
  const displayedProcesses = filteredProcesses.length > 0 || !processes ? filteredProcesses : (processes || []);

  // Keyboard shortcuts
  useKeyboardShortcuts({
    shortcuts: [
      {
        key: '/',
        description: 'Focus search',
        action: () => {
          // Find and focus the search input
          const searchInput = document.querySelector('input[type="text"]') as HTMLInputElement;
          if (searchInput) {
            searchInput.focus();
          }
        },
      },
      {
        key: 'r',
        description: 'Refresh',
        action: () => {
          refetch();
        },
      },
      {
        key: 'a',
        description: 'Select all',
        action: () => {
          if (viewMode === 'flat') {
            handleSelectAll();
          }
        },
        enabled: viewMode === 'flat' && displayedProcesses.length > 0,
      },
      {
        key: 'Escape',
        description: 'Clear selection',
        action: () => {
          if (selectedProcesses.size > 0) {
            handleClearSelection();
          }
          setFocusedIndex(-1);
        },
      },
      {
        key: '?',
        shift: true,
        description: 'Show keyboard shortcuts',
        action: () => {
          setShowShortcutsHelp(true);
        },
      },
      {
        key: 'j',
        description: 'Next process',
        action: () => {
          if (viewMode === 'flat' && displayedProcesses.length > 0) {
            setFocusedIndex((prev) => {
              const next = prev + 1;
              return next >= displayedProcesses.length ? 0 : next;
            });
          }
        },
        enabled: viewMode === 'flat' && displayedProcesses.length > 0,
      },
      {
        key: 'k',
        description: 'Previous process',
        action: () => {
          if (viewMode === 'flat' && displayedProcesses.length > 0) {
            setFocusedIndex((prev) => {
              const next = prev - 1;
              return next < 0 ? displayedProcesses.length - 1 : next;
            });
          }
        },
        enabled: viewMode === 'flat' && displayedProcesses.length > 0,
      },
      {
        key: ' ',
        description: 'Toggle selection',
        action: () => {
          if (viewMode === 'flat' && focusedIndex >= 0 && focusedIndex < displayedProcesses.length) {
            const process = displayedProcesses[focusedIndex];
            const fullName = `${process.group}:${process.name}`;
            handleSelectionChange(fullName, !selectedProcesses.has(fullName));
          }
        },
        enabled: viewMode === 'flat' && focusedIndex >= 0 && displayedProcesses.length > 0,
      },
    ],
  });

  // Auto-select focused process
  useEffect(() => {
    if (focusedIndex >= 0 && focusedIndex < displayedProcesses.length) {
      const process = displayedProcesses[focusedIndex];
      const fullName = `${process.group}:${process.name}`;
      const element = document.querySelector(`[data-process-id="${fullName}"]`);
      if (element) {
        element.scrollIntoView({ behavior: 'smooth', block: 'center' });
      }
    }
  }, [focusedIndex, displayedProcesses]);

  if (isLoading) {
    return (
      <div className="space-y-4 md:space-y-6">
        <h1 className="text-2xl sm:text-3xl font-bold">Processes</h1>
        <div className="grid gap-4 md:gap-6 md:grid-cols-2 lg:grid-cols-3">
          {[1, 2, 3, 4, 5, 6].map((i) => (
            <div key={i} className="h-64 bg-muted rounded-lg animate-pulse" />
          ))}
        </div>
      </div>
    );
  }

  if (isError) {
    return (
      <div className="space-y-4 md:space-y-6">
        <h1 className="text-2xl sm:text-3xl font-bold">Processes</h1>
        <div className="flex flex-col items-center justify-center p-8 md:p-12 text-center">
          <AlertCircle className="h-10 w-10 md:h-12 md:w-12 text-destructive mb-4" />
          <h2 className="text-lg md:text-xl font-semibold mb-2">Failed to load processes</h2>
          <p className="text-sm md:text-base text-muted-foreground mb-4">
            Could not connect to Supervisor. Please check your configuration.
          </p>
          <Button onClick={() => refetch()}>
            <RefreshCw className="h-4 w-4 mr-2" />
            Retry
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="space-y-6 animate-fade-in">
      {/* Header - responsive layout */}
      <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
        <div className="flex items-start gap-4 flex-wrap">
          <div>
            <h1 className="text-2xl sm:text-3xl font-bold">Processes</h1>
            <p className="text-sm md:text-base text-muted-foreground mt-1">
              {displayedProcesses.length} of {processes?.length ?? 0} processes
              {displayedProcesses.length !== (processes?.length ?? 0) && ' (filtered)'}
            </p>
          </div>
          <ConnectionStatus
            status={connectionStatus}
            reconnectAttempts={reconnectAttempts}
            onReconnect={reconnect}
          />
        </div>

        {/* Controls - stack on mobile, row on desktop */}
        <div className="flex flex-wrap items-center gap-2">
          {viewMode === 'flat' && displayedProcesses.length > 0 && (
            <Button
              variant="outline"
              size="sm"
              onClick={handleSelectAll}
              className="gap-2"
            >
              <CheckSquare className="h-4 w-4" />
              <span className="hidden sm:inline">
                {selectedProcesses.size === displayedProcesses.length ? 'Deselect All' : 'Select All'}
              </span>
            </Button>
          )}
          <GroupSelector viewMode={viewMode} onViewModeChange={setViewMode} />
          <Button variant="outline" size="sm" onClick={() => refetch()}>
            <RefreshCw className="h-4 w-4" />
            <span className="hidden sm:inline ml-2">Refresh</span>
          </Button>
          <Button
            variant="outline"
            size="sm"
            onClick={() => setShowShortcutsHelp(true)}
            title="Keyboard Shortcuts (Shift+?)"
          >
            <Keyboard className="h-4 w-4" />
          </Button>
        </div>
      </div>

      {/* Filters */}
      {processes && processes.length > 0 && (
        <ProcessFilters processes={processes} onFilterChange={handleFilterChange} />
      )}

      {/* Process Display */}
      {processes && processes.length === 0 ? (
        <div className="flex flex-col items-center justify-center p-8 md:p-12 text-center border-2 border-dashed rounded-lg">
          <p className="text-sm md:text-base text-muted-foreground">No processes configured</p>
        </div>
      ) : displayedProcesses.length === 0 ? (
        <div className="flex flex-col items-center justify-center p-8 md:p-12 text-center border-2 border-dashed rounded-lg">
          <p className="text-sm md:text-base text-muted-foreground">No processes match the current filters</p>
        </div>
      ) : viewMode === 'grouped' ? (
        <GroupView processes={displayedProcesses} />
      ) : (
        <div className="grid gap-4 md:gap-6 md:grid-cols-2 lg:grid-cols-3">
          {displayedProcesses.map((process, index) => {
            const fullName = `${process.group}:${process.name}`;
            const isFocused = index === focusedIndex;
            return (
              <div key={fullName} data-process-id={fullName}>
                <ProcessCard
                  process={process}
                  isSelected={selectedProcesses.has(fullName)}
                  onSelectionChange={handleSelectionChange}
                  isFocused={isFocused}
                />
              </div>
            );
          })}
        </div>
      )}

      <BatchActions
        selectedProcesses={selectedProcesses}
        processes={displayedProcesses}
        onClearSelection={handleClearSelection}
      />

      {/* Keyboard Shortcuts Help */}
      {showShortcutsHelp && (
        <KeyboardShortcutsHelp onClose={() => setShowShortcutsHelp(false)} />
      )}
    </div>
  );
}
