import React, { useState, useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { WizardStep, WizardStepProps } from '../../../ui/WizardModal/WizardModal';
import { AdvancedOptionsSection } from '../../../ui/AdvancedOptionsSection';
import {
  Package,
  ChefHat,
  Clock,
  AlertCircle,
  Users,
  CheckCircle2,
  Loader2,
  ClipboardCheck,
  TrendingUp,
} from 'lucide-react';
import { useTenant } from '../../../../stores/tenant.store';
import { useRecipes } from '../../../../api/hooks/recipes';
import { useIngredients } from '../../../../api/hooks/inventory';
import { recipesService } from '../../../../api/services/recipes';
import { ProductionPriorityEnum } from '../../../../api/types/production';
import { ProcessStage } from '../../../../api/types/qualityTemplates';
import { Badge } from '../../../ui';
import { Card } from '../../../ui';

// Helper to get stage label with translation
const getStageLabelKey = (stage: ProcessStage): string => {
  const stageKeyMap: Record<ProcessStage, string> = {
    [ProcessStage.MIXING]: 'mixing',
    [ProcessStage.PROOFING]: 'proofing',
    [ProcessStage.SHAPING]: 'shaping',
    [ProcessStage.BAKING]: 'baking',
    [ProcessStage.COOLING]: 'cooling',
    [ProcessStage.PACKAGING]: 'packaging',
    [ProcessStage.FINISHING]: 'finishing',
  };
  return stageKeyMap[stage];
};

// Step 1: Product & Recipe Selection
const ProductRecipeStep: React.FC<WizardStepProps> = ({ dataRef, onDataChange }) => {
  const data = dataRef?.current || {};
  const { t } = useTranslation(['wizards', 'production']);
  const { currentTenant } = useTenant();
  const [selectedRecipe, setSelectedRecipe] = useState<any>(null);
  const [loadingRecipe, setLoadingRecipe] = useState(false);

  // Fetch ingredients and recipes
  const { data: ingredients = [], isLoading: ingredientsLoading } = useIngredients(
    currentTenant?.id || '',
    {},
    { enabled: !!currentTenant?.id }
  );
  const { data: recipes = [], isLoading: recipesLoading } = useRecipes(
    currentTenant?.id || '',
    {},
    { enabled: !!currentTenant?.id }
  );

  // Filter finished products
  const finishedProducts = useMemo(
    () =>
      ingredients.filter(
        (ing: any) =>
          ing.type === 'finished_product' ||
          ing.category === 'finished_products' ||
          ing.name.toLowerCase().includes('pan') ||
          ing.name.toLowerCase().includes('pastel') ||
          ing.name.toLowerCase().includes('torta')
      ),
    [ingredients]
  );

  // Load recipe details when recipe is selected
  const handleRecipeChange = async (recipeId: string) => {
    if (!recipeId) {
      setSelectedRecipe(null);
      onDataChange?.({ ...data, recipe_id: '', selectedRecipe: null });
      return;
    }

    setLoadingRecipe(true);
    try {
      const recipe = await recipesService.getRecipe(currentTenant?.id || '', recipeId);
      setSelectedRecipe(recipe);
      onDataChange?.({ ...data, recipe_id: recipeId, selectedRecipe: recipe });
    } catch (error) {
      console.error('Error loading recipe:', error);
      setSelectedRecipe(null);
      onDataChange?.({ ...data, recipe_id: '', selectedRecipe: null });
    } finally {
      setLoadingRecipe(false);
    }
  };

  const handleProductChange = (productId: string) => {
    const product = finishedProducts.find((p: any) => p.id === productId);
    onDataChange?.({
      ...data,
      product_id: productId,
      product_name: product?.name || '',
    });
  };

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

      {ingredientsLoading || recipesLoading ? (
        <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)]">{t('productionBatch.productRecipe.loading')}</span>
        </div>
      ) : (
        <>
          <div className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                {t('productionBatch.productRecipe.productToProduce')} *
              </label>
              <select
                value={data.product_id || ''}
                onChange={(e) => handleProductChange(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('productionBatch.productRecipe.selectProduct')}</option>
                {finishedProducts.map((product: any) => (
                  <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">
                {t('productionBatch.productRecipe.recipeToUse')}
              </label>
              <select
                value={data.recipe_id || ''}
                onChange={(e) => handleRecipeChange(e.target.value)}
                disabled={loadingRecipe}
                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:opacity-50"
              >
                <option value="">{t('productionBatch.productRecipe.noSpecificRecipe')}</option>
                {recipes.map((recipe: any) => (
                  <option key={recipe.id} value={recipe.id}>
                    {recipe.name}
                  </option>
                ))}
              </select>
              {loadingRecipe && (
                <p className="text-sm text-[var(--text-secondary)] mt-1 flex items-center gap-2">
                  <Loader2 className="w-4 h-4 animate-spin" />
                  {t('productionBatch.productRecipe.loadingRecipeDetails')}
                </p>
              )}
            </div>
          </div>

          {/* Quality Requirements Preview */}
          {selectedRecipe && (
            <Card className="mt-4 p-4 bg-blue-50 border-blue-200">
              <h4 className="font-medium text-[var(--text-primary)] mb-3 flex items-center gap-2">
                <ClipboardCheck className="w-5 h-5 text-blue-600" />
                {t('productionBatch.productRecipe.qualityControlsRequired')}
              </h4>
              {selectedRecipe.quality_check_configuration && selectedRecipe.quality_check_configuration.stages ? (
                <div className="space-y-3">
                  {Object.entries(selectedRecipe.quality_check_configuration.stages).map(
                    ([stage, config]: [string, any]) => {
                      if (!config.template_ids || config.template_ids.length === 0) return null;

                      return (
                        <div key={stage} className="flex items-center gap-2 text-sm">
                          <Badge variant="info">{t(`productionBatch.additionalDetails.stages.${getStageLabelKey(stage as ProcessStage)}`)}</Badge>
                          <span className="text-[var(--text-secondary)]">
                            {config.template_ids.length} {config.template_ids.length > 1 ? t('productionBatch.productRecipe.controls') : t('productionBatch.productRecipe.control')}
                          </span>
                          {config.blocking && <Badge variant="warning" size="sm">{t('productionBatch.productRecipe.blocking')}</Badge>}
                          {config.is_required && <Badge variant="error" size="sm">{t('productionBatch.productRecipe.required')}</Badge>}
                        </div>
                      );
                    }
                  )}
                  <div className="mt-3 pt-3 border-t border-blue-200">
                    <p className="text-sm text-[var(--text-secondary)]">
                      <span className="font-medium">{t('productionBatch.productRecipe.minimumQualityThreshold')}:</span>{' '}
                      {selectedRecipe.quality_check_configuration.overall_quality_threshold || 7.0}/10
                    </p>
                    {selectedRecipe.quality_check_configuration.critical_stage_blocking && (
                      <p className="text-sm text-[var(--text-secondary)] mt-1">
                        <span className="font-medium text-orange-600">⚠️ {t('productionBatch.productRecipe.criticalBlockingActivated')}:</span> {t('productionBatch.productRecipe.batchCannotAdvance')}
                      </p>
                    )}
                  </div>
                </div>
              ) : (
                <p className="text-sm text-[var(--text-secondary)]">
                  {t('productionBatch.productRecipe.noQualityControls')}
                </p>
              )}
            </Card>
          )}
        </>
      )}
    </div>
  );
};

// Step 2: Planning Details
const PlanningDetailsStep: React.FC<WizardStepProps> = ({ dataRef, onDataChange }) => {
  const data = dataRef?.current || {};
  const { t } = useTranslation(['wizards', 'production']);

  const getValue = (field: string, defaultValue: any = '') => {
    return data[field] ?? defaultValue;
  };

  const handleFieldChange = (updates: Record<string, any>) => {
    onDataChange?.({ ...data, ...updates });
  };

  // Auto-calculate end time based on start time and duration
  const calculateEndTime = (startTime: string, durationMinutes: number): string => {
    if (!startTime || !durationMinutes) return '';
    const start = new Date(startTime);
    const end = new Date(start.getTime() + durationMinutes * 60000);
    return end.toISOString().slice(0, 16);
  };

  // Handle start time or duration change
  const handleStartTimeChange = (startTime: string) => {
    const duration = getValue('planned_duration_minutes', 60);
    const endTime = calculateEndTime(startTime, duration);
    handleFieldChange({
      planned_start_time: startTime,
      planned_end_time: endTime,
    });
  };

  const handleDurationChange = (duration: number) => {
    const startTime = getValue('planned_start_time');
    const endTime = startTime ? calculateEndTime(startTime, duration) : '';
    handleFieldChange({
      planned_duration_minutes: duration,
      planned_end_time: endTime,
    });
  };

  return (
    <div className="space-y-6">
      <div className="text-center pb-4 border-b border-[var(--border-primary)]">
        <Clock 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('productionBatch.planningDetails.title')}</h3>
        <p className="text-sm text-[var(--text-secondary)]">{t('productionBatch.planningDetails.description')}</p>
      </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('productionBatch.planningDetails.plannedStart')} *</label>
          <input
            type="datetime-local"
            value={getValue('planned_start_time')}
            onChange={(e) => handleStartTimeChange(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)]"
          />
        </div>

        <div>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
            {t('productionBatch.planningDetails.duration')} *
          </label>
          <input
            type="number"
            value={getValue('planned_duration_minutes', 60)}
            onChange={(e) => handleDurationChange(parseInt(e.target.value) || 0)}
            min="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('productionBatch.planningDetails.plannedEnd')}
          </label>
          <input
            type="datetime-local"
            value={getValue('planned_end_time')}
            readOnly
            disabled
            className="w-full px-3 py-2 border border-[var(--border-secondary)] rounded-lg bg-[var(--bg-secondary)] text-[var(--text-tertiary)] cursor-not-allowed"
          />
          <p className="text-xs text-[var(--text-tertiary)] mt-1">{t('productionBatch.planningDetails.autoCalculated')}</p>
        </div>

        <div>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
            {t('productionBatch.planningDetails.plannedQuantity')} *
          </label>
          <input
            type="number"
            value={getValue('planned_quantity', 1)}
            onChange={(e) => handleFieldChange({ planned_quantity: parseFloat(e.target.value) || 1 })}
            min="1"
            step="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>

      {getValue('planned_start_time') && getValue('planned_end_time') && (
        <div className="p-4 bg-blue-50 border border-blue-200 rounded-lg">
          <div className="flex items-start gap-2">
            <Clock className="w-5 h-5 text-blue-600 flex-shrink-0 mt-0.5" />
            <div className="text-sm">
              <p className="font-medium text-blue-900">{t('productionBatch.planningDetails.planningSummary')}:</p>
              <p className="text-blue-700 mt-1">
                {t('productionBatch.planningDetails.start')}: {new Date(getValue('planned_start_time')).toLocaleString('es-ES')}
              </p>
              <p className="text-blue-700">{t('productionBatch.planningDetails.end')}: {new Date(getValue('planned_end_time')).toLocaleString('es-ES')}</p>
              <p className="text-blue-700">
                {t('productionBatch.planningDetails.durationSummary')}: {getValue('planned_duration_minutes', 0)} {t('productionBatch.planningDetails.minutes')} (
                {(getValue('planned_duration_minutes', 0) / 60).toFixed(1)} {t('productionBatch.planningDetails.hours')})
              </p>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

// Step 3: Priority & Resources
const PriorityResourcesStep: React.FC<WizardStepProps> = ({ dataRef, onDataChange }) => {
  const data = dataRef?.current || {};
  const { t } = useTranslation(['wizards', 'production']);

  const getValue = (field: string, defaultValue: any = '') => {
    return data[field] ?? defaultValue;
  };

  const handleFieldChange = (updates: Record<string, any>) => {
    onDataChange?.({ ...data, ...updates });
  };

  const priorityOptions = Object.values(ProductionPriorityEnum).map((value) => ({
    value,
    label: value.charAt(0) + value.slice(1).toLowerCase(),
  }));

  return (
    <div className="space-y-6">
      <div className="text-center pb-4 border-b border-[var(--border-primary)]">
        <AlertCircle 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('productionBatch.priorityResources.title')}</h3>
        <p className="text-sm text-[var(--text-secondary)]">{t('productionBatch.priorityResources.description')}</p>
      </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('productionBatch.priorityResources.priority')} *</label>
          <select
            value={getValue('priority', ProductionPriorityEnum.MEDIUM)}
            onChange={(e) => handleFieldChange({ priority: 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)]"
          >
            {priorityOptions.map((opt) => (
              <option key={opt.value} value={opt.value}>
                {opt.label}
              </option>
            ))}
          </select>
        </div>

        <div>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">{t('productionBatch.priorityResources.batchNumber')}</label>
          <input
            type="text"
            value={getValue('batch_number')}
            onChange={(e) => handleFieldChange({ batch_number: e.target.value })}
            placeholder={t('productionBatch.priorityResources.autoGeneratedPlaceholder')}
            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="flex items-center gap-3 p-3 border border-[var(--border-secondary)] rounded-lg">
          <input
            type="checkbox"
            checked={getValue('is_rush_order', false)}
            onChange={(e) => handleFieldChange({ is_rush_order: e.target.checked })}
            className="rounded border-[var(--border-secondary)] text-[var(--color-primary)] focus:ring-[var(--color-primary)]"
          />
          <label className="text-sm font-medium text-[var(--text-primary)]">{t('productionBatch.priorityResources.rushOrder')}</label>
        </div>

        <div className="flex items-center gap-3 p-3 border border-[var(--border-secondary)] rounded-lg">
          <input
            type="checkbox"
            checked={getValue('is_special_recipe', false)}
            onChange={(e) => handleFieldChange({ is_special_recipe: e.target.checked })}
            className="rounded border-[var(--border-secondary)] text-[var(--color-primary)] focus:ring-[var(--color-primary)]"
          />
          <label className="text-sm font-medium text-[var(--text-primary)]">{t('productionBatch.priorityResources.specialRecipe')}</label>
        </div>
      </div>

      <div>
        <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
          <Users className="w-4 h-4 inline mr-1.5" />
          {t('productionBatch.priorityResources.assignedStaff')}
        </label>
        <input
          type="text"
          value={getValue('staff_assigned_string', '')}
          onChange={(e) => handleFieldChange({ staff_assigned_string: e.target.value })}
          placeholder={t('productionBatch.priorityResources.staffPlaceholder')}
          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)]"
        />
        <p className="text-xs text-[var(--text-tertiary)] mt-1">{t('productionBatch.priorityResources.staffHint')}</p>
      </div>

      <div>
        <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
          {t('productionBatch.priorityResources.productionNotes')}
        </label>
        <textarea
          value={getValue('production_notes')}
          onChange={(e) => handleFieldChange({ production_notes: e.target.value })}
          placeholder={t('productionBatch.priorityResources.notesPlaceholder')}
          rows={4}
          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 title={t('productionBatch.advancedOptions.title')} description={t('productionBatch.advancedOptions.description')}>
        <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('productionBatch.advancedOptions.stationId')}</label>
            <input
              type="text"
              value={getValue('station_id')}
              onChange={(e) => handleFieldChange({ station_id: e.target.value })}
              placeholder={t('productionBatch.advancedOptions.stationPlaceholder')}
              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('productionBatch.advancedOptions.orderId')}</label>
            <input
              type="text"
              value={getValue('order_id')}
              onChange={(e) => handleFieldChange({ order_id: e.target.value })}
              placeholder={t('productionBatch.advancedOptions.orderPlaceholder')}
              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('productionBatch.advancedOptions.forecastId')}</label>
            <input
              type="text"
              value={getValue('forecast_id')}
              onChange={(e) => handleFieldChange({ forecast_id: e.target.value })}
              placeholder={t('productionBatch.advancedOptions.forecastPlaceholder')}
              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>
      </AdvancedOptionsSection>
    </div>
  );
};

