import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { WizardStep, WizardStepProps } from '../../../ui/WizardModal/WizardModal';
import { ChefHat, Package, ClipboardCheck, CheckCircle2, Loader2, Plus, X, Search, FileText } from 'lucide-react';
import { useTenant } from '../../../../stores/tenant.store';
import { recipesService } from '../../../../api/services/recipes';
import { inventoryService } from '../../../../api/services/inventory';
import { qualityTemplateService } from '../../../../api/services/qualityTemplates';
import { IngredientResponse } from '../../../../api/types/inventory';
import { RecipeCreate, RecipeIngredientCreate, MeasurementUnit, RecipeQualityConfiguration, RecipeStatus } from '../../../../api/types/recipes';
import { QualityCheckTemplate } from '../../../../api/types/qualityTemplates';
import { showToast } from '../../../../utils/toast';
import { AdvancedOptionsSection } from '../../../ui/AdvancedOptionsSection';
import Tooltip from '../../../ui/Tooltip/Tooltip';
import { RecipeInstructionsEditor } from '../../recipes/RecipeInstructionsEditor';
import { RecipeQualityControlEditor } from '../../recipes/RecipeQualityControlEditor';

const RecipeDetailsStep: React.FC<WizardStepProps> = ({ dataRef, onDataChange }) => {
  const { t } = useTranslation('wizards');
  const data = dataRef?.current || {};
  const { currentTenant } = useTenant();
  const [finishedProducts, setFinishedProducts] = useState<IngredientResponse[]>([]);
  const [loading, setLoading] = useState(false);

  const handleFieldChange = (field: string, value: any) => {
    onDataChange?.({ ...data, [field]: value });
  };

  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">{t('recipe.recipeDetails')}</h3>
        <p className="text-sm text-[var(--text-secondary)]">{t('recipe.recipeDetailsDescription')}</p>
      </div>

      {/* Essential Fields Only */}
      <div className="space-y-4">
        <div>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
            {t('recipe.fields.name')} *
          </label>
          <input
            type="text"
            value={data.name || ''}
            onChange={(e) => handleFieldChange('name', e.target.value)}
            placeholder={t('recipe.fields.namePlaceholder')}
            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)]"
          />
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              {t('recipe.fields.category')} *
            </label>
            <select
              value={data.category || 'bread'}
              onChange={(e) => handleFieldChange('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)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
            >
              <option value="bread">{t('recipe.categories.bread')}</option>
              <option value="pastries">{t('recipe.categories.pastries')}</option>
              <option value="cakes">{t('recipe.categories.cakes')}</option>
              <option value="cookies">{t('recipe.categories.cookies')}</option>
              <option value="muffins">{t('recipe.categories.muffins')}</option>
              <option value="sandwiches">{t('recipe.categories.sandwiches')}</option>
              <option value="seasonal">{t('recipe.categories.seasonal')}</option>
              <option value="other">{t('recipe.categories.other')}</option>
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2 inline-flex items-center gap-2">
              {t('recipe.fields.finishedProduct')} *
              <Tooltip content={t('recipe.fields.finishedProductTooltip')}>
                <span />
              </Tooltip>
            </label>
            <select
              value={data.finishedProductId || ''}
              onChange={(e) => handleFieldChange('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)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
              disabled={loading}
            >
              <option value="">{t('recipe.fields.selectProduct')}</option>
              {finishedProducts.map(product => (
                <option key={product.id} value={product.id}>{product.name}</option>
              ))}
            </select>
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2 inline-flex items-center gap-2">
              {t('recipe.fields.yieldQuantity')} *
              <Tooltip content="How many units this recipe produces (e.g., 12 loaves)">
                <span />
              </Tooltip>
            </label>
            <input
              type="number"
              value={data.yieldQuantity || ''}
              onChange={(e) => handleFieldChange('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)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
              min="0.01"
              step="0.01"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              {t('recipe.fields.yieldUnit')} *
            </label>
            <select
              value={data.yieldUnit || 'units'}
              onChange={(e) => handleFieldChange('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)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
            >
              <option value="units">{t('recipe.units.units')}</option>
              <option value="pieces">{t('recipe.units.pieces')}</option>
              <option value="kg">{t('recipe.units.kg')}</option>
              <option value="g">{t('recipe.units.g')}</option>
              <option value="l">{t('recipe.units.l')}</option>
              <option value="ml">{t('recipe.units.ml')}</option>
            </select>
          </div>
        </div>

        <div>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2 inline-flex items-center gap-2">
            {t('recipe.fields.prepTime')} (minutes)
            <Tooltip content="Total preparation time in minutes">
              <span />
            </Tooltip>
          </label>
          <input
            type="number"
            value={data.prepTime || ''}
            onChange={(e) => handleFieldChange('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)] bg-[var(--bg-primary)] text-[var(--text-primary)]"
            min="0"
          />
        </div>
      </div>

      {/* Advanced Options */}
      <AdvancedOptionsSection
        title={t('recipe.advancedOptionsTitle')}
        description={t('recipe.advancedOptionsDescription')}
      >
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              {t('recipe.fields.recipeCode')}
            </label>
            <input
              type="text"
              value={data.recipeCode}
              onChange={(e) => handleFieldChange('recipeCode', e.target.value)}
              placeholder={t('recipe.fields.recipeCodePlaceholder')}
              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)]"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              {t('recipe.fields.version')}
            </label>
            <input
              type="text"
              value={data.version}
              onChange={(e) => handleFieldChange('version', e.target.value)}
              placeholder={t('recipe.fields.versionPlaceholder')}
              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)]"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2 inline-flex items-center gap-2">
              {t('recipe.fields.difficulty')}
              <Tooltip content={t('recipe.fields.difficultyTooltip')}>
                <span />
              </Tooltip>
            </label>
            <input
              type="number"
              value={data.difficultyLevel}
              onChange={(e) => handleFieldChange('difficultyLevel', parseInt(e.target.value) || 1)}
              min="1"
              max="5"
              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)]"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              {t('recipe.fields.cookTime')}
            </label>
            <input
              type="number"
              value={data.cookTime}
              onChange={(e) => handleFieldChange('cookTime', e.target.value)}
              placeholder={t('recipe.fields.cookTimePlaceholder')}
              min="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)]"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2 inline-flex items-center gap-2">
              {t('recipe.fields.restTime')}
              <Tooltip content={t('recipe.fields.restTimeTooltip')}>
                <span />
              </Tooltip>
            </label>
            <input
              type="number"
              value={data.restTime}
              onChange={(e) => handleFieldChange('restTime', e.target.value)}
              placeholder={t('recipe.fields.restTimePlaceholder')}
              min="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)]"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              {t('recipe.fields.totalTime')}
            </label>
            <input
              type="number"
              value={data.totalTime}
              onChange={(e) => handleFieldChange('totalTime', e.target.value)}
              placeholder={t('recipe.fields.totalTimePlaceholder')}
              min="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)]"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              {t('recipe.fields.servesCount')}
            </label>
            <input
              type="number"
              value={data.servesCount}
              onChange={(e) => handleFieldChange('servesCount', e.target.value)}
              placeholder={t('recipe.fields.servesCountPlaceholder')}
              min="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)]"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2 inline-flex items-center gap-2">
              {t('recipe.fields.batchSizeMultiplier')}
              <Tooltip content={t('recipe.fields.batchSizeMultiplierTooltip')}>
                <span />
              </Tooltip>
            </label>
            <input
              type="number"
              value={data.batchSizeMultiplier}
              onChange={(e) => handleFieldChange('batchSizeMultiplier', parseFloat(e.target.value) || 1)}
              placeholder={t('recipe.fields.batchSizeMultiplierPlaceholder')}
              min="0.1"
              step="0.1"
              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)]"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              {t('recipe.fields.minBatchSize')}
            </label>
            <input
              type="number"
              value={data.minBatchSize}
              onChange={(e) => handleFieldChange('minBatchSize', e.target.value)}
              placeholder={t('recipe.fields.minBatchSizePlaceholder')}
              min="0"
              step="0.1"
              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)]"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              {t('recipe.fields.maxBatchSize')}
            </label>
            <input
              type="number"
              value={data.maxBatchSize}
              onChange={(e) => handleFieldChange('maxBatchSize', e.target.value)}
              placeholder={t('recipe.fields.maxBatchSizePlaceholder')}
              min="0"
              step="0.1"
              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)]"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              {t('recipe.fields.optimalTemp')}
            </label>
            <input
              type="number"
              value={data.optimalProductionTemp}
              onChange={(e) => handleFieldChange('optimalProductionTemp', e.target.value)}
              placeholder={t('recipe.fields.optimalTempPlaceholder')}
              step="0.1"
              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)]"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              {t('recipe.fields.optimalHumidity')}
            </label>
            <input
              type="number"
              value={data.optimalHumidity}
              onChange={(e) => handleFieldChange('optimalHumidity', e.target.value)}
              placeholder={t('recipe.fields.optimalHumidityPlaceholder')}
              min="0"
              max="100"
              step="0.1"
              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)]"
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              {t('recipe.fields.targetMargin')}
            </label>
            <input
              type="number"
              value={data.targetMargin}
              onChange={(e) => handleFieldChange('targetMargin', e.target.value)}
              placeholder={t('recipe.fields.targetMarginPlaceholder')}
              min="0"
              max="100"
              step="0.1"
              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)]"
            />
          </div>
        </div>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          <div className="flex items-center gap-3">
            <input
              type="checkbox"
              id="isSeasonal"
              checked={data.isSeasonal}
              onChange={(e) => handleFieldChange('isSeasonal', e.target.checked)}
              className="w-4 h-4 text-[var(--color-primary)] border-[var(--border-secondary)] rounded focus:ring-2 focus:ring-[var(--color-primary)]"
            />
            <label htmlFor="isSeasonal" className="text-sm font-medium text-[var(--text-secondary)]">
              {t('recipe.fields.seasonalItem')}
            </label>
          </div>

          <div className="flex items-center gap-3">
            <input
              type="checkbox"
              id="isSignatureItem"
              checked={data.isSignatureItem}
              onChange={(e) => handleFieldChange('isSignatureItem', e.target.checked)}
              className="w-4 h-4 text-[var(--color-primary)] border-[var(--border-secondary)] rounded focus:ring-2 focus:ring-[var(--color-primary)]"
            />
            <label htmlFor="isSignatureItem" className="text-sm font-medium text-[var(--text-secondary)]">
              {t('recipe.fields.signatureItem')}
            </label>
          </div>
        </div>

        {data.isSeasonal && (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                {t('recipe.fields.seasonStartMonth')}
              </label>
              <select
                value={data.seasonStartMonth}
                onChange={(e) => handleFieldChange('seasonStartMonth', 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)]"
              >
                <option value="">{t('recipe.fields.seasonStartMonthPlaceholder')}</option>
                {Array.from({ length: 12 }, (_, i) => i + 1).map(month => (
                  <option key={month} value={month}>
                    {new Date(2000, month - 1).toLocaleString('default', { month: 'long' })}
                  </option>
                ))}
              </select>
            </div>

            <div>
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                {t('recipe.fields.seasonEndMonth')}
              </label>
              <select
                value={data.seasonEndMonth}
                onChange={(e) => handleFieldChange('seasonEndMonth', 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)]"
              >
                <option value="">{t('recipe.fields.seasonEndMonthPlaceholder')}</option>
                {Array.from({ length: 12 }, (_, i) => i + 1).map(month => (
                  <option key={month} value={month}>
                    {new Date(2000, month - 1).toLocaleString('default', { month: 'long' })}
                  </option>
                ))}
              </select>
            </div>
          </div>
        )}

        <div>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
            {t('recipe.fields.description')}
          </label>
          <textarea
            value={data.description}
            onChange={(e) => handleFieldChange('description', e.target.value)}
            placeholder={t('recipe.fields.descriptionPlaceholder')}
            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)]"
            rows={3}
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2 inline-flex items-center gap-2">
            {t('recipe.fields.prepNotes')}
            <Tooltip content={t('recipe.fields.prepNotesTooltip')}>
              <span />
            </Tooltip>
          </label>
          <textarea
            value={data.preparationNotes}
            onChange={(e) => handleFieldChange('preparationNotes', e.target.value)}
            placeholder={t('recipe.fields.prepNotesPlaceholder')}
            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)]"
            rows={3}
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
            {t('recipe.fields.storageInstructions')}
          </label>
          <textarea
            value={data.storageInstructions}
            onChange={(e) => handleFieldChange('storageInstructions', e.target.value)}
            placeholder={t('recipe.fields.storageInstructionsPlaceholder')}
            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)]"
            rows={3}
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
            {t('recipe.fields.allergens')}
          </label>
          <input
            type="text"
            value={data.allergens}
            onChange={(e) => handleFieldChange('allergens', e.target.value)}
            placeholder={t('recipe.fields.allergensPlaceholder')}
            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)]"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
            {t('recipe.fields.dietaryTags')}
          </label>
          <input
            type="text"
            value={data.dietaryTags}
            onChange={(e) => handleFieldChange('dietaryTags', e.target.value)}
            placeholder={t('recipe.fields.dietaryTagsPlaceholder')}
            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)]"
          />
        </div>
      </AdvancedOptionsSection>
    </div>
  );
};

