import React, { useState, useMemo } from 'react';
import { Plus, Star, Clock, Euro, Package, Eye, ChefHat, Timer, CheckCircle, Trash2, Settings, FileText } from 'lucide-react';
import { StatsGrid, StatusCard, getStatusColor, EditViewModal, SearchAndFilter, type FilterConfig, EmptyState, type EditViewModalSection } from '../../../../components/ui';
import { QualityPromptDialog } from '../../../../components/ui/QualityPromptDialog';
import { formatters } from '../../../../components/ui/Stats/StatsPresets';
import { PageHeader } from '../../../../components/layout';
import { useRecipes, useCreateRecipe, useUpdateRecipe, useDeleteRecipe, useArchiveRecipe } from '../../../../api/hooks/recipes';
import { recipesService } from '../../../../api/services/recipes';
import { useCurrentTenant } from '../../../../stores/tenant.store';
import { useTenantCurrency } from '../../../../hooks/useTenantCurrency';
import type { RecipeResponse, RecipeCreate } from '../../../../api/types/recipes';
import { MeasurementUnit } from '../../../../api/types/recipes';
import { useIngredients } from '../../../../api/hooks/inventory';
import { ProcessStage, type RecipeQualityConfiguration } from '../../../../api/types/qualityTemplates';
import { CreateRecipeModal, DeleteRecipeModal, RecipeViewEditModal } from '../../../../components/domain/recipes';
import { QualityCheckConfigurationModal } from '../../../../components/domain/recipes/QualityCheckConfigurationModal';
import { useQueryClient } from '@tanstack/react-query';
import type { RecipeIngredientResponse } from '../../../../api/types/recipes';

// Ingredients Edit Component for EditViewModal
const IngredientsEditComponent: React.FC<{
  value: RecipeIngredientResponse[];
  onChange: (value: RecipeIngredientResponse[]) => void;
  availableIngredients: Array<{value: string; label: string}>;
  unitOptions: Array<{value: MeasurementUnit; label: string}>;
}> = ({ value, onChange, availableIngredients, unitOptions }) => {
  const ingredientsArray = Array.isArray(value) ? value : [];

  const addIngredient = () => {
    const newIngredient: Partial<RecipeIngredientResponse> = {
      id: `temp-${Date.now()}`, // Temporary ID for new ingredients
      ingredient_id: '',
      quantity: 1,
      unit: MeasurementUnit.GRAMS,
      ingredient_order: ingredientsArray.length + 1,
      is_optional: false
    };
    onChange([...ingredientsArray, newIngredient as RecipeIngredientResponse]);
  };

  const removeIngredient = (index: number) => {
    onChange(ingredientsArray.filter((_, i) => i !== index));
  };

  const updateIngredient = (index: number, field: keyof RecipeIngredientResponse, newValue: any) => {
    const updated = ingredientsArray.map((ingredient, i) =>
      i === index ? { ...ingredient, [field]: newValue } : ingredient
    );
    onChange(updated);
  };

  const [expandedIngredients, setExpandedIngredients] = React.useState<Record<number, boolean>>({});

  const toggleExpanded = (index: number) => {
    setExpandedIngredients(prev => ({
      ...prev,
      [index]: !prev[index]
    }));
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h4 className="text-sm font-medium text-[var(--text-primary)]">Lista de Ingredientes</h4>
        <button
          type="button"
          onClick={addIngredient}
          className="flex items-center gap-2 px-3 py-1.5 text-sm bg-[var(--color-primary)] text-white rounded-md hover:bg-[var(--color-primary)]/90 transition-colors"
        >
          <Plus className="w-4 h-4" />
          Agregar Ingrediente
        </button>
      </div>

      <div className="space-y-3 max-h-[600px] overflow-y-auto pr-2">
        {ingredientsArray.length === 0 ? (
          <div className="text-center py-8 text-[var(--text-secondary)] bg-[var(--bg-secondary)]/30 rounded-lg border-2 border-dashed border-[var(--border-secondary)]">
            <Package className="w-12 h-12 mx-auto mb-2 opacity-50" />
            <p className="text-sm">No hay ingredientes. Haz clic en "Agregar Ingrediente" para comenzar.</p>
          </div>
        ) : (
          ingredientsArray.map((ingredient, index) => {
            const isExpanded = expandedIngredients[index];

            return (
              <div key={ingredient.id || index} className="p-4 border-2 border-[var(--border-secondary)] rounded-lg bg-[var(--bg-secondary)]/50 hover:border-[var(--color-primary)]/30 transition-all space-y-3">
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <div className="w-7 h-7 rounded-full bg-[var(--color-primary)]/10 flex items-center justify-center text-sm font-semibold text-[var(--color-primary)]">
                      {index + 1}
                    </div>
                    <span className="text-sm font-medium text-[var(--text-primary)]">
                      {availableIngredients.find(i => i.value === ingredient.ingredient_id)?.label || 'Ingrediente sin seleccionar'}
                    </span>
                    {ingredient.is_optional && (
                      <span className="text-xs px-2 py-0.5 rounded-full bg-amber-500/10 text-amber-700 dark:text-amber-400 border border-amber-500/20">
                        opcional
                      </span>
                    )}
                  </div>
                  <button
                    type="button"
                    onClick={() => removeIngredient(index)}
                    className="p-1.5 text-red-500 hover:text-red-700 hover:bg-red-50 dark:hover:bg-red-950 rounded transition-colors"
                    title="Eliminar ingrediente"
                  >
                    <Trash2 className="w-4 h-4" />
                  </button>
                </div>

                {/* Main fields */}
                <div className="grid grid-cols-1 sm:grid-cols-4 gap-3">
                  <div className="sm:col-span-2">
                    <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">Ingrediente *</label>
                    <select
                      value={ingredient.ingredient_id}
                      onChange={(e) => updateIngredient(index, 'ingredient_id', e.target.value)}
                      className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)] text-sm"
                    >
                      <option value="">Seleccionar ingrediente...</option>
                      {availableIngredients.map(ing => (
                        <option key={ing.value} value={ing.value}>{ing.label}</option>
                      ))}
                    </select>
                  </div>

                  <div>
                    <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">Cantidad *</label>
                    <input
                      type="number"
                      value={ingredient.quantity}
                      onChange={(e) => updateIngredient(index, 'quantity', parseFloat(e.target.value) || 0)}
                      className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)] text-sm"
                      min="0"
                      step="0.1"
                      placeholder="0"
                    />
                  </div>

                  <div>
                    <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">Unidad *</label>
                    <select
                      value={ingredient.unit}
                      onChange={(e) => updateIngredient(index, 'unit', e.target.value as MeasurementUnit)}
                      className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)] text-sm"
                    >
                      {unitOptions.map(unit => (
                        <option key={unit.value} value={unit.value}>{unit.label}</option>
                      ))}
                    </select>
                  </div>
                </div>

                {/* Optional checkbox and expand button */}
                <div className="flex items-center justify-between pt-2 border-t border-[var(--border-secondary)]">
                  <label className="flex items-center gap-2 text-xs font-medium text-[var(--text-secondary)] cursor-pointer">
                    <input
                      type="checkbox"
                      checked={ingredient.is_optional}
                      onChange={(e) => updateIngredient(index, 'is_optional', e.target.checked)}
                      className="rounded border-[var(--border-secondary)] text-[var(--color-primary)] focus:ring-[var(--color-primary)]"
                    />
                    Ingrediente opcional
                  </label>

                  <button
                    type="button"
                    onClick={() => toggleExpanded(index)}
                    className="flex items-center gap-1 text-xs text-[var(--color-primary)] hover:text-[var(--color-primary)]/80 transition-colors"
                  >
                    {isExpanded ? 'Ocultar detalles' : 'Agregar detalles'}
                    <svg
                      className={`w-4 h-4 transition-transform ${isExpanded ? 'rotate-180' : ''}`}
                      fill="none"
                      viewBox="0 0 24 24"
                      stroke="currentColor"
                    >
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                    </svg>
                  </button>
                </div>

                {/* Expanded details section */}
                {isExpanded && (
                  <div className="space-y-3 pt-3 border-t border-[var(--border-secondary)] bg-[var(--bg-primary)]/50 -mx-4 -mb-3 px-4 pb-3 rounded-b-lg">
                    <div>
                      <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">
                        Método de preparación
                      </label>
                      <input
                        type="text"
                        value={ingredient.preparation_method || ''}
                        onChange={(e) => updateIngredient(index, 'preparation_method', e.target.value)}
                        className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)] text-sm"
                        placeholder="ej: tamizada, a temperatura ambiente, derretida..."
                      />
                    </div>

                    <div>
                      <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">
                        Notas del ingrediente
                      </label>
                      <textarea
                        value={ingredient.ingredient_notes || ''}
                        onChange={(e) => updateIngredient(index, 'ingredient_notes', e.target.value)}
                        className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)] text-sm"
                        placeholder="Notas adicionales sobre este ingrediente..."
                        rows={2}
                      />
                    </div>

                    <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                      <div>
                        <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">
                          Opciones de sustitución
                        </label>
                        <input
                          type="text"
                          value={typeof ingredient.substitution_options === 'string' ? ingredient.substitution_options : ''}
                          onChange={(e) => updateIngredient(index, 'substitution_options', e.target.value)}
                          className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)] text-sm"
                          placeholder="ej: Aceite de oliva, mantequilla..."
                        />
                      </div>

                      <div>
                        <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">
                          Ratio de sustitución
                        </label>
                        <input
                          type="text"
                          value={typeof ingredient.substitution_ratio === 'string' ? ingredient.substitution_ratio : (typeof ingredient.substitution_ratio === 'number' ? String(ingredient.substitution_ratio) : '')}
                          onChange={(e) => updateIngredient(index, 'substitution_ratio', e.target.value)}
                          className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-md focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)] text-sm"
                          placeholder="ej: 1:1, 1:1.2..."
                        />
                      </div>
                    </div>
                  </div>
                )}
              </div>
            );
          })
        )}
      </div>

      {ingredientsArray.length > 0 && (
        <div className="pt-3 border-t border-[var(--border-secondary)]">
          <p className="text-xs text-[var(--text-secondary)]">
            Total: {ingredientsArray.length} ingrediente{ingredientsArray.length !== 1 ? 's' : ''}
          </p>
        </div>
      )}
    </div>
  );
};