// Step 4: Review
const ReviewStep: React.FC<WizardStepProps> = ({ dataRef, onDataChange }) => {
  const data = dataRef?.current || {};
  const { t } = useTranslation(['wizards', 'production']);

  return (
    <div className="space-y-6">
      <div className="text-center pb-4 border-b border-[var(--border-primary)]">
        <CheckCircle2 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('productionBatch.review.title')}</h3>
        <p className="text-sm text-[var(--text-secondary)]">{t('productionBatch.review.description')}</p>
      </div>

      {/* Product Info */}
      <div className="p-4 bg-[var(--bg-secondary)]/50 rounded-lg border border-[var(--border-secondary)]">
        <h4 className="font-semibold text-[var(--text-primary)] mb-3 flex items-center gap-2">
          <Package className="w-5 h-5" />
          {t('productionBatch.review.productInfo')}
        </h4>
        <div className="space-y-2 text-sm">
          <div className="flex justify-between">
            <span className="text-[var(--text-secondary)]">{t('productionBatch.review.product')}:</span>
            <span className="font-medium">{data.product_name || 'N/A'}</span>
          </div>
          <div className="flex justify-between">
            <span className="text-[var(--text-secondary)]">{t('productionBatch.review.recipe')}:</span>
            <span className="font-medium">{data.selectedRecipe?.name || t('productionBatch.review.noSpecificRecipe')}</span>
          </div>
          {data.batch_number && (
            <div className="flex justify-between">
              <span className="text-[var(--text-secondary)]">{t('productionBatch.review.batchNumber')}:</span>
              <span className="font-medium">{data.batch_number}</span>
            </div>
          )}
        </div>
      </div>

      {/* Planning Info */}
      <div className="p-4 bg-[var(--bg-secondary)]/50 rounded-lg border border-[var(--border-secondary)]">
        <h4 className="font-semibold text-[var(--text-primary)] mb-3 flex items-center gap-2">
          <Clock className="w-5 h-5" />
          {t('productionBatch.review.productionPlanning')}
        </h4>
        <div className="space-y-2 text-sm">
          <div className="flex justify-between">
            <span className="text-[var(--text-secondary)]">{t('productionBatch.review.start')}:</span>
            <span className="font-medium">
              {data.planned_start_time
                ? new Date(data.planned_start_time).toLocaleString('es-ES')
                : t('productionBatch.review.notSpecified')}
            </span>
          </div>
          <div className="flex justify-between">
            <span className="text-[var(--text-secondary)]">{t('productionBatch.review.end')}:</span>
            <span className="font-medium">
              {data.planned_end_time ? new Date(data.planned_end_time).toLocaleString('es-ES') : t('productionBatch.review.notSpecified')}
            </span>
          </div>
          <div className="flex justify-between">
            <span className="text-[var(--text-secondary)]">{t('productionBatch.review.duration')}:</span>
            <span className="font-medium">
              {data.planned_duration_minutes} {t('productionBatch.review.minutes')} ({(data.planned_duration_minutes / 60).toFixed(1)} {t('productionBatch.review.hours')})
            </span>
          </div>
          <div className="flex justify-between">
            <span className="text-[var(--text-secondary)]">{t('productionBatch.review.quantity')}:</span>
            <span className="font-medium">{data.planned_quantity} {t('productionBatch.review.units')}</span>
          </div>
        </div>
      </div>

      {/* Priority & Resources */}
      <div className="p-4 bg-[var(--bg-secondary)]/50 rounded-lg border border-[var(--border-secondary)]">
        <h4 className="font-semibold text-[var(--text-primary)] mb-3 flex items-center gap-2">
          <AlertCircle className="w-5 h-5" />
          {t('productionBatch.review.priorityAndResources')}
        </h4>
        <div className="space-y-2 text-sm">
          <div className="flex justify-between">
            <span className="text-[var(--text-secondary)]">{t('productionBatch.review.priority')}:</span>
            <span className="font-medium capitalize">{data.priority || ProductionPriorityEnum.MEDIUM}</span>
          </div>
          <div className="flex justify-between">
            <span className="text-[var(--text-secondary)]">{t('productionBatch.review.rushOrder')}:</span>
            <span className="font-medium">{data.is_rush_order ? t('productionBatch.review.yes') : t('productionBatch.review.no')}</span>
          </div>
          <div className="flex justify-between">
            <span className="text-[var(--text-secondary)]">{t('productionBatch.review.specialRecipe')}:</span>
            <span className="font-medium">{data.is_special_recipe ? t('productionBatch.review.yes') : t('productionBatch.review.no')}</span>
          </div>
          {data.staff_assigned_string && (
            <div className="pt-2 border-t border-[var(--border-primary)]">
              <span className="text-[var(--text-secondary)] block mb-1">{t('productionBatch.review.assignedStaff')}:</span>
              <span className="font-medium">{data.staff_assigned_string}</span>
            </div>
          )}
          {data.production_notes && (
            <div className="pt-2 border-t border-[var(--border-primary)]">
              <span className="text-[var(--text-secondary)] block mb-1">{t('productionBatch.review.notes')}:</span>
              <span className="font-medium">{data.production_notes}</span>
            </div>
          )}
        </div>
      </div>

      {/* Quality Requirements Preview */}
      {data.selectedRecipe?.quality_check_configuration?.stages && (
        <Card className="p-4 bg-blue-50 border-blue-200">
          <h4 className="font-medium text-[var(--text-primary)] mb-3 flex items-center gap-2">
            <ClipboardCheck className="w-5 h-5 text-blue-600" />
            {t('productionBatch.review.qualityControlsRequired')}
          </h4>
          <div className="space-y-2">
            {Object.entries(data.selectedRecipe.quality_check_configuration.stages).map(
              ([stage, config]: [string, any]) => {
                if (!config.template_ids || config.template_ids.length === 0) return null;

                return (
                  <div key={stage} className="flex items-center gap-2 text-sm">
                    <Badge variant="info">{t(`productionBatch.additionalDetails.stages.${getStageLabelKey(stage as ProcessStage)}`)}</Badge>
                    <span className="text-[var(--text-secondary)]">
                      {config.template_ids.length} {config.template_ids.length > 1 ? t('productionBatch.review.controls') : t('productionBatch.review.control')}
                    </span>
                    {config.blocking && <Badge variant="warning" size="sm">{t('productionBatch.review.blocking')}</Badge>}
                    {config.is_required && <Badge variant="error" size="sm">{t('productionBatch.review.required')}</Badge>}
                  </div>
                );
              }
            )}
          </div>
        </Card>
      )}
    </div>
  );
};

