import React from 'react';
import { FileText, CheckCircle2, Package, Clock, Settings } from 'lucide-react';
import type { WizardStepProps } from '../../../ui/WizardModal/WizardModal';
import type { RecipeCreate } from '../../../../api/types/recipes';

interface RecipeReviewStepProps extends WizardStepProps {
  recipeData: Partial<RecipeCreate>;
  onUpdate: (data: Partial<RecipeCreate>) => void;
  ingredientNames: Map<string, string>;
}

export const RecipeReviewStep: React.FC<RecipeReviewStepProps> = ({
  recipeData,
  onUpdate,
  onNext,
  onBack,
  ingredientNames
}) => {
  const handleFieldChange = (field: keyof RecipeCreate, value: any) => {
    onUpdate({ ...recipeData, [field]: value });
  };

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

  // Calculate costs if available (future enhancement)
  const totalIngredients = recipeData.ingredients?.length || 0;
  const validIngredients = recipeData.ingredients?.filter(ing => ing.ingredient_id && ing.quantity > 0).length || 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">
          <FileText 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">
            Instrucciones y Revisión
          </h3>
          <p className="text-sm text-[var(--text-secondary)]">
            Completa las instrucciones y revisa la receta antes de guardar
          </p>
        </div>
      </div>

      {/* Recipe Summary */}
      <div className="p-4 bg-gradient-to-r from-[var(--color-primary)]/5 to-[var(--color-primary)]/10 border border-[var(--color-primary)]/20 rounded-lg">
        <h4 className="text-sm font-semibold text-[var(--text-primary)] mb-3 flex items-center gap-2">
          <CheckCircle2 className="w-4 h-4 text-[var(--color-success)]" />
          Resumen de la Receta
        </h4>

        <div className="grid grid-cols-2 gap-4">
          {/* Product Info */}
          <div className="space-y-2">
            <div className="flex items-start gap-2">
              <Package className="w-4 h-4 text-[var(--text-secondary)] mt-0.5 flex-shrink-0" />
              <div>
                <p className="text-xs text-[var(--text-tertiary)]">Producto</p>
                <p className="text-sm font-medium text-[var(--text-primary)]">{recipeData.name || 'Sin nombre'}</p>
              </div>
            </div>
            <div className="flex items-start gap-2">
              <Package className="w-4 h-4 text-[var(--text-secondary)] mt-0.5 flex-shrink-0" />
              <div>
                <p className="text-xs text-[var(--text-tertiary)]">Categoría</p>
                <p className="text-sm font-medium text-[var(--text-primary)]">{recipeData.category || 'No especificada'}</p>
              </div>
            </div>
            <div className="flex items-start gap-2">
              <Package className="w-4 h-4 text-[var(--text-secondary)] mt-0.5 flex-shrink-0" />
              <div>
                <p className="text-xs text-[var(--text-tertiary)]">Ingredientes</p>
                <p className="text-sm font-medium text-[var(--text-primary)]">{validIngredients} de {totalIngredients}</p>
              </div>
            </div>
          </div>

          {/* Production Info */}
          <div className="space-y-2">
            <div className="flex items-start gap-2">
              <Clock className="w-4 h-4 text-[var(--text-secondary)] mt-0.5 flex-shrink-0" />
              <div>
                <p className="text-xs text-[var(--text-tertiary)]">Tiempo Total</p>
                <p className="text-sm font-medium text-[var(--text-primary)]">
                  {(recipeData.prep_time_minutes || 0) + (recipeData.cook_time_minutes || 0) + (recipeData.rest_time_minutes || 0)} min
                </p>
              </div>
            </div>
            <div className="flex items-start gap-2">
              <Settings className="w-4 h-4 text-[var(--text-secondary)] mt-0.5 flex-shrink-0" />
              <div>
                <p className="text-xs text-[var(--text-tertiary)]">Rendimiento</p>
                <p className="text-sm font-medium text-[var(--text-primary)]">
                  {recipeData.yield_quantity || 0} {recipeData.yield_unit || 'unidades'}
                </p>
              </div>
            </div>
            <div className="flex items-start gap-2">
              <Settings className="w-4 h-4 text-[var(--text-secondary)] mt-0.5 flex-shrink-0" />
              <div>
                <p className="text-xs text-[var(--text-tertiary)]">Dificultad</p>
                <p className="text-sm font-medium text-[var(--text-primary)]">
                  Nivel {recipeData.difficulty_level || 1}/5
                </p>
              </div>
            </div>
          </div>
        </div>

        {/* Ingredients Preview */}
        {recipeData.ingredients && recipeData.ingredients.length > 0 && (
          <div className="mt-3 pt-3 border-t border-[var(--border-secondary)]">
            <p className="text-xs font-medium text-[var(--text-primary)] mb-2">Lista de Ingredientes:</p>
            <div className="flex flex-wrap gap-2">
              {recipeData.ingredients.map((ing, idx) => {
                const name = ingredientNames.get(ing.ingredient_id) || 'Desconocido';
                return (
                  <span
                    key={idx}
                    className="inline-flex items-center gap-1 px-2 py-1 bg-[var(--bg-secondary)] border border-[var(--border-secondary)] rounded text-xs text-[var(--text-primary)]"
                  >
                    <span className="font-medium">{name}</span>
                    <span className="text-[var(--text-tertiary)]">({ing.quantity} {ing.unit})</span>
                  </span>
                );
              })}
            </div>
          </div>
        )}
      </div>

      {/* Instructions Section */}
      <div className="space-y-4">
        <h4 className="text-sm font-semibold text-[var(--text-primary)]">
          Instrucciones de Preparación
        </h4>

        {/* Preparation Notes */}
        <div>
          <label className="block text-sm font-medium text-[var(--text-primary)] mb-1.5">
            Notas de Preparación
          </label>
          <textarea
            value={recipeData.preparation_notes || ''}
            onChange={(e) => handleFieldChange('preparation_notes', e.target.value)}
            placeholder="Pasos detallados para la preparación de la receta..."
            rows={4}
            className="w-full px-4 py-2.5 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)] resize-none"
          />
          <p className="mt-1 text-xs text-[var(--text-tertiary)]">
            Describe el proceso paso a paso
          </p>
        </div>

        {/* Storage Instructions */}
        <div>
          <label className="block text-sm font-medium text-[var(--text-primary)] mb-1.5">
            Instrucciones de Almacenamiento
          </label>
          <textarea
            value={recipeData.storage_instructions || ''}
            onChange={(e) => handleFieldChange('storage_instructions', e.target.value)}
            placeholder="Cómo conservar el producto terminado..."
            rows={2}
            className="w-full px-4 py-2.5 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)] resize-none"
          />
          <p className="mt-1 text-xs text-[var(--text-tertiary)]">
            Condiciones de almacenamiento recomendadas
          </p>
        </div>
      </div>

      {/* Nutritional Information (Optional) */}
      <div className="space-y-4">
        <h4 className="text-sm font-semibold text-[var(--text-primary)]">
          Información Nutricional (Opcional)
        </h4>

        <div className="grid grid-cols-1 gap-4">
          {/* Allergens */}
          <div>
            <label className="block text-sm font-medium text-[var(--text-primary)] mb-1.5">
              Alérgenos
            </label>
            <input
              type="text"
              value={recipeData.allergen_info ? (recipeData.allergen_info as any).allergens?.join(', ') : ''}
              onChange={(e) => handleFieldChange('allergen_info', e.target.value ? { allergens: e.target.value.split(',').map((a: string) => a.trim()) } : null)}
              placeholder="Ej: Gluten, Lácteos, Huevos"
              className="w-full px-4 py-2.5 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)]"
            />
            <p className="mt-1 text-xs text-[var(--text-tertiary)]">
              Separar con comas
            </p>
          </div>

          {/* Dietary Tags */}
          <div>
            <label className="block text-sm font-medium text-[var(--text-primary)] mb-1.5">
              Etiquetas Dietéticas
            </label>
            <input
              type="text"
              value={recipeData.dietary_tags ? (recipeData.dietary_tags as any).tags?.join(', ') : ''}
              onChange={(e) => handleFieldChange('dietary_tags', e.target.value ? { tags: e.target.value.split(',').map((t: string) => t.trim()) } : null)}
              placeholder="Ej: Vegano, Sin gluten, Orgánico"
              className="w-full px-4 py-2.5 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)]"
            />
            <p className="mt-1 text-xs text-[var(--text-tertiary)]">
              Separar con comas
            </p>
          </div>
        </div>
      </div>

      {/* Ready to Save Message */}
      <div className="p-4 bg-[var(--color-success)]/10 border border-[var(--color-success)]/30 rounded-lg">
        <p className="text-sm text-[var(--text-primary)] flex items-center gap-2">
          <CheckCircle2 className="w-4 h-4 text-[var(--color-success)]" />
          <span>
            <span className="font-medium">¡Listo para guardar!</span> Revisa la información y haz clic en "Completar" para crear la receta.
          </span>
        </p>
      </div>

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