// New Step 2: Recipe Instructions
const RecipeInstructionsStep: React.FC<WizardStepProps> = ({ dataRef, onDataChange }) => {
  const { t } = useTranslation('wizards');
  const data = dataRef?.current || {};

  const handleInstructionsChange = (instructions: any) => {
    onDataChange?.({ ...data, instructions });
  };

  return (
    <div className="space-y-6">
      <div className="text-center pb-4 border-b border-[var(--border-primary)]">
        <FileText 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">
          Recipe Instructions
        </h3>
        <p className="text-sm text-[var(--text-secondary)]">
          Add step-by-step instructions for preparing {data.name || 'this recipe'}
        </p>
      </div>

      <RecipeInstructionsEditor
        value={data.instructions || null}
        onChange={handleInstructionsChange}
      />

      <div className="p-3 bg-blue-50 border border-blue-200 rounded-lg text-sm text-blue-700">
        <strong>Tip:</strong> Break down the recipe into clear, manageable steps. Include durations to help with production planning.
      </div>
    </div>
  );
};

interface SelectedIngredient {
  id: string;
  ingredientId: string;
  quantity: number;
  unit: MeasurementUnit;
  notes: string;
  preparationMethod?: string;
  isOptional?: boolean;
  order: number;
}

const IngredientsStep: React.FC<WizardStepProps> = ({ dataRef, onDataChange }) => {
  const { t } = useTranslation('wizards');
  const data = dataRef?.current || {};
  const { currentTenant } = useTenant();
  const [ingredients, setIngredients] = useState<IngredientResponse[]>([]);
  const [loading, setLoading] = useState(true);
  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);
      const rawIngredients = result.filter(ing => ing.category !== 'finished_product');
      setIngredients(rawIngredients);
    } catch (err) {
      setError('Error loading ingredients');
      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: '',
      preparationMethod: '',
      isOptional: false,
      order: (data.ingredients || []).length + 1,
    };
    onDataChange?.({ ...data, ingredients: [...(data.ingredients || []), newIngredient] });
  };

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

  const handleRemoveIngredient = (id: string) => {
    onDataChange?.({
      ...data,
      ingredients: (data.ingredients || []).filter(ing => ing.id !== id)
    });
  };

  const filteredIngredients = ingredients.filter((ing: IngredientResponse) =>
    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">Recipe Ingredients</h3>
        <p className="text-sm text-[var(--text-secondary)]">Add ingredients for {data.name || 'this recipe'}</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)]">Loading ingredients...</span>
        </div>
      ) : (
        <>
          <div className="space-y-4">
            {(data.ingredients || []).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 ingredients added</p>
                <p className="text-sm text-[var(--text-tertiary)]">Click "Add Ingredient" to begin</p>
              </div>
            ) : (
              (data.ingredients || []).map((selectedIng: SelectedIngredient) => (
                <div key={selectedIng.id} className="p-4 border border-[var(--border-secondary)] rounded-lg bg-[var(--bg-secondary)]">
                  <div className="space-y-3">
                    {/* Row 1: Ingredient, Quantity, Unit */}
                    <div className="grid grid-cols-1 md:grid-cols-12 gap-3 items-start">
                      <div className="md:col-span-6">
                        <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">Ingredient *</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="">Select...</option>
                            {filteredIngredients.map((ing: IngredientResponse) => (
                              <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">Quantity *</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-3">
                        <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">Unit *</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}>Grams (g)</option>
                          <option value={MeasurementUnit.KILOGRAMS}>Kilograms (kg)</option>
                          <option value={MeasurementUnit.MILLILITERS}>Milliliters (ml)</option>
                          <option value={MeasurementUnit.LITERS}>Liters (l)</option>
                          <option value={MeasurementUnit.UNITS}>Units</option>
                          <option value={MeasurementUnit.PIECES}>Pieces</option>
                          <option value={MeasurementUnit.CUPS}>Cups</option>
                          <option value={MeasurementUnit.TABLESPOONS}>Tablespoons</option>
                          <option value={MeasurementUnit.TEASPOONS}>Teaspoons</option>
                        </select>
                      </div>
                      <div className="md:col-span-1 flex items-end">
                        <button
                          type="button"
                          onClick={() => handleRemoveIngredient(selectedIng.id)}
                          className="p-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors"
                          title="Remove ingredient"
                        >
                          <X className="w-5 h-5" />
                        </button>
                      </div>
                    </div>

                    {/* Row 2: Preparation Method and Optional Checkbox */}
                    <div className="grid grid-cols-1 md:grid-cols-12 gap-3 items-start">
                      <div className="md:col-span-8">
                        <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">
                          Preparation Method
                        </label>
                        <input
                          type="text"
                          value={selectedIng.preparationMethod || ''}
                          onChange={(e) => handleUpdateIngredient(selectedIng.id, 'preparationMethod', e.target.value)}
                          placeholder="e.g., sifted, melted, chopped"
                          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-4">
                        <label className="block text-xs font-medium text-[var(--text-secondary)] mb-1">Notes</label>
                        <input
                          type="text"
                          value={selectedIng.notes}
                          onChange={(e) => handleUpdateIngredient(selectedIng.id, 'notes', e.target.value)}
                          placeholder="Optional"
                          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>

                    {/* Row 3: Optional Checkbox */}
                    <div className="flex items-center gap-2">
                      <input
                        type="checkbox"
                        id={`optional-${selectedIng.id}`}
                        checked={selectedIng.isOptional || false}
                        onChange={(e) => handleUpdateIngredient(selectedIng.id, 'isOptional', e.target.checked)}
                        className="w-4 h-4 text-[var(--color-primary)] border-[var(--border-secondary)] rounded focus:ring-2 focus:ring-[var(--color-primary)]"
                      />
                      <label htmlFor={`optional-${selectedIng.id}`} className="text-xs text-[var(--text-secondary)]">
                        This ingredient is optional
                      </label>
                    </div>
                  </div>
                </div>
              ))
            )}
          </div>

          <button
            type="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" />
            Add Ingredient
          </button>
        </>
      )}
    </div>
  );
};

