import React, { useState, useCallback, useMemo } from 'react';
import { Sparkles } from 'lucide-react';
import { WizardModal, WizardStep } from '../../ui/WizardModal/WizardModal';
import { ItemTypeSelector, ItemType } from './ItemTypeSelector';

// Import specific wizards
import { InventoryWizardSteps } from './wizards/InventoryWizard';
import { SupplierWizardSteps } from './wizards/SupplierWizard';
import { RecipeWizardSteps } from './wizards/RecipeWizard';
import { EquipmentWizardSteps } from './wizards/EquipmentWizard';
import { QualityTemplateWizardSteps } from './wizards/QualityTemplateWizard';
import { CustomerOrderWizardSteps } from './wizards/CustomerOrderWizard';
import { CustomerWizardSteps } from './wizards/CustomerWizard';
import { TeamMemberWizardSteps } from './wizards/TeamMemberWizard';
import { SalesEntryWizardSteps } from './wizards/SalesEntryWizard';

interface UnifiedAddWizardProps {
  isOpen: boolean;
  onClose: () => void;
  onComplete?: (itemType: ItemType, data?: any) => void;
  // Optional: Start with a specific item type (when opened from individual page buttons)
  initialItemType?: ItemType;
}

export const UnifiedAddWizard: React.FC<UnifiedAddWizardProps> = ({
  isOpen,
  onClose,
  onComplete,
  initialItemType,
}) => {
  const [selectedItemType, setSelectedItemType] = useState<ItemType | null>(
    initialItemType || null
  );
  const [wizardData, setWizardData] = useState<Record<string, any>>({});

  // Reset state when modal closes
  const handleClose = useCallback(() => {
    setSelectedItemType(initialItemType || null);
    setWizardData({});
    onClose();
  }, [onClose, initialItemType]);

  // Handle item type selection from step 0
  const handleItemTypeSelect = useCallback((itemType: ItemType) => {
    setSelectedItemType(itemType);
  }, []);

  // Handle wizard completion
  const handleWizardComplete = useCallback(
    (data?: any) => {
      if (selectedItemType) {
        onComplete?.(selectedItemType, data);
      }
      handleClose();
    },
    [selectedItemType, onComplete, handleClose]
  );

  // Get wizard steps based on selected item type
  // CRITICAL: Memoize the steps to prevent component recreation on every render
  // Without this, every keystroke causes the component to unmount/remount, losing focus
  // IMPORTANT: For dynamic wizards (like sales-entry), we need to include the entryMethod
  // in the dependency array so steps update when the user selects manual vs upload
  const wizardSteps = useMemo((): WizardStep[] => {
    if (!selectedItemType) {
      // Step 0: Item Type Selection
      return [
        {
          id: 'item-type-selection',
          title: 'Seleccionar tipo',
          description: 'Elige qué deseas agregar',
          component: () => (
            <ItemTypeSelector onSelect={handleItemTypeSelect} />
          ),
        },
      ];
    }

    // Return specific wizard steps based on selected type
    switch (selectedItemType) {
      case 'inventory':
        return InventoryWizardSteps(wizardData, setWizardData);
      case 'supplier':
        return SupplierWizardSteps(wizardData, setWizardData);
      case 'recipe':
        return RecipeWizardSteps(wizardData, setWizardData);
      case 'equipment':
        return EquipmentWizardSteps(wizardData, setWizardData);
      case 'quality-template':
        return QualityTemplateWizardSteps(wizardData, setWizardData);
      case 'customer-order':
        return CustomerOrderWizardSteps(wizardData, setWizardData);
      case 'customer':
        return CustomerWizardSteps(wizardData, setWizardData);
      case 'team-member':
        return TeamMemberWizardSteps(wizardData, setWizardData);
      case 'sales-entry':
        return SalesEntryWizardSteps(wizardData, setWizardData);
      default:
        return [];
    }
  }, [selectedItemType, handleItemTypeSelect, wizardData.entryMethod]); // Include only critical fields for dynamic step generation

  // Get wizard title based on selected item type
  const getWizardTitle = (): string => {
    if (!selectedItemType) {
      return 'Agregar Contenido';
    }

    const titleMap: Record<ItemType, string> = {
      'inventory': 'Agregar Inventario',
      'supplier': 'Agregar Proveedor',
      'recipe': 'Agregar Receta',
      'equipment': 'Agregar Equipo',
      'quality-template': 'Agregar Plantilla de Calidad',
      'customer-order': 'Agregar Pedido',
      'customer': 'Agregar Cliente',
      'team-member': 'Agregar Miembro del Equipo',
      'sales-entry': 'Registrar Ventas',
    };

    return titleMap[selectedItemType] || 'Agregar Contenido';
  };

  return (
    <WizardModal
      isOpen={isOpen}
      onClose={handleClose}
      onComplete={handleWizardComplete}
      title={getWizardTitle()}
      steps={wizardSteps}
      icon={<Sparkles className="w-6 h-6" />}
      size="xl"
    />
  );
};

export default UnifiedAddWizard;
