import React, { useState, useMemo, useCallback, useEffect } from 'react';
import { EditViewModal } from '../../ui/EditViewModal/EditViewModal';
import { ChefHat, Clock, Euro, Package, CheckCircle, Star, Settings, FileText, Plus, Trash2 } from 'lucide-react';
import { formatters } from '../../ui/Stats/StatsPresets';
import { getStatusColor } from '../../ui/StatusCard';
import { MeasurementUnit } from '../../../api/types/recipes';
import type { RecipeResponse, RecipeIngredientResponse } from '../../../api/types/recipes';
import { ProcessStage } from '../../../api/types/qualityTemplates';
import type { EditViewModalSection } from '../../ui/EditViewModal/EditViewModal';
import { useIngredients } from '../../../api/hooks/inventory';
import { useCurrentTenant } from '../../../stores/tenant.store';
import { RecipeInstructionsEditor } from './RecipeInstructionsEditor';
import { RecipeQualityControlEditor } from './RecipeQualityControlEditor';
import { useQualityTemplatesForRecipe } from '../../../api/hooks/qualityTemplates';

interface RecipeViewEditModalProps {
  isOpen: boolean;
  onClose: () => void;
  recipe: RecipeResponse | null;
  mode: 'view' | 'edit';
  onModeChange?: (mode: 'view' | 'edit') => void;
  onSave?: (recipe: RecipeResponse) => Promise<void>;
  isSaving?: boolean;
  isLoading?: boolean;
}

