import React, { useState, useEffect } from 'react';
import { WizardStep, WizardStepProps } from '../../../ui/WizardModal/WizardModal';
import { ChefHat, Package, ClipboardCheck, CheckCircle2, Loader2, Plus, X, Search } from 'lucide-react';
import { useTenant } from '../../../../stores/tenant.store';
import { recipesService } from '../../../../api/services/recipes';
import { inventoryService } from '../../../../api/services/inventory';
import { IngredientResponse } from '../../../../api/types/inventory';
import { RecipeCreate, RecipeIngredientCreate, MeasurementUnit } from '../../../../api/types/recipes';
import { showToast } from '../../../../utils/toast';

interface WizardDataProps extends WizardStepProps {
  data: Record<string, any>;
  onDataChange: (data: Record<string, any>) => void;
}

const RecipeDetailsStep: React.FC<WizardDataProps> = ({ data, onDataChange, onNext }) => {
  const { currentTenant } = useTenant();
  const [recipeData, setRecipeData] = useState({
    name: data.name || '',
    category: data.category || 'bread',
    yieldQuantity: data.yieldQuantity || '',
    yieldUnit: data.yieldUnit || 'units',
    prepTime: data.prepTime || '',
    finishedProductId: data.finishedProductId || '',
    instructions: data.instructions || '',
  });
  const [finishedProducts, setFinishedProducts] = useState<IngredientResponse[]>([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    fetchFinishedProducts();
  }, []);

  const fetchFinishedProducts = async () => {
    if (!currentTenant?.id) return;
    setLoading(true);
    try {
      const result = await inventoryService.getIngredients(currentTenant.id, {
        category: 'finished_product'
      });
      setFinishedProducts(result);
    } catch (err) {
      console.error('Error loading finished products:', err);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="space-y-6">
      <div className="text-center pb-4 border-b border-[var(--border-primary)]">
        <ChefHat className="w-12 h-12 mx-auto mb-3 text-[var(--color-primary)]" />
        <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-2">Detalles de la Receta</h3>
      </div>
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div className="md:col-span-2">
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">Nombre *</label>
          <input
            type="text"
            value={recipeData.name}
            onChange={(e) => setRecipeData({ ...recipeData, name: e.target.value })}
            placeholder="Ej: Baguette Tradicional"
            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)]"
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">Categoría *</label>
          <select
            value={recipeData.category}
            onChange={(e) => setRecipeData({ ...recipeData, category: 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)]"
          >
            <option value="bread">Pan</option>
            <option value="pastry">Pastelería</option>
            <option value="cake">Repostería</option>
            <option value="cookie">Galletas</option>
            <option value="other">Otro</option>
          </select>
        </div>
        <div>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">Producto Terminado *</label>
          <select
            value={recipeData.finishedProductId}
            onChange={(e) => setRecipeData({ ...recipeData, finishedProductId: 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)]"
            disabled={loading}
          >
            <option value="">Seleccionar producto...</option>
            {finishedProducts.map(product => (
              <option key={product.id} value={product.id}>{product.name}</option>
            ))}
          </select>
        </div>
        <div>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">Rendimiento *</label>
          <input
            type="number"
            value={recipeData.yieldQuantity}
            onChange={(e) => setRecipeData({ ...recipeData, yieldQuantity: e.target.value })}
            placeholder="12"
            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)]"
            min="1"
          />
        </div>
        <div>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">Unidad *</label>
          <select
            value={recipeData.yieldUnit}
            onChange={(e) => setRecipeData({ ...recipeData, yieldUnit: 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)]"
          >
            <option value="units">Unidades</option>
            <option value="kg">Kilogramos</option>
            <option value="g">Gramos</option>
            <option value="l">Litros</option>
            <option value="ml">Mililitros</option>
            <option value="pieces">Piezas</option>
          </select>
        </div>
        <div>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">Tiempo de Preparación (min)</label>
          <input
            type="number"
            value={recipeData.prepTime}
            onChange={(e) => setRecipeData({ ...recipeData, prepTime: e.target.value })}
            placeholder="60"
            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)]"
            min="0"
          />
        </div>
        <div className="md:col-span-2">
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">Instrucciones</label>
          <textarea
            value={recipeData.instructions}
            onChange={(e) => setRecipeData({ ...recipeData, instructions: e.target.value })}
            placeholder="Pasos de preparación de la receta..."
            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)]"
            rows={4}
          />
        </div>
      </div>
      <div className="flex justify-end pt-4 border-t border-[var(--border-primary)]">
        <button
          onClick={() => { onDataChange({ ...data, ...recipeData }); onNext(); }}
          disabled={!recipeData.name || !recipeData.yieldQuantity || !recipeData.finishedProductId}
          className="px-6 py-2.5 bg-[var(--color-primary)] text-white rounded-lg hover:bg-[var(--color-primary)]/90 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          Continuar
        </button>
      </div>
    </div>
  );
};

