import React, { useState, useMemo } from 'react';
import { ChefHat, Package, Clock, Star, Plus, Trash2, Settings, FileText } from 'lucide-react';
import { AddModal } from '../../ui/AddModal/AddModal';
import { RecipeCreate, RecipeIngredientCreate, MeasurementUnit } from '../../../api/types/recipes';
import { useIngredients } from '../../../api/hooks/inventory';
import { useCurrentTenant } from '../../../stores/tenant.store';
import { statusColors } from '../../../styles/colors';

interface CreateRecipeModalProps {
  isOpen: boolean;
  onClose: () => void;
  onCreateRecipe?: (recipeData: RecipeCreate) => Promise<void>;
}

/**
 * CreateRecipeModal - Modal for creating a new recipe
 * Comprehensive form for adding new recipes
 */
// Custom Ingredients Component for AddModal
const IngredientsComponent: React.FC<{
  value: RecipeIngredientCreate[] | undefined | null;
  onChange: (value: RecipeIngredientCreate[]) => void;
  availableIngredients: Array<{value: string; label: string}>;
  unitOptions: Array<{value: MeasurementUnit; label: string}>;
}> = ({ value, onChange, availableIngredients, unitOptions }) => {
  // Ensure value is always an array
  const ingredientsArray = Array.isArray(value) ? value : [];
  
  const addIngredient = () => {
    const newIngredient: RecipeIngredientCreate = {
      ingredient_id: '',
      quantity: 1,
      unit: MeasurementUnit.GRAMS,
      ingredient_order: ingredientsArray.length + 1,
      is_optional: false
    };
    onChange([...ingredientsArray, newIngredient]);
  };

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

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

  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
        </button>
      </div>

      <div className="space-y-3 max-h-64 overflow-y-auto">
        {ingredientsArray.map((ingredient, index) => (
          <div key={index} className="p-3 border border-[var(--border-secondary)] rounded-lg bg-[var(--bg-secondary)]/50 space-y-3">
            <div className="flex items-center justify-between">
              <span className="text-sm font-medium text-[var(--text-primary)]">Ingrediente #{index + 1}</span>
              <button
                type="button"
                onClick={() => removeIngredient(index)}
                disabled={ingredientsArray.length <= 1}
                className="p-1 text-red-500 hover:text-red-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
              >
                <Trash2 className="w-4 h-4" />
              </button>
            </div>

            <div className="grid grid-cols-1 sm:grid-cols-3 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-2 py-1.5 border border-[var(--border-secondary)] rounded focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)] text-sm"
                >
                  <option value="">Seleccionar...</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-2 py-1.5 border border-[var(--border-secondary)] rounded 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"
                />
              </div>
            </div>

            <div className="grid grid-cols-2 gap-3">
              <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-2 py-1.5 border border-[var(--border-secondary)] rounded 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 className="flex items-center justify-center">
                <label className="flex items-center gap-2 text-sm text-[var(--text-primary)] cursor-pointer">
                  <input
                    type="checkbox"
                    checked={ingredient.is_optional}
                    onChange={(e) => updateIngredient(index, 'is_optional', e.target.checked)}
                    className="w-4 h-4 text-[var(--color-primary)] border-[var(--border-secondary)] rounded focus:ring-[var(--color-primary)]"
                  />
                  Opcional
                </label>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

export const CreateRecipeModal: React.FC<CreateRecipeModalProps> = ({
  isOpen,
  onClose,
  onCreateRecipe
}) => {
  const [ingredientsList, setIngredientsList] = useState<RecipeIngredientCreate[]>([{
    ingredient_id: '',
    quantity: 1,
    unit: MeasurementUnit.GRAMS,
    ingredient_order: 1,
    is_optional: false
  }]);
  const [loading, setLoading] = useState(false);

  // Get tenant and fetch inventory data
  const currentTenant = useCurrentTenant();
  const tenantId = currentTenant?.id || '';

  // Fetch inventory items to populate product and ingredient selectors
  const {
    data: inventoryItems = [],
    isLoading: inventoryLoading
  } = useIngredients(tenantId, {});

  // Separate finished products and ingredients
  const finishedProducts = useMemo(() =>
    (inventoryItems || [])
      .filter(item => item.product_type === 'finished_product')
      .map(product => ({
        value: product.id,
        label: `${product.name} (${product.category || 'Sin categoría'})`
      })),
    [inventoryItems]
  );

  // Available ingredients for recipe ingredients
  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]
  );

  // Category options
  const categoryOptions = [
    { value: 'bread', label: 'Pan' },
    { value: 'pastry', label: 'Bollería' },
    { value: 'cake', label: 'Tarta' },
    { value: 'cookie', label: 'Galleta' },
    { value: 'muffin', label: 'Muffin' },
    { value: 'savory', label: 'Salado' },
    { value: 'desserts', label: 'Postres' },
    { value: 'specialty', label: 'Especialidad' },
    { value: 'other', label: 'Otro' }
  ];

  // Cuisine type options
  const cuisineTypeOptions = [
    { value: 'french', label: 'Francés' },
    { value: 'spanish', label: 'Español' },
    { value: 'italian', label: 'Italiano' },
    { value: 'german', label: 'Alemán' },
    { value: 'american', label: 'Americano' },
    { value: 'artisanal', label: 'Artesanal' },
    { value: 'traditional', label: 'Tradicional' },
    { value: 'modern', label: 'Moderno' }
  ];

  // Unit options
  const unitOptions = [
    { value: MeasurementUnit.UNITS, label: 'Unidades' },
    { value: MeasurementUnit.PIECES, label: 'Piezas' },
    { value: MeasurementUnit.GRAMS, label: 'Gramos' },
    { value: MeasurementUnit.KILOGRAMS, label: 'Kilogramos' },
    { value: MeasurementUnit.MILLILITERS, label: 'Mililitros' },
    { value: MeasurementUnit.LITERS, label: 'Litros' }
  ];

  // Month options for seasonal recipes
  const monthOptions = [
    { value: 1, label: 'Enero' },
    { value: 2, label: 'Febrero' },
    { value: 3, label: 'Marzo' },
    { value: 4, label: 'Abril' },
    { value: 5, label: 'Mayo' },
    { value: 6, label: 'Junio' },
    { value: 7, label: 'Julio' },
    { value: 8, label: 'Agosto' },
    { value: 9, label: 'Septiembre' },
    { value: 10, label: 'Octubre' },
    { value: 11, label: 'Noviembre' },
    { value: 12, label: 'Diciembre' }
  ];

  const validateIngredients = (ingredients: RecipeIngredientCreate[]): string | null => {
    if (!ingredients || ingredients.length === 0) {
      return 'Debe agregar al menos un ingrediente';
    }

    const emptyIngredients = ingredients.filter(ing => !ing.ingredient_id.trim());
    if (emptyIngredients.length > 0) {
      return 'Todos los ingredientes deben tener un ingrediente seleccionado';
    }

    const invalidQuantities = ingredients.filter(ing => ing.quantity <= 0);
    if (invalidQuantities.length > 0) {
      return 'Todas las cantidades deben ser mayor que 0';
    }

    return null;
  };

  const handleSave = async (formData: Record<string, any>) => {
    // Debug: Log the ingredients array to understand what's being submitted
    console.log('=== Recipe Save Debug ===');
    console.log('formData.ingredients:', JSON.stringify(formData.ingredients, null, 2));
    console.log('Type of formData.ingredients:', typeof formData.ingredients);
    console.log('Is array:', Array.isArray(formData.ingredients));
    console.log('========================');

    // Validate ingredients
    const ingredientError = validateIngredients(formData.ingredients || []);
    if (ingredientError) {
      throw new Error(ingredientError);
    }

    // Validate seasonal dates if seasonal is enabled
    if (formData.is_seasonal && (!formData.season_start_month || !formData.season_end_month)) {
      throw new Error('Para recetas estacionales, debe especificar los meses de inicio y fin');
    }

    // Validate batch sizes
    if (formData.minimum_batch_size && formData.maximum_batch_size && formData.minimum_batch_size > formData.maximum_batch_size) {
      throw new Error('El tamaño mínimo de lote no puede ser mayor que el máximo');
    }

    setLoading(true);
    try {
      // Generate recipe code if not provided
      const recipeCode = formData.recipe_code ||
        formData.name.substring(0, 3).toUpperCase() +
        String(Date.now()).slice(-3);

      // Calculate total time including rest time
      const totalTime = (Number(formData.prep_time_minutes) || 0) +
                       (Number(formData.cook_time_minutes) || 0) +
                       (Number(formData.rest_time_minutes) || 0);

      // Filter and validate ingredients before creating the recipe
      const validIngredients = (formData.ingredients || [])
        .filter((ing: RecipeIngredientCreate) => ing.ingredient_id && ing.ingredient_id.trim() !== '')
        .map((ing: RecipeIngredientCreate, index: number) => ({
          ...ing,
          ingredient_order: index + 1
        }));

      // Ensure we have at least one valid ingredient
      if (validIngredients.length === 0) {
        throw new Error('Debe agregar al menos un ingrediente válido con un ingrediente seleccionado');
      }

      const recipeData: RecipeCreate = {
        name: formData.name,
        recipe_code: recipeCode,
        version: formData.version || '1.0',
        finished_product_id: formData.finished_product_id,
        description: formData.description || '',
        category: formData.category,
        cuisine_type: formData.cuisine_type || '',
        difficulty_level: Number(formData.difficulty_level),
        yield_quantity: Number(formData.yield_quantity),
        yield_unit: formData.yield_unit as MeasurementUnit,
        prep_time_minutes: Number(formData.prep_time_minutes) || 0,
        cook_time_minutes: Number(formData.cook_time_minutes) || 0,
        total_time_minutes: totalTime,
        rest_time_minutes: Number(formData.rest_time_minutes) || 0,
        target_margin_percentage: Number(formData.target_margin_percentage) || 30,
        instructions: formData.instructions_text ? { steps: formData.instructions_text } : null,
        preparation_notes: formData.preparation_notes || '',
        storage_instructions: formData.storage_instructions || '',
        quality_check_configuration: null,
        serves_count: Number(formData.serves_count) || 1,
        is_seasonal: formData.is_seasonal || false,
        season_start_month: formData.is_seasonal ? Number(formData.season_start_month) : undefined,
        season_end_month: formData.is_seasonal ? Number(formData.season_end_month) : undefined,
        is_signature_item: formData.is_signature_item || false,
        batch_size_multiplier: Number(formData.batch_size_multiplier) || 1.0,
        minimum_batch_size: formData.minimum_batch_size ? Number(formData.minimum_batch_size) : undefined,
        maximum_batch_size: formData.maximum_batch_size ? Number(formData.maximum_batch_size) : undefined,
        optimal_production_temperature: formData.optimal_production_temperature ? Number(formData.optimal_production_temperature) : undefined,
        optimal_humidity: formData.optimal_humidity ? Number(formData.optimal_humidity) : undefined,
        allergen_info: formData.allergen_info_text ? { allergens: formData.allergen_info_text.split(',').map((a: string) => a.trim()) } : null,
        dietary_tags: formData.dietary_tags_text ? { tags: formData.dietary_tags_text.split(',').map((t: string) => t.trim()) } : null,
        nutritional_info: formData.nutritional_info_text ? { info: formData.nutritional_info_text } : null,
        // Use the validated ingredients list
        ingredients: validIngredients
      };

      // Debug: Log the final payload before sending to API
      console.log('=== Final Recipe Payload ===');
      console.log('recipeData:', JSON.stringify(recipeData, null, 2));
      console.log('ingredients count:', recipeData.ingredients.length);
      console.log('===========================');

      if (onCreateRecipe) {
        await onCreateRecipe(recipeData);
      }

      // Reset ingredients list (AddModal will handle form reset)
      setIngredientsList([{
        ingredient_id: '',
        quantity: 1,
        unit: MeasurementUnit.GRAMS,
        ingredient_order: 1,
        is_optional: false
      }]);
    } catch (error) {
      console.error('Error creating recipe:', error);
      throw error; // Let AddModal handle error display
    } finally {
      setLoading(false);
    }
  };

  const statusConfig = {
    color: statusColors.inProgress.primary,
    text: 'Nueva Receta',
    icon: Plus,
    isCritical: false,
    isHighlight: true
  };

  const sections = [
    {
      title: 'Información Básica',
      icon: ChefHat,
      fields: [
        {
          label: 'Nombre',
          name: 'name',
          type: 'text' as const,
          required: true,
          placeholder: 'Ej: Pan de molde integral',
          validation: (value: string | number) => {
            const str = String(value).trim();
            return str.length < 2 ? 'El nombre debe tener al menos 2 caracteres' : null;
          }
        },
        {
          label: 'Código de receta',
          name: 'recipe_code',
          type: 'text' as const,
          placeholder: 'Ej: PAN001 (opcional)'
        },
        {
          label: 'Versión',
          name: 'version',
          type: 'text' as const,
          defaultValue: '1.0',
          placeholder: '1.0'
        },
        {
          label: 'Descripción',
          name: 'description',
          type: 'textarea' as const,
          placeholder: 'Descripción de la receta...',
          span: 2
        },
        {
          label: 'Categoría',
          name: 'category',
          type: 'select' as const,
          required: true,
          options: categoryOptions,
          placeholder: 'Seleccionar categoría...'
        },
        {
          label: 'Producto terminado',
          name: 'finished_product_id',
          type: 'select' as const,
          required: true,
          options: finishedProducts,
          placeholder: 'Seleccionar producto...'
        },
        {
          label: 'Tipo de cocina',
          name: 'cuisine_type',
          type: 'select' as const,
          options: cuisineTypeOptions,
          placeholder: 'Seleccionar tipo...'
        },
        {
          label: 'Nivel de dificultad',
          name: 'difficulty_level',
          type: 'select' as const,
          required: true,
          defaultValue: 1,
          options: [
            { 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' }
          ]
        }
      ]
    },
    {
      title: 'Rendimiento y Tiempos',
      icon: Clock,
      fields: [
        {
          label: 'Cantidad de rendimiento',
          name: 'yield_quantity',
          type: 'number' as const,
          required: true,
          defaultValue: 1,
          validation: (value: string | number) => {
            const num = Number(value);
            return num <= 0 ? 'La cantidad debe ser mayor a 0' : null;
          }
        },
        {
          label: 'Unidad de rendimiento',
          name: 'yield_unit',
          type: 'select' as const,
          required: true,
          options: unitOptions,
          defaultValue: MeasurementUnit.UNITS
        },
        {
          label: 'Porciones',
          name: 'serves_count',
          type: 'number' as const,
          defaultValue: 1,
          validation: (value: string | number) => {
            const num = Number(value);
            return num <= 0 ? 'Las porciones deben ser mayor a 0' : null;
          }
        },
        {
          label: 'Tiempo de preparación (min)',
          name: 'prep_time_minutes',
          type: 'number' as const,
          defaultValue: 0,
          helpText: 'Tiempo de preparación de ingredientes'
        },
        {
          label: 'Tiempo de cocción (min)',
          name: 'cook_time_minutes',
          type: 'number' as const,
          defaultValue: 0,
          helpText: 'Tiempo de horneado o cocción'
        },
        {
          label: 'Tiempo de reposo (min)',
          name: 'rest_time_minutes',
          type: 'number' as const,
          defaultValue: 0,
          helpText: 'Tiempo de fermentación o reposo'
        }
      ]
    },
    {
      title: 'Configuración Especial',
      icon: Star,
      fields: [
        {
          label: 'Receta estacional',
          name: 'is_seasonal',
          type: 'select' as const,
          options: [
            { value: false, label: 'No' },
            { value: true, label: 'Sí' }
          ],
          defaultValue: false
        },
        {
          label: 'Mes de inicio',
          name: 'season_start_month',
          type: 'select' as const,
          options: monthOptions,
          placeholder: 'Seleccionar mes...'
        },
        {
          label: 'Mes de fin',
          name: 'season_end_month',
          type: 'select' as const,
          options: monthOptions,
          placeholder: 'Seleccionar mes...'
        },
        {
          label: 'Receta estrella',
          name: 'is_signature_item',
          type: 'select' as const,
          options: [
            { value: false, label: 'No' },
            { value: true, label: 'Sí' }
          ],
          defaultValue: false
        },
        {
          label: 'Margen objetivo (%)',
          name: 'target_margin_percentage',
          type: 'number' as const,
          defaultValue: 30,
          helpText: 'Margen de beneficio objetivo para esta receta'
        }
      ]
    },
    {
      title: 'Configuración de Producción',
      icon: Settings,
      fields: [
        {
          label: 'Multiplicador de lote',
          name: 'batch_size_multiplier',
          type: 'number' as const,
          defaultValue: 1.0,
          helpText: 'Factor de escala para producción'
        },
        {
          label: 'Tamaño mínimo de lote',
          name: 'minimum_batch_size',
          type: 'number' as const,
          helpText: 'Cantidad mínima recomendada'
        },
        {
          label: 'Tamaño máximo de lote',
          name: 'maximum_batch_size',
          type: 'number' as const,
          helpText: 'Cantidad máxima recomendada'
        },
        {
          label: 'Temperatura óptima (°C)',
          name: 'optimal_production_temperature',
          type: 'number' as const,
          helpText: 'Temperatura ideal de producción'
        },
        {
          label: 'Humedad óptima (%)',
          name: 'optimal_humidity',
          type: 'number' as const,
          helpText: 'Humedad ideal de producción'
        }
      ]
    },
    {
      title: 'Instrucciones',
      icon: FileText,
      fields: [
        {
          label: 'Notas de preparación',
          name: 'preparation_notes',
          type: 'textarea' as const,
          placeholder: 'Instrucciones detalladas de preparación...',
          span: 2,
          helpText: 'Pasos detallados para la preparación'
        },
        {
          label: 'Instrucciones de almacenamiento',
          name: 'storage_instructions',
          type: 'textarea' as const,
          placeholder: 'Como conservar el producto terminado...',
          span: 2,
          helpText: 'Condiciones de almacenamiento del producto final'
        }
      ]
    },
    {
      title: 'Ingredientes',
      icon: Package,
      columns: 1,
      fields: [
        {
          label: 'Lista de ingredientes',
          name: 'ingredients',
          type: 'component' as const,
          component: IngredientsComponent,
          componentProps: {
            availableIngredients,
            unitOptions
          },
          defaultValue: ingredientsList,
          span: 2,
          helpText: 'Agrega los ingredientes necesarios para esta receta'
        }
      ]
    },
    {
      title: 'Instrucciones Detalladas',
      icon: FileText,
      columns: 1,
      fields: [
        {
          label: 'Instrucciones de preparación',
          name: 'instructions_text',
          type: 'textarea' as const,
          placeholder: 'Describir paso a paso el proceso de elaboración...',
          helpText: 'Instrucciones detalladas para la preparación',
          span: 2
        }
      ]
    },
    {
      title: 'Información Nutricional',
      icon: Package,
      columns: 1,
      fields: [
        {
          label: 'Información de alérgenos',
          name: 'allergen_info_text',
          type: 'text' as const,
          placeholder: 'Ej: Gluten, Lácteos, Huevos',
          helpText: 'Separar con comas los alérgenos presentes'
        },
        {
          label: 'Etiquetas dietéticas',
          name: 'dietary_tags_text',
          type: 'text' as const,
          placeholder: 'Ej: Vegano, Sin gluten, Orgánico',
          helpText: 'Separar con comas las etiquetas dietéticas'
        },
        {
          label: 'Información nutricional',
          name: 'nutritional_info_text',
          type: 'textarea' as const,
          placeholder: 'Calorías, proteínas, carbohidratos, etc.',
          helpText: 'Información nutricional por porción'
        }
      ]
    }
  ];

  return (
    <AddModal
      isOpen={isOpen}
      onClose={onClose}
      title="Nueva Receta"
      subtitle="Crear una nueva receta para la panadería"
      statusIndicator={statusConfig}
      sections={sections}
      size="2xl"
      loading={loading}
      onSave={handleSave}
      initialData={{ ingredients: ingredientsList }}
    />
  );
};

export default CreateRecipeModal;