import { useState, useCallback } from 'react';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Checkbox } from '@/components/ui/checkbox';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  MoreHorizontal,
  Trash2,
  FileSpreadsheet,
  FileText,
  X,
  BarChart3,
} from 'lucide-react';
import type { Scenario } from '@/types/api';

interface BulkOperationsBarProps {
  selectedScenarios: Set<string>;
  scenarios: Scenario[];
  onClearSelection: () => void;
  onBulkDelete: (ids: string[]) => Promise<void>;
  onBulkExport: (ids: string[], format: 'json' | 'csv') => Promise<void>;
  onCompare: (ids: string[]) => void;
  maxCompare?: number;
}

export function BulkOperationsBar({
  selectedScenarios,
  scenarios,
  onClearSelection,
  onBulkDelete,
  onBulkExport,
  onCompare,
  maxCompare = 4,
}: BulkOperationsBarProps) {
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [isDeleting, setIsDeleting] = useState(false);
  const [isExporting, setIsExporting] = useState(false);

  const selectedCount = selectedScenarios.size;
  const selectedScenarioData = scenarios.filter((s) => selectedScenarios.has(s.id));
  const canCompare = selectedCount >= 2 && selectedCount <= maxCompare;

  const handleDelete = useCallback(async () => {
    setIsDeleting(true);
    try {
      await onBulkDelete(Array.from(selectedScenarios));
      setShowDeleteConfirm(false);
      onClearSelection();
    } finally {
      setIsDeleting(false);
    }
  }, [selectedScenarios, onBulkDelete, onClearSelection]);

  const handleExport = useCallback(async (format: 'json' | 'csv') => {
    setIsExporting(true);
    try {
      await onBulkExport(Array.from(selectedScenarios), format);
    } finally {
      setIsExporting(false);
    }
  }, [selectedScenarios, onBulkExport]);

  const handleCompare = useCallback(() => {
    if (canCompare) {
      onCompare(Array.from(selectedScenarios));
    }
  }, [canCompare, onCompare, selectedScenarios]);

  if (selectedCount === 0) {
    return null;
  }

  return (
    <>
      <div 
        className="bg-muted/50 rounded-lg p-3 flex items-center justify-between animate-in slide-in-from-top-2"
        data-tour="bulk-actions"
      >
        <div className="flex items-center gap-4">
          <span className="text-sm font-medium">
            {selectedCount} selected
          </span>
          <div className="flex gap-2 flex-wrap">
            {selectedScenarioData.slice(0, 3).map((s) => (
              <Badge key={s.id} variant="secondary" className="gap-1">
                {s.name}
                <X
                  className="h-3 w-3 cursor-pointer hover:text-destructive"
                  onClick={() => {
                    onClearSelection();
                  }}
                />
              </Badge>
            ))}
            {selectedCount > 3 && (
              <Badge variant="secondary">+{selectedCount - 3} more</Badge>
            )}
          </div>
        </div>

        <div className="flex items-center gap-2">
          <Button
            variant="ghost"
            size="sm"
            onClick={onClearSelection}
            aria-label="Clear selection"
          >
            <X className="h-4 w-4 mr-1" />
            Clear
          </Button>

          {canCompare && (
            <Button
              variant="secondary"
              size="sm"
              onClick={handleCompare}
              aria-label="Compare selected scenarios"
            >
              <BarChart3 className="mr-2 h-4 w-4" />
              Compare
            </Button>
          )}

          <DropdownMenu>
            <DropdownMenuTrigger>
              <Button variant="outline" size="sm">
                <MoreHorizontal className="h-4 w-4 mr-1" />
                Actions
              </Button>
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end">
              <DropdownMenuItem
                onClick={() => handleExport('json')}
                disabled={isExporting}
              >
                <FileText className="mr-2 h-4 w-4" />
                Export as JSON
              </DropdownMenuItem>
              <DropdownMenuItem
                onClick={() => handleExport('csv')}
                disabled={isExporting}
              >
                <FileSpreadsheet className="mr-2 h-4 w-4" />
                Export as CSV
              </DropdownMenuItem>
              <DropdownMenuItem
                className="text-destructive focus:text-destructive"
                onClick={() => setShowDeleteConfirm(true)}
              >
                <Trash2 className="mr-2 h-4 w-4" />
                Delete Selected
              </DropdownMenuItem>
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </div>

      {/* Delete Confirmation Dialog */}
      <Dialog open={showDeleteConfirm} onOpenChange={setShowDeleteConfirm}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>Delete Scenarios</DialogTitle>
            <DialogDescription>
              Are you sure you want to delete {selectedCount} scenario
              {selectedCount !== 1 ? 's' : ''}? This action cannot be undone.
            </DialogDescription>
          </DialogHeader>
          <div className="py-4">
            <p className="text-sm font-medium mb-2">Selected scenarios:</p>
            <ul className="space-y-1 max-h-32 overflow-y-auto">
              {selectedScenarioData.map((s) => (
                <li key={s.id} className="text-sm text-muted-foreground">
                  • {s.name}
                </li>
              ))}
            </ul>
          </div>
          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => setShowDeleteConfirm(false)}
              disabled={isDeleting}
            >
              Cancel
            </Button>
            <Button
              variant="destructive"
              onClick={handleDelete}
              disabled={isDeleting}
            >
              {isDeleting ? 'Deleting...' : 'Delete'}
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </>
  );
}

// Reusable selection checkbox for table rows
interface SelectableRowProps {
  id: string;
  isSelected: boolean;
  onToggle: (id: string) => void;
  name: string;
}

export function SelectableRow({ id, isSelected, onToggle, name }: SelectableRowProps) {
  return (
    <Checkbox
      checked={isSelected}
      onCheckedChange={() => onToggle(id)}
      onClick={(e: React.MouseEvent) => e.stopPropagation()}
      aria-label={`Select ${name}`}
    />
  );
}

// Select all checkbox with indeterminate state
interface SelectAllCheckboxProps {
  totalCount: number;
  selectedCount: number;
  onToggleAll: () => void;
}

export function SelectAllCheckbox({
  totalCount,
  selectedCount,
  onToggleAll,
}: SelectAllCheckboxProps) {
  const checked = selectedCount > 0 && selectedCount === totalCount;
  const indeterminate = selectedCount > 0 && selectedCount < totalCount;

  return (
    <Checkbox
      checked={checked}
      data-state={indeterminate ? 'indeterminate' : checked ? 'checked' : 'unchecked'}
      onCheckedChange={onToggleAll}
      aria-label={selectedCount > 0 ? 'Deselect all' : 'Select all'}
    />
  );
}
