import React from 'react';
import { Package, Plus, Trash2 } from 'lucide-react';
import type { WizardStepProps } from '../../../ui/WizardModal/WizardModal';
import type { RecipeCreate, RecipeIngredientCreate, MeasurementUnit } from '../../../../api/types/recipes';

interface RecipeIngredientsStepProps extends WizardStepProps {
  recipeData: Partial<RecipeCreate>;
  onUpdate: (data: Partial<RecipeCreate>) => void;
  availableIngredients: Array<{ value: string; label: string }>;
  unitOptions: Array<{ value: MeasurementUnit; label: string }>;
}

export const RecipeIngredientsStep: React.FC<RecipeIngredientsStepProps> = ({
  recipeData,
  onUpdate,
  onNext,
  onBack,
  availableIngredients,
  unitOptions
}) => {
  const ingredients = recipeData.ingredients || [];

  const addIngredient = () => {
    const newIngredient: RecipeIngredientCreate = {
      ingredient_id: '',
      quantity: 1,
      unit: 'grams' as MeasurementUnit,
      ingredient_order: ingredients.length + 1,
      is_optional: false
    };
    onUpdate({ ...recipeData, ingredients: [...ingredients, newIngredient] });
  };

  const removeIngredient = (index: number) => {
    if (ingredients.length > 1) {
      const updated = ingredients.filter((_, i) => i !== index);
      onUpdate({ ...recipeData, ingredients: updated });
    }
  };

  const updateIngredient = (index: number, field: keyof RecipeIngredientCreate, value: any) => {
    const updated = ingredients.map((ing, i) =>
      i === index ? { ...ing, [field]: value } : ing
    );
    onUpdate({ ...recipeData, ingredients: updated });
  };

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    onNext();
  };

  // Validation: at least one ingredient with valid data
  const isValid =
    ingredients.length > 0 &&
    ingredients.some((ing) => ing.ingredient_id && ing.ingredient_id.trim() !== '' && ing.quantity > 0);

  return (
    <form onSubmit={handleSubmit} className="space-y-6">
      {/* Header */}
      <div className="flex items-start gap-4 pb-4 border-b border-[var(--border-secondary)]">
        <div className="w-12 h-12 rounded-full bg-[var(--color-primary)]/10 flex items-center justify-center flex-shrink-0">
          <Package className="w-6 h-6 text-[var(--color-primary)]" />
        </div>
        <div className="flex-1">
          <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-1">
            Ingredientes
          </h3>
          <p className="text-sm text-[var(--text-secondary)]">
            Agrega los ingredientes necesarios para esta receta
          </p>
        </div>
        <button
          type="button"
          onClick={addIngredient}
          className="px-4 py-2 bg-[var(--color-primary)] text-white rounded-lg hover:bg-[var(--color-primary-dark)] transition-colors flex items-center gap-2 text-sm font-medium"
        >
          <Plus className="w-4 h-4" />
          Agregar
        </button>
      </div>

      {/* Ingredients List */}
      <div className="space-y-4 max-h-[450px] overflow-y-auto pr-2">
        {ingredients.length === 0 ? (
          <div className="text-center py-12 border-2 border-dashed border-[var(--border-secondary)] rounded-lg">
            <Package className="w-12 h-12 text-[var(--text-tertiary)] mx-auto mb-3" />
            <p className="text-sm text-[var(--text-secondary)] mb-4">
              No hay ingredientes agregados
            </p>
            <button
              type="button"
              onClick={addIngredient}
              className="px-4 py-2 bg-[var(--color-primary)] text-white rounded-lg hover:bg-[var(--color-primary-dark)] transition-colors inline-flex items-center gap-2"
            >
              <Plus className="w-4 h-4" />
              Agregar Primer Ingrediente
            </button>
          </div>
        ) : (
          ingredients.map((ingredient, index) => (
            <div
              key={index}
              className="p-4 border border-[var(--border-secondary)] rounded-lg bg-[var(--bg-secondary)]/50 space-y-3"
            >
              {/* Header */}
              <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={ingredients.length <= 1}
                  className="p-1.5 text-red-500 hover:text-red-700 hover:bg-red-50 rounded disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
                  title={ingredients.length <= 1 ? 'Debe haber al menos un ingrediente' : 'Eliminar'}
                >
                  <Trash2 className="w-4 h-4" />
                </button>
              </div>

              {/* Fields */}
              <div className="grid grid-cols-1 gap-3">
                {/* Ingredient Selection */}
                <div>
                  <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">
                    Ingrediente <span className="text-red-500">*</span>
                  </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-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)] text-sm"
                    required
                  >
                    <option value="">Seleccionar...</option>
                    {availableIngredients.map((ing) => (
                      <option key={ing.value} value={ing.value}>
                        {ing.label}
                      </option>
                    ))}
                  </select>
                </div>

                <div className="grid grid-cols-3 gap-3">
                  {/* Quantity */}
                  <div>
                    <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">
                      Cantidad <span className="text-red-500">*</span>
                    </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-lg 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"
                      required
                    />
                  </div>

                  {/* Unit */}
                  <div>
                    <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">
                      Unidad <span className="text-red-500">*</span>
                    </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-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] bg-[var(--bg-primary)] text-[var(--text-primary)] text-sm"
                      required
                    >
                      {unitOptions.map((unit) => (
                        <option key={unit.value} value={unit.value}>
                          {unit.label}
                        </option>
                      ))}
                    </select>
                  </div>

                  {/* Optional Checkbox */}
                  <div className="flex items-end">
                    <label className="flex items-center gap-2 text-sm text-[var(--text-primary)] cursor-pointer pb-2">
                      <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>

      {/* Validation Message */}
      {!isValid && ingredients.length > 0 && (
        <div className="p-3 bg-[var(--color-warning)]/10 border border-[var(--color-warning)]/30 rounded-lg">
          <p className="text-sm text-[var(--text-primary)]">
            <span className="font-medium">⚠️ Atención:</span> Asegúrate de seleccionar al menos un ingrediente con cantidad válida.
          </p>
        </div>
      )}

      {/* Hidden submit button for form handling */}
      <button type="submit" className="hidden" disabled={!isValid} />
    </form>
  );
};