// 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 RecipeViewEditModal: React.FC<RecipeViewEditModalProps> = ({
  isOpen,
  onClose,
  recipe,
  mode,
  onModeChange,
  onSave,
  isSaving = false,
  isLoading = false
}) => {
  const [editedRecipe, setEditedRecipe] = useState<Partial<RecipeResponse>>({});
  const [editedIngredients, setEditedIngredients] = useState<RecipeIngredientResponse[]>([]);

  // Fetch ingredients for lookup
  const currentTenant = useCurrentTenant();
  const tenantId = currentTenant?.id || '';
  const { data: inventoryItems = [] } = useIngredients(tenantId, {});

  // Fetch quality templates for the recipe
  const { data: qualityTemplates = [] } = useQualityTemplatesForRecipe(tenantId, recipe?.id || '');

  // 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' },
  ], []);

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

  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`;
  };

  // Parse instructions safely to prevent rendering issues
  const formatJsonField = (jsonData: any): string => {
    if (jsonData === null || jsonData === undefined) return '';
    if (typeof jsonData === 'string') return jsonData;
    try {
      return JSON.stringify(jsonData, null, 2);
    } catch (error) {
      console.error('Error formatting JSON field:', error);
      return String(jsonData);
    }
  };

  // Get field value based on mode and edited state
  const getFieldValue = useCallback((currentValue: any, fieldName: keyof RecipeResponse) => {
    if (mode === 'edit' && editedRecipe && fieldName in editedRecipe) {
      return editedRecipe[fieldName];
    }
    return currentValue;
  }, [mode, editedRecipe]);

  // Handle field changes in edit mode
  const handleFieldChange = useCallback((sectionIndex: number, fieldIndex: number, value: string | number | boolean) => {
    setEditedRecipe(prev => ({ ...prev }));
  }, []);

  // Handle ingredient changes
  const handleIngredientsChange = useCallback((value: RecipeIngredientResponse[]) => {
    setEditedIngredients(value);
  }, []);

  // Get recipe status config
  const getRecipeStatusConfig = useCallback((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
    };
  }, []);

  // Memoized sections to prevent re-renders
  const sections = useMemo((): EditViewModalSection[] => {
    if (!recipe) return [];

    return [
      {
        title: 'Información Básica',
        icon: ChefHat,
        fields: [
          {
            label: 'Nombre',
            value: getFieldValue(recipe.name, 'name'),
            type: mode === 'edit' ? 'text' : 'text',
            editable: mode === 'edit',
            span: 2
          },
          {
            label: 'Código de receta',
            value: getFieldValue(recipe.recipe_code || 'Sin código', 'recipe_code'),
            type: mode === 'edit' ? 'text' : 'text',
            editable: mode === 'edit'
          },
          {
            label: 'Versión',
            value: getFieldValue(recipe.version, 'version'),
            type: mode === 'edit' ? 'text' : 'text',
            editable: mode === 'edit'
          },
          {
            label: 'Descripción',
            value: getFieldValue(recipe.description || 'Sin descripción', 'description'),
            type: mode === 'edit' ? 'textarea' : 'text',
            editable: mode === 'edit',
            span: 2
          },
          {
            label: 'Categoría',
            value: mode === 'edit'
              ? getFieldValue(recipe.category, 'category')
              : getCategoryLabel(getFieldValue(recipe.category, 'category') as string),
            type: mode === 'edit' ? 'select' : 'status',
            options: mode === '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(recipe.cuisine_type || 'No especificado', 'cuisine_type'),
            type: mode === 'edit' ? 'text' : 'text',
            editable: mode === 'edit'
          },
          {
            label: 'Dificultad',
            value: mode === 'edit'
              ? getFieldValue(recipe.difficulty_level, 'difficulty_level')
              : `Nivel ${getFieldValue(recipe.difficulty_level, 'difficulty_level')}`,
            type: mode === 'edit' ? 'select' : 'text',
            options: mode === '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(recipe.status, 'status'),
            type: mode === 'edit' ? 'select' : 'text',
            options: mode === 'edit' ? [
              { value: 'draft', label: 'Borrador' },
              { value: 'active', label: 'Activo' },
              { value: 'testing', label: 'Testing' },
              { value: 'archived', label: 'Archivado' },
              { value: 'discontinued', label: 'Discontinuado' }
            ] : undefined,
            highlight: recipe.status === 'active',
            editable: true
          },
          {
            label: 'Rendimiento',
            value: getFieldValue(recipe.yield_quantity, 'yield_quantity'),
            type: mode === 'edit' ? 'number' : 'text',
            editable: mode === 'edit'
          },
          {
            label: 'Unidad de rendimiento',
            value: getFieldValue(recipe.yield_unit, 'yield_unit'),
            type: mode === 'edit' ? 'text' : 'text',
            editable: mode === 'edit'
          },
          {
            label: 'Porciones',
            value: getFieldValue(recipe.serves_count || 1, 'serves_count'),
            type: mode === 'edit' ? 'number' : 'text',
            editable: mode === 'edit'
          }
        ]
      },
      {
        title: 'Tiempos',
        icon: Clock,
        fields: [
          {
            label: 'Tiempo de preparación',
            value: mode === 'edit'
              ? getFieldValue(recipe.prep_time_minutes || 0, 'prep_time_minutes')
              : formatTime(getFieldValue(recipe.prep_time_minutes || 0, 'prep_time_minutes')),
            type: mode === 'edit' ? 'number' : 'text',
            placeholder: mode === 'edit' ? 'minutos' : undefined,
            editable: mode === 'edit'
          },
          {
            label: 'Tiempo de cocción',
            value: mode === 'edit'
              ? getFieldValue(recipe.cook_time_minutes || 0, 'cook_time_minutes')
              : formatTime(getFieldValue(recipe.cook_time_minutes || 0, 'cook_time_minutes')),
            type: mode === 'edit' ? 'number' : 'text',
            placeholder: mode === 'edit' ? 'minutos' : undefined,
            editable: mode === 'edit'
          },
          {
            label: 'Tiempo de reposo',
            value: mode === 'edit'
              ? getFieldValue(recipe.rest_time_minutes || 0, 'rest_time_minutes')
              : formatTime(getFieldValue(recipe.rest_time_minutes || 0, 'rest_time_minutes')),
            type: mode === 'edit' ? 'number' : 'text',
            placeholder: mode === 'edit' ? 'minutos' : undefined,
            editable: mode === 'edit'
          },
          {
            label: 'Tiempo total',
            value: recipe.total_time_minutes ? formatTime(recipe.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(recipe.estimated_cost_per_unit || 0, 'estimated_cost_per_unit'),
            type: mode === 'edit' ? 'number' : 'currency',
            editable: mode === 'edit'
          },
          {
            label: 'Precio de venta sugerido',
            value: getFieldValue(recipe.suggested_selling_price || 0, 'suggested_selling_price'),
            type: mode === 'edit' ? 'number' : 'currency',
            editable: mode === 'edit'
          },
          {
            label: 'Margen objetivo',
            value: getFieldValue(recipe.target_margin_percentage || 0, 'target_margin_percentage'),
            type: mode === 'edit' ? 'number' : 'percentage',
            highlight: true,
            editable: mode === 'edit'
          }
        ]
      },
      {
        title: 'Configuración Especial',
        icon: Star,
        fields: [
          {
            label: 'Receta estacional',
            value: mode === 'edit'
              ? getFieldValue(recipe.is_seasonal, 'is_seasonal')
              : (recipe.is_seasonal ? 'Sí' : 'No'),
            type: mode === 'edit' ? 'select' : 'text',
            options: mode === 'edit' ? [
              { value: 'false', label: 'No' },
              { value: 'true', label: 'Sí' }
            ] : undefined,
            editable: mode === 'edit'
          },
          {
            label: 'Mes de inicio',
            value: getFieldValue(recipe.season_start_month || 'No especificado', 'season_start_month'),
            type: mode === 'edit' ? 'number' : 'text',
            editable: mode === 'edit'
          },
          {
            label: 'Mes de fin',
            value: getFieldValue(recipe.season_end_month || 'No especificado', 'season_end_month'),
            type: mode === 'edit' ? 'number' : 'text',
            editable: mode === 'edit'
          },
          {
            label: 'Receta estrella',
            value: mode === 'edit'
              ? getFieldValue(recipe.is_signature_item, 'is_signature_item')
              : (recipe.is_signature_item ? 'Sí' : 'No'),
            type: mode === 'edit' ? 'select' : 'text',
            options: mode === 'edit' ? [
              { value: 'false', label: 'No' },
              { value: 'true', label: 'Sí' }
            ] : undefined,
            editable: mode === 'edit',
            highlight: recipe.is_signature_item
          }
        ]
      },
      {
        title: 'Configuración de Producción',
        icon: Settings,
        fields: [
          {
            label: 'Multiplicador de lote',
            value: getFieldValue(recipe.batch_size_multiplier || 1.0, 'batch_size_multiplier'),
            type: mode === 'edit' ? 'number' : 'text',
            editable: mode === 'edit'
          },
          {
            label: 'Tamaño mínimo de lote',
            value: getFieldValue(recipe.minimum_batch_size || 'No especificado', 'minimum_batch_size'),
            type: mode === 'edit' ? 'number' : 'text',
            editable: mode === 'edit'
          },
          {
            label: 'Tamaño máximo de lote',
            value: getFieldValue(recipe.maximum_batch_size || 'No especificado', 'maximum_batch_size'),
            type: mode === 'edit' ? 'number' : 'text',
            editable: mode === 'edit'
          },
          {
            label: 'Temperatura óptima',
            value: mode === 'edit'
              ? getFieldValue(recipe.optimal_production_temperature || '', 'optimal_production_temperature')
              : `${getFieldValue(recipe.optimal_production_temperature || 'No especificado', 'optimal_production_temperature')}${recipe.optimal_production_temperature ? '°C' : ''}`,
            type: mode === 'edit' ? 'number' : 'text',
            editable: mode === 'edit'
          },
          {
            label: 'Humedad óptima',
            value: mode === 'edit'
              ? getFieldValue(recipe.optimal_humidity || '', 'optimal_humidity')
              : `${getFieldValue(recipe.optimal_humidity || 'No especificado', 'optimal_humidity')}${recipe.optimal_humidity ? '%' : ''}`,
            type: mode === 'edit' ? 'number' : 'text',
            editable: mode === 'edit'
          }
        ]
      },
      {
        title: 'Instrucciones',
        icon: FileText,
        fields: [
          {
            label: 'Notas de preparación',
            value: getFieldValue(recipe.preparation_notes || 'No especificado', 'preparation_notes'),
            type: mode === 'edit' ? 'textarea' : 'text',
            editable: mode === 'edit',
            span: 2
          },
          {
            label: 'Instrucciones de almacenamiento',
            value: getFieldValue(recipe.storage_instructions || 'No especificado', 'storage_instructions'),
            type: mode === 'edit' ? 'textarea' : 'text',
            editable: mode === 'edit',
            span: 2
          },
          {
            label: 'Instrucciones de preparación',
            value: mode === 'edit'
              ? formatJsonField(getFieldValue(recipe.instructions, 'instructions'))
              : '', // Empty string when using customRenderer in view mode
            type: mode === 'edit' ? ('component' as const) : ('custom' as const),
            editable: mode === 'edit',
            span: 2,
            component: mode === 'edit' ? RecipeInstructionsEditor : undefined,
            componentProps: mode === 'edit' ? {
              value: getFieldValue(recipe.instructions, 'instructions'),
              onChange: (value: any) => {
                setEditedRecipe(prev => ({
                  ...prev,
                  instructions: value
                }));
              }
            } : undefined,
            customRenderer: mode === 'view' ? () => {
              const instructions = recipe.instructions;

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

              // Handle structured instructions with steps
              if (typeof instructions === 'object' && instructions.steps && Array.isArray(instructions.steps)) {
                return (
                  <div className="space-y-4">
                    <div className="grid grid-cols-1 gap-4">
                      {instructions.steps.map((step: any, index: number) => (
                        <div
                          key={`step-${step.step || index}`}
                          className="p-4 rounded-lg border border-[var(--border-secondary)] bg-[var(--bg-secondary)]/30 hover:border-[var(--color-primary)]/50 transition-colors"
                        >
                          <div className="flex items-start gap-3">
                            <div className="flex-shrink-0 w-8 h-8 rounded-full bg-[var(--color-primary)]/20 flex items-center justify-center text-sm font-bold text-[var(--color-primary)]">
                              {step.step || index + 1}
                            </div>
                            <div className="flex-1">
                              <h4 className="font-bold text-[var(--text-primary)] mb-1">
                                {step.title || `Paso ${step.step || index + 1}`}
                              </h4>
                              <p className="text-[var(--text-secondary)] mb-2">{step.description}</p>
                              {step.duration_minutes && (
                                <div className="flex items-center gap-2 text-xs text-[var(--text-tertiary)]">
                                  <Clock className="w-3 h-3" />
                                  <span>{step.duration_minutes} minutos</span>
                                </div>
                              )}
                            </div>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                );
              }

              // Handle array of instruction objects (legacy format)
              if (Array.isArray(instructions)) {
                return (
                  <div className="space-y-4">
                    <div className="grid grid-cols-1 gap-4">
                      {instructions.map((item: any, index: number) => {
                        // Handle different item types
                        let stepTitle = '';
                        let stepDescription = '';
                        let duration = item.duration_minutes || '';

                        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);
                          }

                          // Handle duration if provided in the object
                          if (item.duration_minutes) {
                            duration = item.duration_minutes;
                          }
                        } else {
                          stepDescription = String(item);
                        }

                        return (
                          <div
                            key={`step-${item.step || item.title || index}`}
                            className="p-4 rounded-lg border border-[var(--border-secondary)] bg-[var(--bg-secondary)]/30 hover:border-[var(--color-primary)]/50 transition-colors"
                          >
                            <div className="flex items-start gap-3">
                              <div className="flex-shrink-0 w-8 h-8 rounded-full bg-[var(--color-primary)]/20 flex items-center justify-center text-sm font-bold text-[var(--color-primary)]">
                                {item.step || index + 1}
                              </div>
                              <div className="flex-1">
                                {stepTitle ? (
                                  <h4 className="font-bold text-[var(--text-primary)] mb-1">{stepTitle}</h4>
                                ) : (
                                  <h4 className="font-bold text-[var(--text-primary)] mb-1">Paso {index + 1}</h4>
                                )}
                                <p className="text-[var(--text-secondary)] mb-2">{stepDescription}</p>
                                {duration && (
                                  <div className="flex items-center gap-2 text-xs text-[var(--text-tertiary)]">
                                    <Clock className="w-3 h-3" />
                                    <span>{duration} minutos</span>
                                  </div>
                                )}
                              </div>
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                );
              }

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

              // Handle object (fallback)
              if (typeof instructions === 'object') {
                return (
                  <div className="text-sm text-[var(--text-primary)] whitespace-pre-wrap p-4 bg-[var(--bg-secondary)]/30 rounded-md">
                    {formatJsonField(instructions)}
                  </div>
                );
              }

              return (
                <div className="text-sm text-[var(--text-secondary)] italic p-4 bg-[var(--bg-secondary)]/30 rounded-md">
                  No especificado
                </div>
              );
            } : undefined
          }
        ]
      },
      {
        title: 'Información Nutricional',
        icon: Package,
        fields: [
          {
            label: 'Información de alérgenos',
            value: mode === 'edit'
              ? formatJsonField(getFieldValue(recipe.allergen_info, 'allergen_info'))
              : formatJsonField(recipe.allergen_info),
            type: mode === 'edit' ? 'textarea' : 'text',
            editable: mode === 'edit',
            span: 2
          },
          {
            label: 'Etiquetas dietéticas',
            value: mode === 'edit'
              ? formatJsonField(getFieldValue(recipe.dietary_tags, 'dietary_tags'))
              : formatJsonField(recipe.dietary_tags),
            type: mode === 'edit' ? 'textarea' : 'text',
            editable: mode === 'edit',
            span: 2
          },
          {
            label: 'Información nutricional',
            value: mode === 'edit'
              ? formatJsonField(getFieldValue(recipe.nutritional_info, 'nutritional_info'))
              : formatJsonField(recipe.nutritional_info),
            type: mode === 'edit' ? 'textarea' : 'text',
            editable: mode === 'edit',
            span: 2
          }
        ]
      },
      {
        title: 'Ingredientes',
        icon: Package,
        fields: [
          {
            label: '',
            value: '',
            type: mode === 'edit' ? ('component' as const) : ('custom' as const),
            component: mode === 'edit' ? IngredientsEditComponent : undefined,
            componentProps: mode === 'edit' ? {
              value: editedIngredients.length > 0 ? editedIngredients : (recipe.ingredients || []),
              availableIngredients,
              unitOptions,
              onChange: handleIngredientsChange,
            } : undefined,
            customRenderer: mode === 'view' ? () => {
              const ingredients = recipe.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}-${ing.ingredient_id || idx}`} // Using more stable key
                        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: mode === 'edit'
          }
        ]
      },
      {
        title: 'Control de Calidad',
        icon: CheckCircle,
        fields: [
          {
            label: '',
            value: '',
            type: mode === 'edit' ? ('component' as const) : ('custom' as const),
            component: mode === 'edit' ? RecipeQualityControlEditor : undefined,
            componentProps: mode === 'edit' ? {
              value: getFieldValue(recipe.quality_check_configuration, 'quality_check_configuration'),
              onChange: (value: any) => {
                setEditedRecipe(prev => ({
                  ...prev,
                  quality_check_configuration: value
                }));
              },
              allTemplates: qualityTemplates.map(template => ({
                id: template.id,
                name: template.name,
                category: template.category
              }))
            } : undefined,
            customRenderer: mode === 'view' ? () => {
              const config = recipe.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}-${stageConfig.template_ids?.length || 0}`} // More stable key
                        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,
            span: 2,
            editable: mode === 'edit'
          }
        ]
      }
    ];
  }, [
    recipe,
    mode,
    getFieldValue,
    formatTime,
    getCategoryLabel,
    getQualityConfigSummary,
    formatJsonField,
    ingredientLookup,
    availableIngredients,
    unitOptions,
    editedIngredients,
    handleIngredientsChange,
    qualityTemplates
  ]);

  // Handle save
  const handleSave = useCallback(async () => {
    if (!recipe) return;
    
    try {
      // Create updated recipe object with both edited values and original values
      const updatedRecipe: RecipeResponse = {
        ...recipe,
        ...editedRecipe,
        // Update ingredients if they were edited
        ingredients: mode === 'edit' ? editedIngredients : recipe.ingredients
      };
      
      if (onSave) {
        await onSave(updatedRecipe);
      }
      
      // Reset edited state after save
      setEditedRecipe({});
      setEditedIngredients([]);
    } catch (error) {
      console.error('Error saving recipe:', error);
      throw error;
    }
  }, [recipe, editedRecipe, editedIngredients, onSave, mode]);

  return (
    <EditViewModal
      isOpen={isOpen}
      onClose={onClose}
      mode={mode}
      onModeChange={onModeChange}
      title={recipe?.name || ''}
      subtitle={recipe?.description || ''}
      statusIndicator={recipe ? getRecipeStatusConfig(recipe) : undefined}
      size="xl"
      sections={sections}
      onFieldChange={handleFieldChange}
      showDefaultActions={true}
      onSave={handleSave}
      loading={isLoading || isSaving}
    />
  );
};

export default RecipeViewEditModal;