// New Step 4: Enhanced Quality Control Configuration
// API submission is handled centrally in UnifiedAddWizard.handleWizardComplete
const QualityControlStep: React.FC<WizardStepProps> = ({ dataRef, onDataChange }) => {
  const { t } = useTranslation('wizards');
  const data = dataRef?.current || {};
  const { currentTenant } = useTenant();
  const [templates, setTemplates] = useState<QualityCheckTemplate[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

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

  const fetchTemplates = async () => {
    if (!currentTenant?.id) return;
    setLoading(true);
    try {
      const result = await qualityTemplateService.getTemplates(currentTenant.id, { is_active: true });
      setTemplates(result.templates || []);
    } catch (err) {
      console.error('Error loading quality templates:', err);
      setError('Error loading quality templates');
    } finally {
      setLoading(false);
    }
  };

  const handleQualityConfigChange = (config: any) => {
    onDataChange?.({ ...data, qualityConfiguration: config });
  };

  // Format templates for the editor
  const formattedTemplates = templates.map(t => ({
    id: t.id,
    name: t.name,
    category: t.check_type || 'general'
  }));

  return (
    <div className="space-y-6">
      <div className="text-center pb-4 border-b border-[var(--border-primary)]">
        <ClipboardCheck 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">
          Quality Control Configuration (Optional)
        </h3>
        <p className="text-sm text-[var(--text-secondary)]">
          Configure quality control checks for each production stage
        </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)]">Loading templates...</span>
        </div>
      ) : templates.length === 0 ? (
        <div className="text-center py-12 border-2 border-dashed border-[var(--border-secondary)] rounded-lg">
          <ClipboardCheck className="w-12 h-12 mx-auto mb-3 text-[var(--text-tertiary)]" />
          <p className="text-[var(--text-secondary)] mb-2">No quality templates available</p>
          <p className="text-sm text-[var(--text-tertiary)]">
            You can create templates from the Database menu
          </p>
        </div>
      ) : (
        <>
          <RecipeQualityControlEditor
            value={data.qualityConfiguration || null}
            onChange={handleQualityConfigChange}
            allTemplates={formattedTemplates}
          />

          <div className="p-3 bg-blue-50 border border-blue-200 rounded-lg text-sm text-blue-700">
            <strong>Tip:</strong> Configure which quality checks are required at each production stage. You can make certain stages blocking to halt production if quality checks fail.
          </div>
        </>
      )}
    </div>
  );
};

