'use client';

import { useState, useCallback } 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 } from 'lucide-react';
import { Button } from '@/components/ui/button';
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 { data: processes, isLoading, isError, refetch } = useProcesses();

  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());
  };

  if (isLoading) {
    return (
      <div className="space-y-6">
        <h1 className="text-3xl font-bold">Processes</h1>
        <div className="grid 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-6">
        <h1 className="text-3xl font-bold">Processes</h1>
        <div className="flex flex-col items-center justify-center p-12 text-center">
          <AlertCircle className="h-12 w-12 text-destructive mb-4" />
          <h2 className="text-xl font-semibold mb-2">Failed to load processes</h2>
          <p className="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>
    );
  }

  const displayedProcesses = filteredProcesses.length > 0 || !processes ? filteredProcesses : processes;

  return (
    <div className="space-y-6 animate-fade-in">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-3xl font-bold">Processes</h1>
          <p className="text-muted-foreground mt-1">
            {displayedProcesses.length} of {processes?.length ?? 0} processes
            {displayedProcesses.length !== (processes?.length ?? 0) && ' (filtered)'}
          </p>
        </div>
        <div className="flex items-center gap-4">
          {viewMode === 'flat' && displayedProcesses.length > 0 && (
            <Button
              variant="outline"
              size="sm"
              onClick={handleSelectAll}
              className="gap-2"
            >
              <CheckSquare className="h-4 w-4" />
              {selectedProcesses.size === displayedProcesses.length ? 'Deselect All' : 'Select All'}
            </Button>
          )}
          <GroupSelector viewMode={viewMode} onViewModeChange={setViewMode} />
          <Button variant="outline" onClick={() => refetch()}>
            <RefreshCw className="h-4 w-4 mr-2" />
            Refresh
          </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-12 text-center border-2 border-dashed rounded-lg">
          <p className="text-muted-foreground">No processes configured</p>
        </div>
      ) : displayedProcesses.length === 0 ? (
        <div className="flex flex-col items-center justify-center p-12 text-center border-2 border-dashed rounded-lg">
          <p className="text-muted-foreground">No processes match the current filters</p>
        </div>
      ) : viewMode === 'grouped' ? (
        <GroupView processes={displayedProcesses} />
      ) : (
        <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
          {displayedProcesses.map((process) => {
            const fullName = `${process.group}:${process.name}`;
            return (
              <ProcessCard
                key={fullName}
                process={process}
                isSelected={selectedProcesses.has(fullName)}
                onSelectionChange={handleSelectionChange}
              />
            );
          })}
        </div>
      )}

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