interface SelectedIngredient {
  id: string;
  ingredientId: string;
  quantity: number;
  unit: MeasurementUnit;
  notes: string;
  order: number;
}

const IngredientsStep: React.FC<WizardDataProps> = ({ data, onDataChange, onComplete }) => {
  const { currentTenant } = useTenant();
  const [ingredients, setIngredients] = useState<IngredientResponse[]>([]);
  const [selectedIngredients, setSelectedIngredients] = useState<SelectedIngredient[]>(data.ingredients || []);
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [searchTerm, setSearchTerm] = useState('');

  useEffect(() => {
    fetchIngredients();
  }, []);

  const fetchIngredients = async () => {
    if (!currentTenant?.id) return;
    setLoading(true);
    try {
      const result = await inventoryService.getIngredients(currentTenant.id);
      // Filter out finished products - we only want raw ingredients
      const rawIngredients = result.filter(ing => ing.category !== 'finished_product');
      setIngredients(rawIngredients);
    } catch (err) {
      setError('Error al cargar ingredientes');
      console.error('Error loading ingredients:', err);
    } finally {
      setLoading(false);
    }
  };

  const handleAddIngredient = () => {
    const newIngredient: SelectedIngredient = {
      id: Date.now().toString(),
      ingredientId: '',
      quantity: 0,
      unit: MeasurementUnit.GRAMS,
      notes: '',
      order: selectedIngredients.length + 1,
    };
    setSelectedIngredients([...selectedIngredients, newIngredient]);
  };

  const handleUpdateIngredient = (id: string, field: keyof SelectedIngredient, value: any) => {
    setSelectedIngredients(
      selectedIngredients.map(ing =>
        ing.id === id ? { ...ing, [field]: value } : ing
      )
    );
  };

  const handleRemoveIngredient = (id: string) => {
    setSelectedIngredients(selectedIngredients.filter(ing => ing.id !== id));
  };

  const handleSaveRecipe = async () => {
    if (!currentTenant?.id) {
      setError('No se pudo obtener información del tenant');
      return;
    }

    if (selectedIngredients.length === 0) {
      setError('Debes agregar al menos un ingrediente');
      return;
    }

    // Validate all ingredients are filled
    const invalidIngredients = selectedIngredients.filter(
      ing => !ing.ingredientId || ing.quantity <= 0
    );
    if (invalidIngredients.length > 0) {
      setError('Todos los ingredientes deben tener un ingrediente seleccionado y cantidad mayor a 0');
      return;
    }

    setSaving(true);
    setError(null);

    try {
      // Prepare recipe data according to RecipeCreate interface
      const recipeIngredients: RecipeIngredientCreate[] = selectedIngredients.map((ing, index) => ({
        ingredient_id: ing.ingredientId,
        quantity: ing.quantity,
        unit: ing.unit,
        ingredient_notes: ing.notes || null,
        is_optional: false,
        ingredient_order: index + 1,
      }));

      const recipeData: RecipeCreate = {
        name: data.name,
        category: data.category,
        finished_product_id: data.finishedProductId,
        yield_quantity: parseFloat(data.yieldQuantity),
        yield_unit: data.yieldUnit as MeasurementUnit,
        prep_time_minutes: data.prepTime ? parseInt(data.prepTime) : null,
        instructions: data.instructions ? { steps: data.instructions } : null,
        ingredients: recipeIngredients,
      };

      await recipesService.createRecipe(currentTenant.id, recipeData);
      showToast.success('Receta creada exitosamente');
      onDataChange({ ...data, ingredients: selectedIngredients });
      onComplete();
    } catch (err: any) {
      console.error('Error creating recipe:', err);
      const errorMessage = err.response?.data?.detail || 'Error al crear la receta';
      setError(errorMessage);
      showToast.error(errorMessage);
    } finally {
      setSaving(false);
    }
  };

  const filteredIngredients = ingredients.filter(ing =>
    ing.name.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <div className="space-y-6">
      <div className="text-center pb-4 border-b border-[var(--border-primary)]">
        <Package className="w-12 h-12 mx-auto mb-3 text-[var(--color-primary)]" />
        <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-2">Ingredientes</h3>
        <p className="text-sm text-[var(--text-secondary)]">{data.name}</p>
      </div>

      {error && (
        <div className="p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">
          {error}
        </div>
      )}

      {loading ? (
        <div className="flex items-center justify-center py-12">
          <Loader2 className="w-8 h-8 animate-spin text-[var(--color-primary)]" />
          <span className="ml-3 text-[var(--text-secondary)]">Cargando ingredientes...</span>
        </div>
      ) : (
        <>
          <div className="space-y-4">
            {selectedIngredients.length === 0 ? (
              <div className="text-center py-8 border-2 border-dashed border-[var(--border-secondary)] rounded-lg">
                <Package className="w-12 h-12 mx-auto mb-3 text-[var(--text-tertiary)]" />
                <p className="text-[var(--text-secondary)] mb-2">No hay ingredientes agregados</p>
                <p className="text-sm text-[var(--text-tertiary)]">Haz clic en "Agregar Ingrediente" para comenzar</p>
              </div>
            ) : (
              selectedIngredients.map((selectedIng) => (
                <div key={selectedIng.id} className="p-4 border border-[var(--border-secondary)] rounded-lg bg-[var(--bg-secondary)]">
                  <div className="grid grid-cols-1 md:grid-cols-12 gap-3 items-start">
                    <div className="md:col-span-5">
                      <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">Ingrediente *</label>
                      <div className="relative">
                        <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-[var(--text-tertiary)]" />
                        <select
                          value={selectedIng.ingredientId}
                          onChange={(e) => handleUpdateIngredient(selectedIng.id, 'ingredientId', e.target.value)}
                          className="w-full pl-9 pr-3 py-2 border border-[var(--border-secondary)] rounded-lg focus:outline-none focus:ring-2 focus:ring-[var(--color-primary)] text-sm"
                        >
                          <option value="">Seleccionar...</option>
                          {filteredIngredients.map(ing => (
                            <option key={ing.id} value={ing.id}>
                              {ing.name} {ing.category ? `(${ing.category})` : ''}
                            </option>
                          ))}
                        </select>
                      </div>
                    </div>
                    <div className="md:col-span-2">
                      <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">Cantidad *</label>
                      <input
                        type="number"
                        value={selectedIng.quantity || ''}
                        onChange={(e) => handleUpdateIngredient(selectedIng.id, 'quantity', parseFloat(e.target.value) || 0)}
                        placeholder="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)] text-sm"
                        min="0"
                        step="0.01"
                      />
                    </div>
                    <div className="md:col-span-2">
                      <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">Unidad *</label>
                      <select
                        value={selectedIng.unit}
                        onChange={(e) => handleUpdateIngredient(selectedIng.id, '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)] text-sm"
                      >
                        <option value={MeasurementUnit.GRAMS}>Gramos (g)</option>
                        <option value={MeasurementUnit.KILOGRAMS}>Kilogramos (kg)</option>
                        <option value={MeasurementUnit.MILLILITERS}>Mililitros (ml)</option>
                        <option value={MeasurementUnit.LITERS}>Litros (l)</option>
                        <option value={MeasurementUnit.UNITS}>Unidades</option>
                        <option value={MeasurementUnit.PIECES}>Piezas</option>
                        <option value={MeasurementUnit.CUPS}>Tazas</option>
                        <option value={MeasurementUnit.TABLESPOONS}>Cucharadas</option>
                        <option value={MeasurementUnit.TEASPOONS}>Cucharaditas</option>
                      </select>
                    </div>
                    <div className="md:col-span-2">
                      <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">Notas</label>
                      <input
                        type="text"
                        value={selectedIng.notes}
                        onChange={(e) => handleUpdateIngredient(selectedIng.id, 'notes', e.target.value)}
                        placeholder="Opcional"
                        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)] text-sm"
                      />
                    </div>
                    <div className="md:col-span-1 flex items-end">
                      <button
                        onClick={() => handleRemoveIngredient(selectedIng.id)}
                        className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                        title="Eliminar ingrediente"
                      >
                        <X className="w-5 h-5" />
                      </button>
                    </div>
                  </div>
                </div>
              ))
            )}
          </div>

          <button
            onClick={handleAddIngredient}
            className="w-full py-3 border-2 border-dashed border-[var(--border-secondary)] rounded-lg text-[var(--text-secondary)] hover:border-[var(--color-primary)] hover:text-[var(--color-primary)] transition-colors inline-flex items-center justify-center gap-2"
          >
            <Plus className="w-5 h-5" />
            Agregar Ingrediente
          </button>
        </>
      )}

      <div className="flex justify-end gap-3 pt-4 border-t border-[var(--border-primary)]">
        <button
          onClick={handleSaveRecipe}
          disabled={saving || selectedIngredients.length === 0 || loading}
          className="px-8 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 font-semibold inline-flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
        >
          {saving ? (
            <>
              <Loader2 className="w-5 h-5 animate-spin" />
              Creando...
            </>
          ) : (
            <>
              <CheckCircle2 className="w-5 h-5" />
              Crear Receta
            </>
          )}
        </button>
      </div>
    </div>
  );
};

export const RecipeWizardSteps = (data: Record<string, any>, setData: (data: Record<string, any>) => void): WizardStep[] => [
  { id: 'recipe-details', title: 'Detalles de la Receta', description: 'Nombre, categoría, rendimiento', component: (props) => <RecipeDetailsStep {...props} data={data} onDataChange={setData} /> },
  { id: 'recipe-ingredients', title: 'Ingredientes', description: 'Selección y cantidades', component: (props) => <IngredientsStep {...props} data={data} onDataChange={setData} /> },
];
