import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { WizardStep, WizardStepProps } from '../../../ui/WizardModal/WizardModal';
import { AdvancedOptionsSection } from '../../../ui/AdvancedOptionsSection';
import { KeyValueEditor } from '../../../ui/KeyValueEditor/KeyValueEditor';
import Tooltip from '../../../ui/Tooltip/Tooltip';
import {
  Info,
  Eye,
  Ruler,
  Thermometer,
  Weight,
  CheckSquare,
  Clock,
  ClipboardList
} from 'lucide-react';

// STEP 1: Quality Check Type Selection
const QualityCheckTypeStep: React.FC<WizardStepProps> = ({ dataRef, onDataChange }) => {
  const data = dataRef?.current || {};
  const { t } = useTranslation('wizards');

  const handleTypeSelect = (type: string) => {
    onDataChange?.({ ...data, checkType: type });
  };

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

  const checkTypes = [
    {
      value: 'visual',
      icon: Eye,
      titleKey: 'qualityTemplate.checkTypes.visual',
      descriptionKey: 'qualityTemplate.checkTypeDescriptions.visual'
    },
    {
      value: 'measurement',
      icon: Ruler,
      titleKey: 'qualityTemplate.checkTypes.measurement',
      descriptionKey: 'qualityTemplate.checkTypeDescriptions.measurement'
    },
    {
      value: 'temperature',
      icon: Thermometer,
      titleKey: 'qualityTemplate.checkTypes.temperature',
      descriptionKey: 'qualityTemplate.checkTypeDescriptions.temperature'
    },
    {
      value: 'weight',
      icon: Weight,
      titleKey: 'qualityTemplate.checkTypes.weight',
      descriptionKey: 'qualityTemplate.checkTypeDescriptions.weight'
    },
    {
      value: 'boolean',
      icon: CheckSquare,
      titleKey: 'qualityTemplate.checkTypes.boolean',
      descriptionKey: 'qualityTemplate.checkTypeDescriptions.boolean'
    },
    {
      value: 'timing',
      icon: Clock,
      titleKey: 'qualityTemplate.checkTypes.timing',
      descriptionKey: 'qualityTemplate.checkTypeDescriptions.timing'
    },
    {
      value: 'checklist',
      icon: ClipboardList,
      titleKey: 'qualityTemplate.checkTypes.checklist',
      descriptionKey: 'qualityTemplate.checkTypeDescriptions.checklist'
    }
  ];

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="text-center pb-4 border-b border-[var(--border-primary)]">
        <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-2">
          {t('qualityTemplate.selectCheckType')}
        </h3>
        <p className="text-sm text-[var(--text-secondary)]">
          {t('qualityTemplate.selectCheckTypeDescription')}
        </p>
      </div>

      {/* Check Type Cards */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        {checkTypes.map((type) => {
          const IconComponent = type.icon;
          const isSelected = data.checkType === type.value;

          return (
            <button
              key={type.value}
              type="button"
              onClick={() => handleTypeSelect(type.value)}
              className={`p-5 border-2 rounded-lg transition-all text-left ${
                isSelected
                  ? 'border-[var(--color-primary)] bg-[var(--color-primary)]/5 shadow-md'
                  : 'border-[var(--border-secondary)] hover:border-[var(--color-primary)]/50'
              }`}
            >
              <div className="flex items-start gap-4">
                <div
                  className={`p-3 rounded-lg ${
                    isSelected
                      ? 'bg-[var(--color-primary)] text-white'
                      : 'bg-[var(--bg-secondary)] text-[var(--text-tertiary)]'
                  }`}
                >
                  <IconComponent className="w-6 h-6" />
                </div>
                <div className="flex-1">
                  <h3 className="font-semibold text-[var(--text-primary)] mb-1">
                    {t(type.titleKey)}
                  </h3>
                  <p className="text-sm text-[var(--text-secondary)]">
                    {t(type.descriptionKey)}
                  </p>
                </div>
              </div>
            </button>
          );
        })}
      </div>

      {/* Advanced Options */}
      <AdvancedOptionsSection
        title={t('qualityTemplate.sections.additionalIdentifiers')}
        description={t('qualityTemplate.sections.additionalIdentifiersDescription')}
      >
        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {/* Template Code */}
          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              {t('qualityTemplate.fields.templateCode')}
              <Tooltip content={t('qualityTemplate.fields.templateCodeTooltip')}>
                <Info className="inline w-4 h-4 ml-1 text-[var(--text-tertiary)]" />
              </Tooltip>
            </label>
            <input
              type="text"
              value={data.templateCode || ''}
              onChange={(e) => handleFieldChange('templateCode', e.target.value)}
              placeholder={t('qualityTemplate.fields.templateCodePlaceholder')}
              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>

          {/* Category */}
          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              {t('qualityTemplate.fields.category')}
            </label>
            <input
              type="text"
              value={data.category || ''}
              onChange={(e) => handleFieldChange('category', e.target.value)}
              placeholder={t('qualityTemplate.fields.categoryPlaceholder')}
              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 2: Essential Configuration
const EssentialConfigurationStep: React.FC<WizardStepProps> = ({ dataRef, onDataChange }) => {
  const data = dataRef?.current || {};
  const { t } = useTranslation('wizards');

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

  const handleStageToggle = (stage: string) => {
    const currentStages = data.applicableStages || [];
    const newStages = currentStages.includes(stage)
      ? currentStages.filter((s: string) => s !== stage)
      : [...currentStages, stage];
    handleFieldChange('applicableStages', newStages);
  };

  const isMeasurementType = ['measurement', 'temperature', 'weight'].includes(data.checkType);

  const processStages = [
    'mixing',
    'proofing',
    'shaping',
    'baking',
    'cooling',
    'packaging',
    'finishing'
  ];

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="text-center pb-4 border-b border-[var(--border-primary)]">
        <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-2">
          {t('qualityTemplate.essentialConfiguration')}
        </h3>
        <p className="text-sm text-[var(--text-secondary)]">
          {t('qualityTemplate.essentialConfigurationDescription')}
        </p>
      </div>

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

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

        {/* Weight */}
        <div>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
            {t('qualityTemplate.fields.weight')} *
            <Tooltip content={t('qualityTemplate.fields.weightTooltip')}>
              <Info className="inline w-4 h-4 ml-1 text-[var(--text-tertiary)]" />
            </Tooltip>
          </label>
          <input
            type="number"
            value={data.weight || 5.0}
            onChange={(e) => handleFieldChange('weight', parseFloat(e.target.value))}
            placeholder="5.0"
            step="0.1"
            min="0"
            max="10"
            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>

        {/* Applicable Stages */}
        <div>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
            {t('qualityTemplate.fields.applicableStages')}
            <Tooltip content={t('qualityTemplate.fields.applicableStagesTooltip')}>
              <Info className="inline w-4 h-4 ml-1 text-[var(--text-tertiary)]" />
            </Tooltip>
          </label>
          <div className="flex flex-wrap gap-2">
            {processStages.map((stage) => {
              const isSelected = (data.applicableStages || []).includes(stage);
              return (
                <button
                  key={stage}
                  type="button"
                  onClick={() => handleStageToggle(stage)}
                  className={`px-3 py-1.5 rounded-full text-sm font-medium transition-colors ${
                    isSelected
                      ? 'bg-[var(--color-primary)] text-white'
                      : 'bg-[var(--bg-secondary)] text-[var(--text-secondary)] hover:bg-[var(--color-primary)]/10'
                  }`}
                >
                  {t(`qualityTemplate.processStages.${stage}`)}
                </button>
              );
            })}
          </div>
          <p className="text-xs text-[var(--text-tertiary)] mt-2">
            {t('qualityTemplate.fields.applicableStagesHelp')}
          </p>
        </div>
      </div>

      {/* Measurement-Specific Fields */}
      {isMeasurementType && (
        <div className="border-t border-[var(--border-primary)] pt-4">
          <h4 className="text-sm font-semibold text-[var(--text-primary)] mb-3">
            {t('qualityTemplate.sections.measurementSpecifications')}
          </h4>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            {/* Min Value */}
            <div>
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                {t('qualityTemplate.fields.minValue')}
              </label>
              <input
                type="number"
                value={data.minValue || ''}
                onChange={(e) => handleFieldChange('minValue', e.target.value ? parseFloat(e.target.value) : null)}
                placeholder="0"
                step="0.01"
                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>

            {/* Max Value */}
            <div>
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                {t('qualityTemplate.fields.maxValue')}
              </label>
              <input
                type="number"
                value={data.maxValue || ''}
                onChange={(e) => handleFieldChange('maxValue', e.target.value ? parseFloat(e.target.value) : null)}
                placeholder="100"
                step="0.01"
                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>

            {/* Target Value */}
            <div>
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                {t('qualityTemplate.fields.targetValue')}
              </label>
              <input
                type="number"
                value={data.targetValue || ''}
                onChange={(e) => handleFieldChange('targetValue', e.target.value ? parseFloat(e.target.value) : null)}
                placeholder="50"
                step="0.01"
                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>

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

            {/* Tolerance Percentage */}
            <div className="md:col-span-2">
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                {t('qualityTemplate.fields.tolerancePercentage')}
                <Tooltip content={t('qualityTemplate.fields.toleranceTooltip')}>
                  <Info className="inline w-4 h-4 ml-1 text-[var(--text-tertiary)]" />
                </Tooltip>
              </label>
              <input
                type="number"
                value={data.tolerancePercentage || ''}
                onChange={(e) => handleFieldChange('tolerancePercentage', e.target.value ? parseFloat(e.target.value) : null)}
                placeholder="5.0"
                step="0.1"
                min="0"
                max="100"
                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>
      )}

      {/* Advanced Options */}
      <AdvancedOptionsSection
        title={t('qualityTemplate.sections.additionalDetails')}
        description={t('qualityTemplate.sections.additionalDetailsDescription')}
      >
        <div className="space-y-4">
          {/* Instructions */}
          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              {t('qualityTemplate.fields.instructions')}
            </label>
            <textarea
              value={data.instructions || ''}
              onChange={(e) => handleFieldChange('instructions', e.target.value)}
              placeholder={t('qualityTemplate.fields.instructionsPlaceholder')}
              rows={3}
              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 3: Quality Criteria & Settings
const QualityCriteriaSettingsStep: React.FC<WizardStepProps> = ({ dataRef, onDataChange }) => {
  const data = dataRef?.current || {};
  const { t } = useTranslation('wizards');

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

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="text-center pb-4 border-b border-[var(--border-primary)]">
        <h3 className="text-lg font-semibold text-[var(--text-primary)] mb-2">
          {t('qualityTemplate.criteriaAndSettings')}
        </h3>
        <p className="text-sm text-[var(--text-secondary)]">
          {t('qualityTemplate.criteriaAndSettingsDescription')}
        </p>
      </div>

      {/* Scoring Configuration */}
      <div className="space-y-4">
        <h4 className="text-sm font-semibold text-[var(--text-primary)]">
          {t('qualityTemplate.sections.scoringConfiguration')}
        </h4>

        <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
          {/* Scoring Method */}
          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              {t('qualityTemplate.fields.scoringMethod')}
            </label>
            <select
              value={data.scoringMethod || 'weighted_average'}
              onChange={(e) => handleFieldChange('scoringMethod', 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="weighted_average">{t('qualityTemplate.scoringMethods.weightedAverage')}</option>
              <option value="pass_fail">{t('qualityTemplate.scoringMethods.passFail')}</option>
              <option value="percentage">{t('qualityTemplate.scoringMethods.percentage')}</option>
              <option value="points">{t('qualityTemplate.scoringMethods.pointsBased')}</option>
            </select>
          </div>

          {/* Pass Threshold */}
          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              {t('qualityTemplate.fields.passThreshold')}
              <Tooltip content={t('qualityTemplate.fields.passThresholdTooltip')}>
                <Info className="inline w-4 h-4 ml-1 text-[var(--text-tertiary)]" />
              </Tooltip>
            </label>
            <input
              type="number"
              value={data.passThreshold || 70}
              onChange={(e) => handleFieldChange('passThreshold', parseFloat(e.target.value))}
              placeholder="70.0"
              step="0.1"
              min="0"
              max="100"
              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>

          {/* Frequency Days */}
          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              {t('qualityTemplate.fields.frequencyDays')}
              <Tooltip content={t('qualityTemplate.fields.frequencyDaysTooltip')}>
                <Info className="inline w-4 h-4 ml-1 text-[var(--text-tertiary)]" />
              </Tooltip>
            </label>
            <input
              type="number"
              value={data.frequencyDays || ''}
              onChange={(e) => handleFieldChange('frequencyDays', e.target.value ? parseInt(e.target.value) : null)}
              placeholder={t('qualityTemplate.fields.frequencyDaysPlaceholder')}
              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>

          {/* Is Required */}
          <div className="flex items-center gap-2">
            <input
              type="checkbox"
              checked={data.isRequired || false}
              onChange={(e) => handleFieldChange('isRequired', e.target.checked)}
              className="rounded border-[var(--border-secondary)] text-[var(--color-primary)] focus:ring-[var(--color-primary)]"
            />
            <label className="text-sm text-[var(--text-secondary)]">
              {t('qualityTemplate.fields.requiredCheck')}
            </label>
          </div>
        </div>
      </div>

      {/* Advanced Options */}
      <AdvancedOptionsSection
        title={t('qualityTemplate.sections.advancedOptions')}
        description={t('qualityTemplate.sections.advancedOptionsDescription')}
      >
        {/* Check Points Configuration */}
        <div className="space-y-4">
          <h5 className="text-xs font-semibold text-[var(--text-secondary)] uppercase tracking-wider">
            {t('qualityTemplate.sections.checkPointsConfiguration')}
          </h5>
          <div className="grid grid-cols-1 gap-4">
            <div>
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                {t('qualityTemplate.fields.checkPointsJsonArray')}
                <Tooltip content={t('qualityTemplate.fields.checkPointsTooltip')}>
                  <Info className="inline w-4 h-4 ml-1 text-[var(--text-tertiary)]" />
                </Tooltip>
              </label>
              <textarea
                value={data.checkPoints || ''}
                onChange={(e) => handleFieldChange('checkPoints', e.target.value)}
                placeholder={t('qualityTemplate.fields.checkPointsPlaceholder')}
                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)] font-mono text-xs"
              />
            </div>

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

        {/* JSONB Configuration Fields */}
        <div className="space-y-4 border-t border-[var(--border-primary)] pt-4">
          <h5 className="text-xs font-semibold text-[var(--text-secondary)] uppercase tracking-wider">
            {t('qualityTemplate.sections.advancedConfiguration')}
          </h5>
          <div className="space-y-6">
            {/* Parameters */}
            <KeyValueEditor
              label={t('qualityTemplate.fields.parametersJson')}
              tooltip={t('qualityTemplate.fields.parametersTooltip')}
              value={data.parameters}
              onChange={(value) => handleFieldChange('parameters', value)}
              placeholder="{}"
              suggestions={
                data.checkType === 'temperature'
                  ? [
                      { key: 'temp_min', value: '75', type: 'number' },
                      { key: 'temp_max', value: '85', type: 'number' },
                      { key: 'humidity', value: '65', type: 'number' }
                    ]
                  : data.checkType === 'weight'
                  ? [
                      { key: 'weight_min', value: '450', type: 'number' },
                      { key: 'weight_max', value: '550', type: 'number' },
                      { key: 'unit', value: 'g', type: 'string' }
                    ]
                  : []
              }
            />

            {/* Thresholds */}
            <KeyValueEditor
              label={t('qualityTemplate.fields.thresholdsJson')}
              tooltip={t('qualityTemplate.fields.thresholdsTooltip')}
              value={data.thresholds}
              onChange={(value) => handleFieldChange('thresholds', value)}
              placeholder="{}"
              suggestions={[
                { key: 'critical', value: '90', type: 'number' },
                { key: 'warning', value: '70', type: 'number' },
                { key: 'acceptable', value: '50', type: 'number' }
              ]}
            />

            {/* Scoring Criteria */}
            <KeyValueEditor
              label={t('qualityTemplate.fields.scoringCriteriaJson')}
              tooltip={t('qualityTemplate.fields.scoringCriteriaTooltip')}
              value={data.scoringCriteria}
              onChange={(value) => handleFieldChange('scoringCriteria', value)}
              placeholder="{}"
              suggestions={[
                { key: 'appearance', value: '30', type: 'number' },
                { key: 'texture', value: '30', type: 'number' },
                { key: 'taste', value: '40', type: 'number' }
              ]}
            />
          </div>
        </div>

        {/* Responsibility & Requirements */}
        <div className="space-y-4 border-t border-[var(--border-primary)] pt-4">
          <h5 className="text-xs font-semibold text-[var(--text-secondary)] uppercase tracking-wider">
            {t('qualityTemplate.sections.responsibilityRequirements')}
          </h5>
          <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('qualityTemplate.fields.responsibleRole')}
              </label>
              <input
                type="text"
                value={data.responsibleRole || ''}
                onChange={(e) => handleFieldChange('responsibleRole', e.target.value)}
                placeholder={t('qualityTemplate.fields.responsibleRolePlaceholder')}
                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('qualityTemplate.fields.requiredEquipment')}
              </label>
              <input
                type="text"
                value={data.requiredEquipment || ''}
                onChange={(e) => handleFieldChange('requiredEquipment', e.target.value)}
                placeholder={t('qualityTemplate.fields.requiredEquipmentPlaceholder')}
                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="md:col-span-2">
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                {t('qualityTemplate.fields.specificConditions')}
              </label>
              <textarea
                value={data.specificConditions || ''}
                onChange={(e) => handleFieldChange('specificConditions', e.target.value)}
                placeholder={t('qualityTemplate.fields.specificConditionsPlaceholder')}
                rows={2}
                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>

        {/* Control Settings */}
        <div className="space-y-4 border-t border-[var(--border-primary)] pt-4">
          <h5 className="text-xs font-semibold text-[var(--text-secondary)] uppercase tracking-wider">
            {t('qualityTemplate.sections.controlSettings')}
          </h5>
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div className="flex items-center gap-2">
              <input
                type="checkbox"
                checked={data.isActive !== false}
                onChange={(e) => handleFieldChange('isActive', e.target.checked)}
                className="rounded border-[var(--border-secondary)] text-[var(--color-primary)] focus:ring-[var(--color-primary)]"
              />
              <label className="text-sm text-[var(--text-secondary)]">
                {t('qualityTemplate.fields.activeTemplate')}
              </label>
            </div>

            <div className="flex items-center gap-2">
              <input
                type="checkbox"
                checked={data.requiresPhoto || false}
                onChange={(e) => handleFieldChange('requiresPhoto', e.target.checked)}
                className="rounded border-[var(--border-secondary)] text-[var(--color-primary)] focus:ring-[var(--color-primary)]"
              />
              <label className="text-sm text-[var(--text-secondary)]">
                {t('qualityTemplate.fields.requiresPhotoEvidence')}
              </label>
            </div>

            <div className="flex items-center gap-2">
              <input
                type="checkbox"
                checked={data.isCritical || false}
                onChange={(e) => handleFieldChange('isCritical', e.target.checked)}
                className="rounded border-[var(--border-secondary)] text-[var(--color-primary)] focus:ring-[var(--color-primary)]"
              />
              <label className="text-sm text-[var(--text-secondary)]">
                {t('qualityTemplate.fields.criticalControlPoint')}
              </label>
            </div>

            <div className="flex items-center gap-2">
              <input
                type="checkbox"
                checked={data.notifyOnFail || false}
                onChange={(e) => handleFieldChange('notifyOnFail', e.target.checked)}
                className="rounded border-[var(--border-secondary)] text-[var(--color-primary)] focus:ring-[var(--color-primary)]"
              />
              <label className="text-sm text-[var(--text-secondary)]">
                {t('qualityTemplate.fields.notifyOnFailure')}
              </label>
            </div>
          </div>
        </div>
      </AdvancedOptionsSection>
    </div>
  );
};

export const QualityTemplateWizardSteps = (
  dataRef: React.MutableRefObject<Record<string, any>>,
  setData: (data: Record<string, any>) => void
): WizardStep[] => {
  return [
    {
      id: 'check-type',
      title: 'qualityTemplate.steps.checkType',
      component: QualityCheckTypeStep,
      validate: () => {
        return !!dataRef.current.checkType;
      },
    },
    {
      id: 'essential-configuration',
      title: 'qualityTemplate.steps.essentialConfiguration',
      component: EssentialConfigurationStep,
      validate: () => {
        const name = dataRef.current.name;
        const weight = dataRef.current.weight;
        return !!(
          name &&
          name.trim().length >= 1 &&
          weight !== undefined &&
          weight >= 0 &&
          weight <= 10
        );
      },
    },
    {
      id: 'criteria-settings',
      title: 'qualityTemplate.steps.criteriaSettings',
      component: QualityCriteriaSettingsStep,
      validate: () => {
        // Optional step - all fields are optional
        return true;
      },
    },
  ];
};