export const ProductionBatchWizardSteps = (
  dataRef: React.MutableRefObject<Record<string, any>>,
  _setData: (data: Record<string, any>) => void
): WizardStep[] => {
  return [
    {
      id: 'product-recipe',
      title: 'Producto y Receta',
      component: ProductRecipeStep,
      validate: () => {
        const data = dataRef.current;
        if (!data.product_id) {
          throw new Error('Debes seleccionar un producto');
        }
        return true;
      },
    },
    {
      id: 'planning-details',
      title: 'Planificación',
      component: PlanningDetailsStep,
      validate: () => {
        const data = dataRef.current;
        if (!data.planned_start_time) {
          throw new Error('Debes especificar la fecha y hora de inicio');
        }
        if (!data.planned_duration_minutes || data.planned_duration_minutes <= 0) {
          throw new Error('La duración debe ser mayor a 0 minutos');
        }
        if (!data.planned_quantity || data.planned_quantity <= 0) {
          throw new Error('La cantidad debe ser mayor a 0');
        }
        if (data.planned_end_time && new Date(data.planned_end_time) <= new Date(data.planned_start_time)) {
          throw new Error('La fecha de fin debe ser posterior a la fecha de inicio');
        }
        return true;
      },
    },
    {
      id: 'priority-resources',
      title: 'Prioridad y Recursos',
      component: PriorityResourcesStep,
    },
    {
      id: 'review',
      title: 'Revisar y Confirmar',
      component: ReviewStep,
    },
  ];
};