const RecipesPage: React.FC = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const [categoryFilter, setCategoryFilter] = useState('');
  const [difficultyFilter, setDifficultyFilter] = useState('');
  const [isSignatureOnly, setIsSignatureOnly] = useState(false);
  const [showForm, setShowForm] = useState(false);
  const [modalMode, setModalMode] = useState<'view' | 'edit'>('view');
  const [selectedRecipe, setSelectedRecipe] = useState<RecipeResponse | null>(null);
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [showQualityConfigModal, setShowQualityConfigModal] = useState(false);
  const [showQualityPrompt, setShowQualityPrompt] = useState(false);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [recipeToDelete, setRecipeToDelete] = useState<RecipeResponse | null>(null);
  const [newlyCreatedRecipe, setNewlyCreatedRecipe] = useState<RecipeResponse | null>(null);
  const [editedRecipe, setEditedRecipe] = useState<Partial<RecipeResponse>>({});
  const [editedIngredients, setEditedIngredients] = useState<RecipeIngredientResponse[]>([]);

  const currentTenant = useCurrentTenant();
  const tenantId = currentTenant?.id || '';
  const { currencySymbol } = useTenantCurrency();
  const queryClient = useQueryClient();

  // Mutations
  const createRecipeMutation = useCreateRecipe(tenantId);
  const updateRecipeMutation = useUpdateRecipe(tenantId);
  const deleteRecipeMutation = useDeleteRecipe(tenantId);
  const archiveRecipeMutation = useArchiveRecipe(tenantId);

  // API Data
  const {
    data: recipes = [],
    isRefetching: isRefetchingRecipes
  } = useRecipes(tenantId, { search_term: searchTerm || undefined });

  // Fetch inventory items for ingredient name lookup
  const {
    data: inventoryItems = []
  } = useIngredients(tenantId, {});

  // Create ingredient lookup map (UUID -> name)
  const ingredientLookup = useMemo(() => {
    const map: Record<string, string> = {};
    inventoryItems.forEach(item => {
      map[item.id] = item.name;
    });
    return map;
  }, [inventoryItems]);

  // Available ingredients for editing
  const availableIngredients = useMemo(() =>
    (inventoryItems || [])
      .filter(item => item.product_type !== 'finished_product')
      .map(ingredient => ({
        value: ingredient.id,
        label: `${ingredient.name} (${ingredient.category || 'Sin categoría'})`
      })),
    [inventoryItems]
  );

  // Unit options for ingredients
  const unitOptions = useMemo(() => [
    { value: MeasurementUnit.GRAMS, label: 'g' },
    { value: MeasurementUnit.KILOGRAMS, label: 'kg' },
    { value: MeasurementUnit.MILLILITERS, label: 'ml' },
    { value: MeasurementUnit.LITERS, label: 'L' },
    { value: MeasurementUnit.UNITS, label: 'unidades' },
    { value: MeasurementUnit.TABLESPOONS, label: 'cucharadas' },
    { value: MeasurementUnit.TEASPOONS, label: 'cucharaditas' },
  ], []);

  const getRecipeStatusConfig = (recipe: RecipeResponse) => {
    const category = recipe.category || 'other';
    const difficulty = recipe.difficulty_level || 1;
    const isSignature = recipe.is_signature_item;
    const categoryConfig = {
      bread: { text: 'Pan', icon: ChefHat },
      pastry: { text: 'Bollería', icon: ChefHat },
      cake: { text: 'Tarta', icon: ChefHat },
      cookie: { text: 'Galleta', icon: ChefHat },
      other: { text: 'Otro', icon: ChefHat },
    };

    const difficultyConfig = {
      1: { icon: '●', label: 'Fácil' },
      2: { icon: '●●', label: 'Medio' },
      3: { icon: '●●●', label: 'Difícil' },
    };

    const categoryInfo = categoryConfig[category as keyof typeof categoryConfig] || categoryConfig.other;
    const difficultyInfo = difficultyConfig[Math.min(difficulty, 3) as keyof typeof difficultyConfig] || difficultyConfig[1];
    
    return {
      color: getStatusColor(category),
      text: categoryInfo.text,
      icon: categoryInfo.icon,
      difficultyIcon: difficultyInfo.icon,
      difficultyLabel: difficultyInfo.label,
      isCritical: false,
      isHighlight: isSignature
    };
  };

  const formatTime = (minutes: number) => {
    const hours = Math.floor(minutes / 60);
    const mins = minutes % 60;
    return hours > 0 ? `${hours}h ${mins}m` : `${mins}m`;
  };

  // Helper to translate category values to labels
  const getCategoryLabel = (category: string | null | undefined): string => {
    if (!category) return 'Sin categoría';
    const categoryLabels: Record<string, string> = {
      'bread': 'Panes',
      'pastry': 'Bollería',
      'cake': 'Tartas',
      'cookie': 'Galletas',
      'other': 'Otro'
    };
    return categoryLabels[category] || category;
  };

  const getQualityConfigSummary = (config: any) => {
    if (!config || !config.stages) return 'No configurado';

    const stageLabels: Record<string, string> = {
      [ProcessStage.MIXING]: 'Mezclado',
      [ProcessStage.PROOFING]: 'Fermentación',
      [ProcessStage.SHAPING]: 'Formado',
      [ProcessStage.BAKING]: 'Horneado',
      [ProcessStage.COOLING]: 'Enfriado',
      [ProcessStage.PACKAGING]: 'Empaquetado',
      [ProcessStage.FINISHING]: 'Acabado'
    };

    const configuredStages = Object.keys(config.stages)
      .filter(stage => config.stages[stage]?.template_ids?.length > 0)
      .map(stage => stageLabels[stage] || stage);

    if (configuredStages.length === 0) return 'No configurado';
    if (configuredStages.length <= 2) return `Configurado para: ${configuredStages.join(', ')}`;

    return `Configurado para ${configuredStages.length} etapas`;
  };

  const getQualityIndicator = (recipe: RecipeResponse) => {
    if (!recipe.quality_check_configuration || !recipe.quality_check_configuration.stages) {
      return '❌ Sin configurar';
    }

    const stages = recipe.quality_check_configuration.stages;
    const configuredStages = Object.keys(stages).filter(
      stage => stages[stage]?.template_ids?.length > 0
    );

    const totalTemplates = Object.values(stages).reduce(
      (sum, stage) => sum + (stage?.template_ids?.length || 0),
      0
    );

    if (configuredStages.length === 0) {
      return '❌ Sin configurar';
    }

    const totalStages = Object.keys(ProcessStage).length;
    if (configuredStages.length < totalStages / 2) {
      return `⚠️ Parcial (${configuredStages.length}/${totalStages} etapas)`;
    }

    return `✅ Configurado (${totalTemplates} controles)`;
  };

  const filteredRecipes = useMemo(() => {
    let filtered = recipes;

    // Apply search filter
    if (searchTerm) {
      const searchLower = searchTerm.toLowerCase();
      filtered = filtered.filter(recipe =>
        recipe.name.toLowerCase().includes(searchLower) ||
        (recipe.description && recipe.description.toLowerCase().includes(searchLower)) ||
        (recipe.category && recipe.category.toLowerCase().includes(searchLower))
      );
    }

    // Apply category filter
    if (categoryFilter) {
      filtered = filtered.filter(recipe => recipe.category === categoryFilter);
    }

    // Apply difficulty filter
    if (difficultyFilter) {
      filtered = filtered.filter(recipe => recipe.difficulty_level?.toString() === difficultyFilter);
    }

    // Apply signature filter
    if (isSignatureOnly) {
      filtered = filtered.filter(recipe => recipe.is_signature_item);
    }

    return filtered;
  }, [recipes, searchTerm, categoryFilter, difficultyFilter, isSignatureOnly]);

  const recipeStats = useMemo(() => {
    const stats = {
      totalRecipes: recipes.length,
      signatureRecipes: recipes.filter(r => r.is_signature_item).length,
      easyRecipes: recipes.filter(r => r.difficulty_level === 1).length,
      averageCost: recipes.length > 0 ? recipes.reduce((sum, r) => sum + (r.estimated_cost_per_unit || 0), 0) / recipes.length : 0,
      averageProfit: 0, // Will be calculated based on suggested selling price - cost
      categories: [...new Set(recipes.map(r => r.category).filter(Boolean))].length,
    };

    // Calculate average profit
    stats.averageProfit = recipes.length > 0 ?
      recipes.reduce((sum, r) => {
        const cost = r.estimated_cost_per_unit || 0;
        const price = r.suggested_selling_price || 0;
        return sum + (price - cost);
      }, 0) / recipes.length : 0;

    return stats;
  }, [recipes]);

  const stats = [
    {
      title: 'Total Recetas',
      value: recipeStats.totalRecipes,
      variant: 'default' as const,
      icon: ChefHat,
    },
    {
      title: 'Especiales',
      value: recipeStats.signatureRecipes,
      variant: 'warning' as const,
      icon: Star,
    },
    {
      title: 'Fáciles',
      value: recipeStats.easyRecipes,
      variant: 'success' as const,
      icon: Timer,
    },
    {
      title: 'Costo Promedio',
      value: formatters.currency(recipeStats.averageCost),
      variant: 'info' as const,
      icon: Euro,
    },
    {
      title: 'Margen Promedio',
      value: formatters.currency(recipeStats.averageProfit),
      variant: 'success' as const,
      icon: Euro,
    },
    {
      title: 'Categorías',
      value: recipeStats.categories,
      variant: 'info' as const,
      icon: Package,
    },
  ];

  // Handle opening a recipe (fetch full details with ingredients)
  const handleOpenRecipe = async (recipeId: string) => {
    try {
      // Fetch full recipe details including ingredients
      const fullRecipe = await recipesService.getRecipe(tenantId, recipeId);
      setSelectedRecipe(fullRecipe);
      setModalMode('view');
      setShowForm(true);
    } catch (error) {
      console.error('Error fetching recipe details:', error);
    }
  };

  // Handle creating a new recipe
  const handleCreateRecipe = async (recipeData: RecipeCreate) => {
    try {
      const newRecipe = await createRecipeMutation.mutateAsync(recipeData);
      setShowCreateModal(false);

      // Fetch full recipe details and show quality prompt
      const fullRecipe = await recipesService.getRecipe(tenantId, newRecipe.id);
      setNewlyCreatedRecipe(fullRecipe);
      setShowQualityPrompt(true);

      console.log('Recipe created successfully');
    } catch (error) {
      console.error('Error creating recipe:', error);
      throw error;
    }
  };

  // Handle quality prompt - configure now
  const handleConfigureQualityNow = async () => {
    setShowQualityPrompt(false);
    if (newlyCreatedRecipe) {
      setSelectedRecipe(newlyCreatedRecipe);
      setModalMode('edit');
      setShowQualityConfigModal(true);
      setShowForm(true);
    }
  };

  // Handle quality prompt - configure later
  const handleConfigureQualityLater = () => {
    setShowQualityPrompt(false);
    setNewlyCreatedRecipe(null);
  };

  // Handle field changes in edit mode
  const handleFieldChange = (sectionIndex: number, fieldIndex: number, value: string | number | boolean) => {
    if (!selectedRecipe) return;

    const fieldMap: Record<string, string> = {
      // Información Básica
      'Nombre': 'name',
      'Código de receta': 'recipe_code',
      'Versión': 'version',
      'Descripción': 'description',
      'Categoría': 'category',
      'Producto terminado': 'finished_product_id',
      'Tipo de cocina': 'cuisine_type',
      'Dificultad': 'difficulty_level',
      'Estado': 'status',
      'Rendimiento': 'yield_quantity',
      'Unidad de rendimiento': 'yield_unit',
      'Porciones': 'serves_count',
      // Tiempos
      'Tiempo de preparación': 'prep_time_minutes',
      'Tiempo de cocción': 'cook_time_minutes',
      'Tiempo de reposo': 'rest_time_minutes',
      // Configuración Especial
      'Receta estacional': 'is_seasonal',
      'Mes de inicio': 'season_start_month',
      'Mes de fin': 'season_end_month',
      'Receta estrella': 'is_signature_item',
      // Configuración de Producción
      'Multiplicador de lote': 'batch_size_multiplier',
      'Tamaño mínimo de lote': 'minimum_batch_size',
      'Tamaño máximo de lote': 'maximum_batch_size',
      'Temperatura óptima': 'optimal_production_temperature',
      'Humedad óptima': 'optimal_humidity',
      // Análisis Financiero
      'Costo estimado por unidad': 'estimated_cost_per_unit',
      'Precio de venta sugerido': 'suggested_selling_price',
      'Margen objetivo': 'target_margin_percentage',
      // Instrucciones y Calidad
      'Notas de preparación': 'preparation_notes',
      'Instrucciones de almacenamiento': 'storage_instructions',
      'Estándares de calidad': 'quality_standards',
      'Instrucciones de preparación': 'instructions',
      'Puntos de control de calidad': 'quality_check_points',
      'Problemas comunes y soluciones': 'common_issues',
      // Información Nutricional
      'Información de alérgenos': 'allergen_info',
      'Etiquetas dietéticas': 'dietary_tags',
      'Información nutricional': 'nutritional_info'
    };

    const sections = getModalSections();
    const field = sections[sectionIndex]?.fields[fieldIndex];
    const fieldKey = fieldMap[field?.label || ''];

    if (fieldKey) {
      setEditedRecipe(prev => ({
        ...prev,
        [fieldKey]: value
      }));
    }
  };

  // Refetch callback for wait-for-refetch pattern
  const handleRecipeSaveComplete = async () => {
    if (!tenantId) return;
    // Invalidate recipes query to trigger refetch
    await queryClient.invalidateQueries({ queryKey: ['recipes', tenantId] });
  };

  // Handle saving edited recipe
  const handleSaveRecipe = async () => {
    if (!selectedRecipe || (!Object.keys(editedRecipe).length && editedIngredients.length === 0)) return;

    try {
      const updateData: any = {
        ...editedRecipe,
        // Convert time fields from formatted strings back to numbers if needed
        prep_time_minutes: editedRecipe.prep_time_minutes !== undefined
          ? (typeof editedRecipe.prep_time_minutes === 'string'
            ? parseInt(String(editedRecipe.prep_time_minutes))
            : editedRecipe.prep_time_minutes)
          : undefined,
        cook_time_minutes: editedRecipe.cook_time_minutes !== undefined
          ? (typeof editedRecipe.cook_time_minutes === 'string'
            ? parseInt(String(editedRecipe.cook_time_minutes))
            : editedRecipe.cook_time_minutes)
          : undefined,
        // Ensure yield_unit is properly typed
        yield_unit: editedRecipe.yield_unit ? editedRecipe.yield_unit as MeasurementUnit : undefined,
        // Convert difficulty level to number if needed
        difficulty_level: editedRecipe.difficulty_level !== undefined
          ? (typeof editedRecipe.difficulty_level === 'string'
            ? parseInt(String(editedRecipe.difficulty_level))
            : editedRecipe.difficulty_level)
          : undefined,
      };

      // Include ingredient updates if they were edited
      if (editedIngredients.length > 0) {
        updateData.ingredients = editedIngredients.map((ing, index) => ({
          ingredient_id: ing.ingredient_id,
          quantity: ing.quantity,
          unit: ing.unit,
          alternative_quantity: ing.alternative_quantity || null,
          alternative_unit: ing.alternative_unit || null,
          preparation_method: ing.preparation_method || null,
          ingredient_notes: ing.ingredient_notes || null,
          is_optional: ing.is_optional || false,
          ingredient_order: index + 1, // Maintain order based on array position
          ingredient_group: ing.ingredient_group || null,
          substitution_options: ing.substitution_options || null,
          substitution_ratio: ing.substitution_ratio || null,
        }));
      }

      await updateRecipeMutation.mutateAsync({
        id: selectedRecipe.id,
        data: updateData
      });

      // Note: Don't manually switch mode here - EditViewModal will handle it
      // after refetch completes if waitForRefetch is enabled
      setEditedRecipe({});
      setEditedIngredients([]);
      console.log('Recipe updated successfully');
    } catch (error) {
      console.error('Error updating recipe:', error);
    }
  };

  // Handle saving quality configuration
  const handleSaveQualityConfiguration = async (config: RecipeQualityConfiguration) => {
    if (!selectedRecipe) return;

    try {
      await updateRecipeMutation.mutateAsync({
        id: selectedRecipe.id,
        data: {
          quality_check_configuration: config
        }
      });

      // Update local state
      setSelectedRecipe({
        ...selectedRecipe,
        quality_check_configuration: config
      });

      console.log('Quality configuration updated successfully');
    } catch (error) {
      console.error('Error updating quality configuration:', error);
      throw error;
    }
  };

  // Handle soft delete (archive)
  const handleSoftDelete = async (recipeId: string) => {
    try {
      await archiveRecipeMutation.mutateAsync(recipeId);
      console.log('Recipe archived successfully');
    } catch (error) {
      console.error('Error archiving recipe:', error);
      throw error;
    }
  };

  // Handle hard delete (permanent)
  const handleHardDelete = async (recipeId: string) => {
    try {
      await deleteRecipeMutation.mutateAsync(recipeId);
      console.log('Recipe deleted successfully');
    } catch (error) {
      console.error('Error deleting recipe:', error);
      throw error;
    }
  };

  // Get current value for field (edited value or original)
  const getFieldValue = (originalValue: any, fieldKey: string) => {
    return editedRecipe[fieldKey as keyof RecipeResponse] !== undefined
      ? editedRecipe[fieldKey as keyof RecipeResponse]
      : originalValue;
  };

  // Helper to display JSON fields in a readable format
  const formatJsonField = (jsonData: any): string => {
    if (!jsonData) return 'No especificado';
    if (typeof jsonData === 'string') return jsonData;

    // Handle arrays
    if (Array.isArray(jsonData)) {
      // Check if it's an array of objects with step/description pattern
      if (jsonData.length > 0 && typeof jsonData[0] === 'object') {
        return jsonData.map((item, index) => {
          if (item.step && item.description) {
            return `${index + 1}. ${item.step}: ${item.description}`;
          } else if (item.description) {
            return `${index + 1}. ${item.description}`;
          } else if (item.step) {
            return `${index + 1}. ${item.step}`;
          }
          return `${index + 1}. ${JSON.stringify(item)}`;
        }).join('\n');
      }
      // Simple array of strings
      return jsonData.join(', ');
    }

    if (typeof jsonData === 'object') {
      // Extract common patterns
      if (jsonData.steps) return jsonData.steps;
      if (jsonData.checkpoints) return jsonData.checkpoints;
      if (jsonData.issues) return jsonData.issues;
      if (jsonData.allergens) return Array.isArray(jsonData.allergens) ? jsonData.allergens.join(', ') : jsonData.allergens;
      if (jsonData.tags) return Array.isArray(jsonData.tags) ? jsonData.tags.join(', ') : jsonData.tags;
      if (jsonData.info) return jsonData.info;
      return JSON.stringify(jsonData, null, 2);
    }
    return String(jsonData);
  };

  // Get modal sections with editable fields
  const getModalSections = (): EditViewModalSection[] => {
    if (!selectedRecipe) return [];

    return [
      {
        title: 'Información Básica',
        icon: ChefHat,
        fields: [
          {
            label: 'Nombre',
            value: getFieldValue(selectedRecipe.name, 'name'),
            type: modalMode === 'edit' ? 'text' : 'text',
            editable: modalMode === 'edit',
            span: 2
          },
          {
            label: 'Código de receta',
            value: getFieldValue(selectedRecipe.recipe_code || 'Sin código', 'recipe_code'),
            type: modalMode === 'edit' ? 'text' : 'text',
            editable: modalMode === 'edit'
          },
          {
            label: 'Versión',
            value: getFieldValue(selectedRecipe.version, 'version'),
            type: modalMode === 'edit' ? 'text' : 'text',
            editable: modalMode === 'edit'
          },
          {
            label: 'Descripción',
            value: getFieldValue(selectedRecipe.description || 'Sin descripción', 'description'),
            type: modalMode === 'edit' ? 'textarea' : 'text',
            editable: modalMode === 'edit',
            span: 2
          },
          {
            label: 'Categoría',
            value: modalMode === 'edit'
              ? getFieldValue(selectedRecipe.category, 'category')
              : getCategoryLabel(getFieldValue(selectedRecipe.category, 'category') as string),
            type: modalMode === 'edit' ? 'select' : 'status',
            options: modalMode === 'edit' ? [
              { value: 'bread', label: 'Panes' },
              { value: 'pastry', label: 'Bollería' },
              { value: 'cake', label: 'Tartas' },
              { value: 'cookie', label: 'Galletas' },
              { value: 'other', label: 'Otro' }
            ] : undefined,
            editable: true
          },
          {
            label: 'Tipo de cocina',
            value: getFieldValue(selectedRecipe.cuisine_type || 'No especificado', 'cuisine_type'),
            type: modalMode === 'edit' ? 'text' : 'text',
            editable: modalMode === 'edit'
          },
          {
            label: 'Dificultad',
            value: modalMode === 'edit'
              ? getFieldValue(selectedRecipe.difficulty_level, 'difficulty_level')
              : `Nivel ${getFieldValue(selectedRecipe.difficulty_level, 'difficulty_level')}`,
            type: modalMode === 'edit' ? 'select' : 'text',
            options: modalMode === 'edit' ? [
              { value: 1, label: '1 - Fácil' },
              { value: 2, label: '2 - Medio' },
              { value: 3, label: '3 - Difícil' },
              { value: 4, label: '4 - Muy Difícil' },
              { value: 5, label: '5 - Extremo' }
            ] : undefined,
            editable: true
          },
          {
            label: 'Estado',
            value: getFieldValue(selectedRecipe.status, 'status'),
            type: modalMode === 'edit' ? 'select' : 'text',
            options: modalMode === 'edit' ? [
              { value: 'draft', label: 'Borrador' },
              { value: 'active', label: 'Activo' },
              { value: 'testing', label: 'Testing' },
              { value: 'archived', label: 'Archivado' },
              { value: 'discontinued', label: 'Discontinuado' }
            ] : undefined,
            highlight: selectedRecipe.status === 'active',
            editable: true
          },
          {
            label: 'Rendimiento',
            value: getFieldValue(selectedRecipe.yield_quantity, 'yield_quantity'),
            type: modalMode === 'edit' ? 'number' : 'text',
            editable: modalMode === 'edit'
          },
          {
            label: 'Unidad de rendimiento',
            value: getFieldValue(selectedRecipe.yield_unit, 'yield_unit'),
            type: modalMode === 'edit' ? 'text' : 'text',
            editable: modalMode === 'edit'
          },
          {
            label: 'Porciones',
            value: getFieldValue(selectedRecipe.serves_count || 1, 'serves_count'),
            type: modalMode === 'edit' ? 'number' : 'text',
            editable: modalMode === 'edit'
          }
        ]
      },
      {
        title: 'Tiempos',
        icon: Clock,
        fields: [
          {
            label: 'Tiempo de preparación',
            value: modalMode === 'edit'
              ? getFieldValue(selectedRecipe.prep_time_minutes || 0, 'prep_time_minutes')
              : formatTime(getFieldValue(selectedRecipe.prep_time_minutes || 0, 'prep_time_minutes')),
            type: modalMode === 'edit' ? 'number' : 'text',
            placeholder: modalMode === 'edit' ? 'minutos' : undefined,
            editable: modalMode === 'edit'
          },
          {
            label: 'Tiempo de cocción',
            value: modalMode === 'edit'
              ? getFieldValue(selectedRecipe.cook_time_minutes || 0, 'cook_time_minutes')
              : formatTime(getFieldValue(selectedRecipe.cook_time_minutes || 0, 'cook_time_minutes')),
            type: modalMode === 'edit' ? 'number' : 'text',
            placeholder: modalMode === 'edit' ? 'minutos' : undefined,
            editable: modalMode === 'edit'
          },
          {
            label: 'Tiempo de reposo',
            value: modalMode === 'edit'
              ? getFieldValue(selectedRecipe.rest_time_minutes || 0, 'rest_time_minutes')
              : formatTime(getFieldValue(selectedRecipe.rest_time_minutes || 0, 'rest_time_minutes')),
            type: modalMode === 'edit' ? 'number' : 'text',
            placeholder: modalMode === 'edit' ? 'minutos' : undefined,
            editable: modalMode === 'edit'
          },
          {
            label: 'Tiempo total',
            value: selectedRecipe.total_time_minutes ? formatTime(selectedRecipe.total_time_minutes) : 'No especificado',
            type: 'text',
            highlight: true,
            readonly: true
          }
        ]
      },
      {
        title: 'Análisis Financiero',
        icon: Euro,
        fields: [
          {
            label: 'Costo estimado por unidad',
            value: getFieldValue(selectedRecipe.estimated_cost_per_unit || 0, 'estimated_cost_per_unit'),
            type: modalMode === 'edit' ? 'number' : 'currency',
            editable: modalMode === 'edit'
          },
          {
            label: 'Precio de venta sugerido',
            value: getFieldValue(selectedRecipe.suggested_selling_price || 0, 'suggested_selling_price'),
            type: modalMode === 'edit' ? 'number' : 'currency',
            editable: modalMode === 'edit'
          },
          {
            label: 'Margen objetivo',
            value: getFieldValue(selectedRecipe.target_margin_percentage || 0, 'target_margin_percentage'),
            type: modalMode === 'edit' ? 'number' : 'percentage',
            highlight: true,
            editable: modalMode === 'edit'
          }
        ]
      },
      {
        title: 'Configuración Especial',
        icon: Star,
        fields: [
          {
            label: 'Receta estacional',
            value: modalMode === 'edit'
              ? getFieldValue(selectedRecipe.is_seasonal, 'is_seasonal')
              : (selectedRecipe.is_seasonal ? 'Sí' : 'No'),
            type: modalMode === 'edit' ? 'select' : 'text',
            options: modalMode === 'edit' ? [
              { value: 'false', label: 'No' },
              { value: 'true', label: 'Sí' }
            ] : undefined,
            editable: modalMode === 'edit'
          },
          {
            label: 'Mes de inicio',
            value: getFieldValue(selectedRecipe.season_start_month || 'No especificado', 'season_start_month'),
            type: modalMode === 'edit' ? 'number' : 'text',
            editable: modalMode === 'edit'
          },
          {
            label: 'Mes de fin',
            value: getFieldValue(selectedRecipe.season_end_month || 'No especificado', 'season_end_month'),
            type: modalMode === 'edit' ? 'number' : 'text',
            editable: modalMode === 'edit'
          },
          {
            label: 'Receta estrella',
            value: modalMode === 'edit'
              ? getFieldValue(selectedRecipe.is_signature_item, 'is_signature_item')
              : (selectedRecipe.is_signature_item ? 'Sí' : 'No'),
            type: modalMode === 'edit' ? 'select' : 'text',
            options: modalMode === 'edit' ? [
              { value: 'false', label: 'No' },
              { value: 'true', label: 'Sí' }
            ] : undefined,
            editable: modalMode === 'edit',
            highlight: selectedRecipe.is_signature_item
          }
        ]
      },
      {
        title: 'Configuración de Producción',
        icon: Settings,
        fields: [
          {
            label: 'Multiplicador de lote',
            value: getFieldValue(selectedRecipe.batch_size_multiplier || 1.0, 'batch_size_multiplier'),
            type: modalMode === 'edit' ? 'number' : 'text',
            editable: modalMode === 'edit'
          },
          {
            label: 'Tamaño mínimo de lote',
            value: getFieldValue(selectedRecipe.minimum_batch_size || 'No especificado', 'minimum_batch_size'),
            type: modalMode === 'edit' ? 'number' : 'text',
            editable: modalMode === 'edit'
          },
          {
            label: 'Tamaño máximo de lote',
            value: getFieldValue(selectedRecipe.maximum_batch_size || 'No especificado', 'maximum_batch_size'),
            type: modalMode === 'edit' ? 'number' : 'text',
            editable: modalMode === 'edit'
          },
          {
            label: 'Temperatura óptima',
            value: modalMode === 'edit'
              ? getFieldValue(selectedRecipe.optimal_production_temperature || '', 'optimal_production_temperature')
              : `${getFieldValue(selectedRecipe.optimal_production_temperature || 'No especificado', 'optimal_production_temperature')}${selectedRecipe.optimal_production_temperature ? '°C' : ''}`,
            type: modalMode === 'edit' ? 'number' : 'text',
            editable: modalMode === 'edit'
          },
          {
            label: 'Humedad óptima',
            value: modalMode === 'edit'
              ? getFieldValue(selectedRecipe.optimal_humidity || '', 'optimal_humidity')
              : `${getFieldValue(selectedRecipe.optimal_humidity || 'No especificado', 'optimal_humidity')}${selectedRecipe.optimal_humidity ? '%' : ''}`,
            type: modalMode === 'edit' ? 'number' : 'text',
            editable: modalMode === 'edit'
          }
        ]
      },
      {
        title: 'Instrucciones',
        icon: FileText,
        fields: [
          {
            label: 'Notas de preparación',
            value: getFieldValue(selectedRecipe.preparation_notes || 'No especificado', 'preparation_notes'),
            type: modalMode === 'edit' ? 'textarea' : 'text',
            editable: modalMode === 'edit',
            span: 2
          },
          {
            label: 'Instrucciones de almacenamiento',
            value: getFieldValue(selectedRecipe.storage_instructions || 'No especificado', 'storage_instructions'),
            type: modalMode === 'edit' ? 'textarea' : 'text',
            editable: modalMode === 'edit',
            span: 2
          },
          {
            label: 'Instrucciones de preparación',
            value: modalMode === 'edit'
              ? formatJsonField(getFieldValue(selectedRecipe.instructions, 'instructions'))
              : '', // Empty string when using customRenderer in view mode
            type: modalMode === 'edit' ? 'textarea' : 'custom',
            editable: modalMode === 'edit',
            span: 2,
            customRenderer: modalMode === 'view' ? () => {
              const instructions = selectedRecipe.instructions;

              if (!instructions) {
                return (
                  <div className="text-sm text-[var(--text-secondary)] italic">
                    No especificado
                  </div>
                );
              }

              // Handle array of instruction objects
              if (Array.isArray(instructions)) {
                return (
                  <div className="space-y-2">
                    {instructions.map((item: any, index: number) => {
                      // Handle different item types
                      let stepTitle = '';
                      let stepDescription = '';

                      if (typeof item === 'string') {
                        stepDescription = item;
                      } else if (typeof item === 'object' && item !== null) {
                        stepTitle = item.step || item.title || '';
                        stepDescription = item.description || '';

                        // If no description but has other fields, stringify them
                        if (!stepDescription && !stepTitle) {
                          stepDescription = JSON.stringify(item);
                        }
                      } else {
                        stepDescription = String(item);
                      }

                      return (
                        <div key={index} className="flex gap-3">
                          <div className="flex-shrink-0 w-6 h-6 rounded-full bg-[var(--color-primary)]/10 flex items-center justify-center text-xs font-semibold text-[var(--color-primary)]">
                            {index + 1}
                          </div>
                          <div className="flex-1">
                            {stepTitle && stepDescription ? (
                              <>
                                <div className="font-medium text-[var(--text-primary)]">{stepTitle}</div>
                                <div className="text-sm text-[var(--text-secondary)] mt-1">{stepDescription}</div>
                              </>
                            ) : stepDescription ? (
                              <div className="text-sm text-[var(--text-primary)]">{stepDescription}</div>
                            ) : stepTitle ? (
                              <div className="text-sm text-[var(--text-primary)]">{stepTitle}</div>
                            ) : (
                              <div className="text-sm text-[var(--text-secondary)] italic">
                                Sin información
                              </div>
                            )}
                          </div>
                        </div>
                      );
                    })}
                  </div>
                );
              }

              // Handle string
              if (typeof instructions === 'string') {
                return (
                  <div className="text-sm text-[var(--text-primary)] whitespace-pre-wrap">
                    {instructions}
                  </div>
                );
              }

              // Handle object
              if (typeof instructions === 'object') {
                return (
                  <div className="text-sm text-[var(--text-primary)] whitespace-pre-wrap">
                    {formatJsonField(instructions)}
                  </div>
                );
              }

              return (
                <div className="text-sm text-[var(--text-secondary)] italic">
                  No especificado
                </div>
              );
            } : undefined
          }
        ]
      },
      {
        title: 'Información Nutricional',
        icon: Package,
        fields: [
          {
            label: 'Información de alérgenos',
            value: modalMode === 'edit'
              ? formatJsonField(getFieldValue(selectedRecipe.allergen_info, 'allergen_info'))
              : formatJsonField(selectedRecipe.allergen_info),
            type: modalMode === 'edit' ? 'textarea' : 'text',
            editable: modalMode === 'edit',
            span: 2
          },
          {
            label: 'Etiquetas dietéticas',
            value: modalMode === 'edit'
              ? formatJsonField(getFieldValue(selectedRecipe.dietary_tags, 'dietary_tags'))
              : formatJsonField(selectedRecipe.dietary_tags),
            type: modalMode === 'edit' ? 'textarea' : 'text',
            editable: modalMode === 'edit',
            span: 2
          },
          {
            label: 'Información nutricional',
            value: modalMode === 'edit'
              ? formatJsonField(getFieldValue(selectedRecipe.nutritional_info, 'nutritional_info'))
              : formatJsonField(selectedRecipe.nutritional_info),
            type: modalMode === 'edit' ? 'textarea' : 'text',
            editable: modalMode === 'edit',
            span: 2
          }
        ]
      },
      {
        title: 'Ingredientes',
        icon: Package,
        fields: [
          {
            label: '',
            value: '',
            type: modalMode === 'edit' ? ('component' as const) : ('custom' as const),
            component: modalMode === 'edit' ? IngredientsEditComponent : undefined,
            componentProps: modalMode === 'edit' ? {
              value: editedIngredients.length > 0 ? editedIngredients : (selectedRecipe.ingredients || []),
              availableIngredients,
              unitOptions,
              onChange: (newIngredients: RecipeIngredientResponse[]) => {
                setEditedIngredients(newIngredients);
              }
            } : undefined,
            customRenderer: modalMode === 'view' ? () => {
              const ingredients = selectedRecipe.ingredients
                ?.sort((a, b) => a.ingredient_order - b.ingredient_order) || [];

              if (ingredients.length === 0) {
                return (
                  <div className="text-sm text-[var(--text-secondary)] italic p-4 bg-[var(--bg-secondary)]/30 rounded-md">
                    No hay ingredientes especificados
                  </div>
                );
              }

              return (
                <div className="space-y-3">
                  {ingredients.map((ing, idx) => {
                    const ingredientName = ingredientLookup[ing.ingredient_id] || 'Ingrediente desconocido';
                    const hasDetails = ing.preparation_method || ing.ingredient_notes || ing.substitution_options;

                    return (
                      <div
                        key={ing.id || idx}
                        className="p-3 rounded-lg bg-[var(--bg-secondary)]/50 border border-[var(--border-secondary)] hover:border-[var(--color-primary)]/30 transition-colors"
                      >
                        <div className="flex items-start gap-3">
                          <div className="flex-shrink-0 w-8 h-8 rounded-full bg-[var(--color-primary)]/10 flex items-center justify-center text-sm font-semibold text-[var(--color-primary)]">
                            {idx + 1}
                          </div>
                          <div className="flex-1 space-y-2">
                            <div className="flex items-baseline gap-2 flex-wrap">
                              <span className="font-bold text-[var(--color-primary)]">
                                {ing.quantity} {ing.unit}
                              </span>
                              <span className="text-[var(--text-primary)] font-medium">
                                {ingredientName}
                              </span>
                              {ing.is_optional && (
                                <span className="text-xs px-2 py-0.5 rounded-full bg-amber-500/10 text-amber-700 dark:text-amber-400 border border-amber-500/20">
                                  opcional
                                </span>
                              )}
                            </div>

                            {hasDetails && (
                              <div className="space-y-1.5 text-sm">
                                {ing.preparation_method && (
                                  <div className="flex items-start gap-2 text-[var(--text-secondary)]">
                                    <span className="text-blue-500 flex-shrink-0">→</span>
                                    <span className="italic">{ing.preparation_method}</span>
                                  </div>
                                )}
                                {ing.ingredient_notes && (
                                  <div className="flex items-start gap-2 text-[var(--text-secondary)]">
                                    <span className="flex-shrink-0">💡</span>
                                    <span>{ing.ingredient_notes}</span>
                                  </div>
                                )}
                                {ing.substitution_options && (
                                  <div className="flex items-start gap-2 text-[var(--text-secondary)]">
                                    <span className="flex-shrink-0">🔄</span>
                                    <span>
                                      <strong>Sustituto:</strong> {typeof ing.substitution_options === 'string' ? ing.substitution_options : JSON.stringify(ing.substitution_options)}
                                      {ing.substitution_ratio && ` (ratio: ${ing.substitution_ratio})`}
                                    </span>
                                  </div>
                                )}
                              </div>
                            )}
                          </div>
                        </div>
                      </div>
                    );
                  })}

                  {/* Summary footer */}
                  <div className="pt-2 mt-2 border-t border-[var(--border-secondary)]">
                    <div className="text-sm text-[var(--text-secondary)] flex items-center justify-between">
                      <span>Total: {ingredients.length} ingrediente{ingredients.length !== 1 ? 's' : ''}</span>
                      {ingredients.some(ing => ing.is_optional) && (
                        <span className="text-xs text-amber-600 dark:text-amber-400">
                          ⚠️ Incluye ingredientes opcionales
                        </span>
                      )}
                    </div>
                  </div>
                </div>
              );
            } : undefined,
            span: 2,
            editable: modalMode === 'edit'
          }
        ]
      },
      {
        title: 'Control de Calidad',
        icon: CheckCircle,
        fields: [
          {
            label: 'Configuración de controles',
            value: selectedRecipe.quality_check_configuration
              ? getQualityConfigSummary(selectedRecipe.quality_check_configuration)
              : 'No configurado',
            type: modalMode === 'view' ? 'custom' : 'button',
            span: 2,
            buttonText: modalMode === 'edit' ? 'Configurar Controles de Calidad' : undefined,
            onButtonClick: modalMode === 'edit' ? () => {
              // Open quality check configuration modal
              setShowQualityConfigModal(true);
            } : undefined,
            customRenderer: modalMode === 'view' ? () => {
              const config = selectedRecipe.quality_check_configuration as any;

              if (!config || !config.stages || Object.keys(config.stages).length === 0) {
                return (
                  <div className="text-sm text-[var(--text-secondary)] italic p-4 bg-[var(--bg-secondary)]/30 rounded-md">
                    No hay controles de calidad configurados para esta receta
                  </div>
                );
              }

              const stageLabels = {
                [ProcessStage.MIXING]: 'Mezclado',
                [ProcessStage.PROOFING]: 'Fermentación',
                [ProcessStage.SHAPING]: 'Formado',
                [ProcessStage.BAKING]: 'Horneado',
                [ProcessStage.COOLING]: 'Enfriado',
                [ProcessStage.PACKAGING]: 'Empaquetado',
                [ProcessStage.FINISHING]: 'Acabado'
              };

              const configuredStages = Object.entries(config.stages).filter(
                ([_, stageConfig]: [string, any]) => stageConfig?.template_ids?.length > 0
              );

              return (
                <div className="space-y-4">
                  {/* Summary Stats */}
                  <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                    <div className="p-3 rounded-lg bg-blue-50 dark:bg-blue-950/30 border border-blue-200 dark:border-blue-800">
                      <div className="text-xs text-blue-600 dark:text-blue-400 font-medium mb-1">Etapas Configuradas</div>
                      <div className="text-2xl font-bold text-blue-700 dark:text-blue-300">{configuredStages.length}</div>
                    </div>
                    <div className="p-3 rounded-lg bg-green-50 dark:bg-green-950/30 border border-green-200 dark:border-green-800">
                      <div className="text-xs text-green-600 dark:text-green-400 font-medium mb-1">Total Controles</div>
                      <div className="text-2xl font-bold text-green-700 dark:text-green-300">
                        {Object.values(config.stages).reduce((sum: number, stage: any) => sum + (stage?.template_ids?.length || 0), 0)}
                      </div>
                    </div>
                    <div className="p-3 rounded-lg bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-800">
                      <div className="text-xs text-amber-600 dark:text-amber-400 font-medium mb-1">Umbral de Calidad</div>
                      <div className="text-2xl font-bold text-amber-700 dark:text-amber-300">
                        {config.overall_quality_threshold ? `${config.overall_quality_threshold}/10` : 'N/A'}
                      </div>
                    </div>
                  </div>

                  {/* Configured Stages */}
                  <div className="space-y-3">
                    <h4 className="text-sm font-semibold text-[var(--text-primary)] flex items-center gap-2">
                      <CheckCircle className="w-4 h-4" />
                      Etapas Configuradas
                    </h4>
                    {configuredStages.map(([stage, stageConfig]: [string, any]) => (
                      <div
                        key={stage}
                        className="p-4 rounded-lg bg-[var(--bg-secondary)]/50 border border-[var(--border-secondary)] hover:border-[var(--color-primary)]/30 transition-colors"
                      >
                        <div className="flex items-start justify-between mb-2">
                          <div className="flex items-center gap-2">
                            <div className="w-8 h-8 rounded-full bg-[var(--color-primary)]/10 flex items-center justify-center">
                              <CheckCircle className="w-4 h-4 text-[var(--color-primary)]" />
                            </div>
                            <div>
                              <h5 className="text-sm font-semibold text-[var(--text-primary)]">
                                {stageLabels[stage as ProcessStage] || stage}
                              </h5>
                              <p className="text-xs text-[var(--text-secondary)]">
                                {stageConfig.template_ids.length} control{stageConfig.template_ids.length !== 1 ? 'es' : ''}
                              </p>
                            </div>
                          </div>
                          <div className="flex gap-2">
                            {stageConfig.is_required && (
                              <span className="text-xs px-2 py-0.5 rounded-full bg-red-500/10 text-red-700 dark:text-red-400 border border-red-500/20">
                                Obligatorio
                              </span>
                            )}
                            {stageConfig.blocking && (
                              <span className="text-xs px-2 py-0.5 rounded-full bg-amber-500/10 text-amber-700 dark:text-amber-400 border border-amber-500/20">
                                Bloqueante
                              </span>
                            )}
                          </div>
                        </div>
                      </div>
                    ))}
                  </div>

                  {/* Global Settings */}
                  {(config.auto_create_quality_checks || config.quality_manager_approval_required || config.critical_stage_blocking) && (
                    <div className="pt-3 border-t border-[var(--border-secondary)]">
                      <h4 className="text-sm font-semibold text-[var(--text-primary)] mb-2">Configuración Global</h4>
                      <div className="flex flex-wrap gap-2">
                        {config.auto_create_quality_checks && (
                          <span className="text-xs px-2 py-1 rounded-md bg-blue-500/10 text-blue-700 dark:text-blue-400 border border-blue-500/20">
                            ✓ Creación automática de controles
                          </span>
                        )}
                        {config.quality_manager_approval_required && (
                          <span className="text-xs px-2 py-1 rounded-md bg-purple-500/10 text-purple-700 dark:text-purple-400 border border-purple-500/20">
                            ✓ Requiere aprobación del responsable
                          </span>
                        )}
                        {config.critical_stage_blocking && (
                          <span className="text-xs px-2 py-1 rounded-md bg-red-500/10 text-red-700 dark:text-red-400 border border-red-500/20">
                            ✓ Etapas críticas bloqueantes
                          </span>
                        )}
                      </div>
                    </div>
                  )}
                </div>
              );
            } : undefined,
            readonly: modalMode !== 'edit'
          }
        ]
      }
    ];
  };

  return (
    <div className="space-y-6">
      <PageHeader
        title="Gestión de Recetas"
        description="Administra y organiza todas las recetas de tu panadería"
        actions={[
          {
            id: "new",
            label: "Nueva Receta",
            variant: "primary" as const,
            icon: Plus,
            onClick: () => setShowCreateModal(true)
          }
        ]}
      />

      {/* Stats Grid */}
      <StatsGrid
        stats={stats}
        columns={3}
      />

      {/* Search and Filter Controls */}
      <SearchAndFilter
        searchValue={searchTerm}
        onSearchChange={setSearchTerm}
        searchPlaceholder="Buscar recetas por nombre, descripción o categoría..."
        filters={[
          {
            key: 'category',
            label: 'Categoría',
            type: 'dropdown',
            value: categoryFilter,
            onChange: (value) => setCategoryFilter(value as string),
            placeholder: 'Todas las categorías',
            options: [
              { value: 'bread', label: 'Pan' },
              { value: 'pastry', label: 'Bollería' },
              { value: 'cake', label: 'Tarta' },
              { value: 'cookie', label: 'Galleta' },
              { value: 'other', label: 'Otro' }
            ]
          },
          {
            key: 'difficulty',
            label: 'Dificultad',
            type: 'dropdown',
            value: difficultyFilter,
            onChange: (value) => setDifficultyFilter(value as string),
            placeholder: 'Todas las dificultades',
            options: [
              { value: '1', label: 'Nivel 1 - Fácil' },
              { value: '2', label: 'Nivel 2 - Medio' },
              { value: '3', label: 'Nivel 3 - Difícil' },
              { value: '4', label: 'Nivel 4 - Muy Difícil' },
              { value: '5', label: 'Nivel 5 - Extremo' }
            ]
          },
          {
            key: 'signature',
            label: 'Solo recetas especiales',
            type: 'checkbox',
            value: isSignatureOnly,
            onChange: (value) => setIsSignatureOnly(value as boolean)
          }
        ] as FilterConfig[]}
      />

      {/* Recipes Grid */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
        {filteredRecipes.map((recipe) => {
          const statusConfig = getRecipeStatusConfig(recipe);
          const cost = recipe.estimated_cost_per_unit || 0;
          const price = recipe.suggested_selling_price || 0;
          const profitMargin = price > 0 ? Math.round(((price - cost) / price) * 100) : 0;
          const totalTime = formatTime((recipe.prep_time_minutes || 0) + (recipe.cook_time_minutes || 0));
          
          return (
            <StatusCard
              key={recipe.id}
              id={recipe.id}
              statusIndicator={statusConfig}
              title={recipe.name}
              subtitle={`${statusConfig.text} • ${statusConfig.difficultyLabel}${statusConfig.isHighlight ? ' ★' : ''}`}
              primaryValue={recipe.ingredients?.length || 0}
              primaryValueLabel="ingredientes"
              secondaryInfo={{
                label: 'Margen',
                value: `${currencySymbol}${formatters.compact(price - cost)}`
              }}
              progress={{
                label: 'Margen de beneficio',
                percentage: profitMargin,
                color: profitMargin > 50 ? '#10b981' : profitMargin > 30 ? '#f59e0b' : '#ef4444'
              }}
              metadata={[
                `Tiempo: ${totalTime}`,
                `Rendimiento: ${recipe.yield_quantity} ${recipe.yield_unit}`,
                `Control de Calidad: ${getQualityIndicator(recipe)}`
              ]}
              onClick={() => handleOpenRecipe(recipe.id)}
              actions={[
                // Primary action - View recipe details
                {
                  label: 'Ver Detalles',
                  icon: Eye,
                  variant: 'primary',
                  priority: 'primary',
                  onClick: () => handleOpenRecipe(recipe.id)
                },
                // Delete action
                {
                  label: 'Eliminar',
                  icon: Trash2,
                  variant: 'outline',
                  priority: 'secondary',
                  onClick: () => {
                    setRecipeToDelete(recipe);
                    setShowDeleteModal(true);
                  }
                }
              ]}
            />
          );
        })}
      </div>

      {/* Empty State */}
      {filteredRecipes.length === 0 && (
        <EmptyState
          icon={ChefHat}
          title="No se encontraron recetas"
          description="Intenta ajustar la búsqueda o crear una nueva receta"
          actionLabel="Nueva Receta"
          actionIcon={Plus}
          onAction={() => setShowCreateModal(true)}
        />
      )}

      {/* Recipe Details Modal */}
      {showForm && selectedRecipe && (
        <RecipeViewEditModal
          isOpen={showForm}
          onClose={() => {
            setShowForm(false);
            setSelectedRecipe(null);
            setModalMode('view');
          }}
          recipe={selectedRecipe}
          mode={modalMode}
          onModeChange={(newMode) => {
            setModalMode(newMode);
          }}
          onSave={handleSaveRecipe}
          isSaving={updateRecipeMutation.isPending}
        />
      )}

      {/* Create Recipe Modal */}
      <CreateRecipeModal
        isOpen={showCreateModal}
        onClose={() => setShowCreateModal(false)}
        onCreateRecipe={handleCreateRecipe}
      />

      {/* Quality Check Configuration Modal */}
      {selectedRecipe && (
        <QualityCheckConfigurationModal
          isOpen={showQualityConfigModal}
          onClose={() => setShowQualityConfigModal(false)}
          recipe={selectedRecipe}
          onSaveConfiguration={handleSaveQualityConfiguration}
          isLoading={updateRecipeMutation.isPending}
        />
      )}

      {/* Delete Recipe Modal */}
      <DeleteRecipeModal
        isOpen={showDeleteModal}
        onClose={() => {
          setShowDeleteModal(false);
          setRecipeToDelete(null);
        }}
        recipe={recipeToDelete}
        onSoftDelete={handleSoftDelete}
        onHardDelete={handleHardDelete}
        isLoading={archiveRecipeMutation.isPending || deleteRecipeMutation.isPending}
      />

      {/* Quality Configuration Prompt */}
      {newlyCreatedRecipe && (
        <QualityPromptDialog
          isOpen={showQualityPrompt}
          onClose={handleConfigureQualityLater}
          onConfigureNow={handleConfigureQualityNow}
          onConfigureLater={handleConfigureQualityLater}
          recipeName={newlyCreatedRecipe.name}
        />
      )}
    </div>
  );
};

export default RecipesPage;