/**
 * FloatingSelectionBar Component
 *
 * Fixed bottom action bar that appears when rows are selected.
 * Provides bulk actions: apply template, save as template, delete.
 *
 * PERFORMANCE CRITICAL:
 * - Only subscribes to selectedRows.size via useSelectedRowCount()
 * - Never subscribes to the full rows array or selectedRows Set
 * - Uses getState() for action-time data access
 */

import { memo, useCallback, useState } from 'react';
import { Button } from '@/components/ui/button';
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { X, Trash2, Save } from 'lucide-react';
import { useValidationStore } from '../store/validationStore';
import {
  useSelectedRowCount,
  useHasSingleRowSelected,
  useTemplates,
  useTemplatesLoading,
} from '../store/selectors';
import { useTemplateManagement } from '../hooks/useTemplateManagement';
import SearchableTemplateSelect from './SearchableTemplateSelect';
import { toast } from 'sonner';

/**
 * Floating selection bar - appears when rows are selected
 *
 * PERFORMANCE: Only subscribes to:
 * - selectedRowCount (number) - minimal subscription
 * - hasSingleRowSelected (boolean) - for save template button
 * - templates/templatesLoading - rarely changes
 */
export const FloatingSelectionBar = memo(() => {
  const selectedCount = useSelectedRowCount();
  const hasSingleRow = useHasSingleRowSelected();
  const templates = useTemplates();
  const templatesLoading = useTemplatesLoading();
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);

  const { applyTemplateToSelected, getTemplateDisplayText } = useTemplateManagement();

  // Clear selection - uses getState() to avoid subscription
  const handleClearSelection = useCallback(() => {
    useValidationStore.getState().clearSelection();
  }, []);

  // Delete selected rows - uses getState() at action time
  const handleDeleteSelected = useCallback(() => {
    const { rows, selectedRows, deleteRows } = useValidationStore.getState();

    // Map selected UUIDs to indices
    const indicesToDelete: number[] = [];
    rows.forEach((row, index) => {
      if (selectedRows.has(row.__index)) {
        indicesToDelete.push(index);
      }
    });

    if (indicesToDelete.length === 0) {
      toast.error('No rows selected');
      return;
    }

    // Show confirmation dialog for multiple rows
    if (indicesToDelete.length > 1) {
      setDeleteDialogOpen(true);
      return;
    }

    // For single row, delete directly
    deleteRows(indicesToDelete);
    toast.success('Row deleted');
  }, []);

  // Confirm deletion callback
  const handleConfirmDelete = useCallback(() => {
    const { rows, selectedRows, deleteRows } = useValidationStore.getState();

    const indicesToDelete: number[] = [];
    rows.forEach((row, index) => {
      if (selectedRows.has(row.__index)) {
        indicesToDelete.push(index);
      }
    });

    if (indicesToDelete.length > 0) {
      deleteRows(indicesToDelete);
      toast.success(`${indicesToDelete.length} rows deleted`);
    }
    setDeleteDialogOpen(false);
  }, []);

  // Save as template - opens dialog with row data
  const handleSaveAsTemplate = useCallback(() => {
    const { rows, selectedRows, openTemplateForm } = useValidationStore.getState();

    // Find the single selected row
    const selectedRow = rows.find((row) => selectedRows.has(row.__index));
    if (!selectedRow) {
      toast.error('No row selected');
      return;
    }

    // Prepare row data for template form (exclude metadata fields)
    const templateData: Record<string, unknown> = {};
    const excludeFields = [
      'id',
      '__index',
      '__meta',
      '__template',
      '__original',
      '__corrected',
      '__changes',
      '__aiSupplemental',
    ];

    for (const [key, value] of Object.entries(selectedRow)) {
      if (excludeFields.includes(key)) continue;
      templateData[key] = value;
    }

    openTemplateForm(templateData);
  }, []);

  // Handle template selection for bulk apply
  const handleTemplateChange = useCallback(
    (templateId: string) => {
      if (!templateId) return;
      applyTemplateToSelected(templateId);
    },
    [applyTemplateToSelected]
  );

  // Don't render if nothing selected
  if (selectedCount === 0) return null;

  return (
    <>
      <div className="fixed bottom-[12rem] md:bottom-20 left-1/2 -translate-x-1/2 z-50 animate-in fade-in slide-in-from-bottom-4 duration-200">
        <div className="bg-background border border-border rounded-xl shadow-xl px-4 py-3 flex items-center gap-4">
          {/* Selection count badge */}
          <div className="flex items-center gap-2">
            <div className="bg-primary text-primary-foreground text-sm font-medium px-2.5 py-1 rounded-md whitespace-nowrap">
              {selectedCount} selected
            </div>
            <Button
              variant="ghost"
              size="sm"
              onClick={handleClearSelection}
              className="h-8 w-8 p-0"
              title="Clear selection"
            >
              <X className="h-4 w-4" />
            </Button>
          </div>

          {/* Divider */}
          <div className="h-8 w-px bg-border" />

          {/* Apply template to selected */}
          <div className="flex items-center gap-2">
            <span className="text-sm text-muted-foreground whitespace-nowrap">Apply <span className="hidden md:inline">template:</span></span>
            <SearchableTemplateSelect
              templates={templates}
              value=""
              onValueChange={handleTemplateChange}
              getTemplateDisplayText={getTemplateDisplayText}
              placeholder="Select template"
              triggerClassName="w-[200px]"
              disabled={templatesLoading}
            />
          </div>

          {/* Divider */}
          <div className="h-8 w-px bg-border" />

          {/* Save as template - only when single row selected */}
          {hasSingleRow && (
            <>
              <Button
                variant="outline"
                size="sm"
                onClick={handleSaveAsTemplate}
                className="gap-2"
              >
                <Save className="h-4 w-4" />
                <span className="hidden md:inline">Save as Template</span>
              </Button>

              {/* Divider */}
              <div className="h-8 w-px bg-border" />
            </>
          )}

          {/* Delete selected */}
          <Button
            variant="destructive"
            size="sm"
            onClick={handleDeleteSelected}
            className="gap-2"
          >
            <Trash2 className="h-4 w-4" />
            <span className="hidden md:inline">Delete</span>
          </Button>
        </div>
      </div>

      {/* Delete confirmation dialog */}
      <AlertDialog open={deleteDialogOpen} onOpenChange={setDeleteDialogOpen}>
        <AlertDialogContent>
          <AlertDialogHeader>
            <AlertDialogTitle>Delete {selectedCount} rows?</AlertDialogTitle>
            <AlertDialogDescription>
              This action cannot be undone. This will permanently delete the selected rows from your import data.
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogCancel>Cancel</AlertDialogCancel>
            <AlertDialogAction
              onClick={handleConfirmDelete}
              className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
            >
              Delete
            </AlertDialogAction>
          </AlertDialogFooter>
        </AlertDialogContent>
      </AlertDialog>
    </>
  );
});

FloatingSelectionBar.displayName = 'FloatingSelectionBar';