export const RecipeWizardSteps = (dataRef: React.MutableRefObject<Record<string, any>>, setData: (data: Record<string, any>) => void): WizardStep[] => {
  // New architecture: return direct component references instead of arrow functions
  // dataRef and onDataChange are now passed through WizardModal props
  return [
    {
      id: 'recipe-details',
      title: 'wizards:recipe.steps.recipeDetails',
      description: 'wizards:recipe.steps.recipeDetailsDescription',
      component: RecipeDetailsStep,
      validate: () => {
        const data = dataRef.current;
        // Validate required fields
        if (!data.name || data.name.trim().length < 2) {
          return false;
        }
        if (!data.category) {
          return false;
        }
        if (!data.finishedProductId) {
          return false;
        }
        if (!data.yieldQuantity || parseFloat(data.yieldQuantity) <= 0) {
          return false;
        }
        if (!data.yieldUnit) {
          return false;
        }
        return true;
      },
    },
    {
      id: 'recipe-instructions',
      title: 'Recipe Instructions',
      description: 'Add step-by-step preparation instructions',
      component: RecipeInstructionsStep,
      isOptional: true,
    },
    {
      id: 'recipe-ingredients',
      title: 'wizards:recipe.steps.ingredients',
      description: 'wizards:recipe.steps.ingredientsDescription',
      component: IngredientsStep,
      validate: () => {
        const data = dataRef.current;
        const ingredients = data.ingredients || [];

        // Must have at least one ingredient
        if (ingredients.length === 0) {
          return false;
        }

        // Each ingredient must have required fields
        return ingredients.every((ing: any) =>
          ing.ingredientId &&
          ing.quantity &&
          parseFloat(ing.quantity) > 0 &&
          ing.unit
        );
      },
    },
    {
      id: 'recipe-quality-control',
      title: 'Quality Control',
      description: 'Configure quality checks for production stages',
      component: QualityControlStep,
      isOptional: true,
    },
  ];
};
