import { memo, useCallback, useMemo } from 'react';
import { FixedSizeList as List } from 'react-window';
import { useNavigate } from 'react-router-dom';
import { Badge } from '@/components/ui/badge';
import { Checkbox } from '@/components/ui/checkbox';
import type { Scenario } from '@/types/api';

interface VirtualScenarioListProps {
  scenarios: Scenario[];
  selectedScenarios: Set<string>;
  onToggleScenario: (id: string) => void;
  onToggleAll: () => void;
}

const statusColors = {
  draft: 'secondary',
  running: 'default',
  completed: 'outline',
  archived: 'destructive',
} as const;

interface RowData {
  scenarios: Scenario[];
  selectedScenarios: Set<string>;
  onToggleScenario: (id: string) => void;
  onRowClick: (id: string) => void;
}

const ScenarioRow = memo(function ScenarioRow({
  index,
  style,
  data,
}: {
  index: number;
  style: React.CSSProperties;
  data: RowData;
}) {
  const scenario = data.scenarios[index];
  const isSelected = data.selectedScenarios.has(scenario.id);

  return (
    <div
      style={style}
      className="flex items-center border-b hover:bg-muted/50 cursor-pointer"
      onClick={() => data.onRowClick(scenario.id)}
      role="row"
      aria-selected={isSelected}
    >
      <div className="w-[50px] p-4" onClick={(e) => e.stopPropagation()}>
        <Checkbox
          checked={isSelected}
          onCheckedChange={() => data.onToggleScenario(scenario.id)}
          aria-label={`Select ${scenario.name}`}
        />
      </div>
      <div className="flex-1 p-4 font-medium">{scenario.name}</div>
      <div className="w-[120px] p-4">
        <Badge variant={statusColors[scenario.status]}>
          {scenario.status}
        </Badge>
      </div>
      <div className="w-[120px] p-4">{scenario.region}</div>
      <div className="w-[120px] p-4">{scenario.total_requests.toLocaleString()}</div>
      <div className="w-[120px] p-4">${scenario.total_cost_estimate.toFixed(6)}</div>
    </div>
  );
});

export const VirtualScenarioList = memo(function VirtualScenarioList({
  scenarios,
  selectedScenarios,
  onToggleScenario,
  onToggleAll,
}: VirtualScenarioListProps) {
  const navigate = useNavigate();

  const handleRowClick = useCallback((id: string) => {
    navigate(`/scenarios/${id}`);
  }, [navigate]);

  const itemData = useMemo<RowData>(
    () => ({
      scenarios,
      selectedScenarios,
      onToggleScenario,
      onRowClick: handleRowClick,
    }),
    [scenarios, selectedScenarios, onToggleScenario, handleRowClick]
  );

  const allSelected = useMemo(
    () => scenarios.length > 0 && scenarios.every((s) => selectedScenarios.has(s.id)),
    [scenarios, selectedScenarios]
  );

  return (
    <div className="border rounded-md">
      {/* Header */}
      <div className="flex items-center border-b bg-muted/50 font-medium" role="rowgroup">
        <div className="w-[50px] p-4">
          <Checkbox
            checked={allSelected}
            onCheckedChange={onToggleAll}
            aria-label="Select all scenarios"
          />
        </div>
        <div className="flex-1 p-4">Name</div>
        <div className="w-[120px] p-4">Status</div>
        <div className="w-[120px] p-4">Region</div>
        <div className="w-[120px] p-4">Requests</div>
        <div className="w-[120px] p-4">Cost</div>
      </div>
      
      {/* Virtual List */}
      <List
        height={400}
        itemCount={scenarios.length}
        itemSize={60}
        itemData={itemData}
        width="100%"
      >
        {ScenarioRow}
      </List>
    </div>
  );
});
