import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { WizardStep, WizardStepProps } from '../../../ui/WizardModal/WizardModal';
import { AdvancedOptionsSection } from '../../../ui/AdvancedOptionsSection';
import Tooltip from '../../../ui/Tooltip/Tooltip';
import { Info } from 'lucide-react';

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

// Single comprehensive step with all fields
const QualityTemplateDetailsStep: React.FC<WizardDataProps> = ({ data, onDataChange }) => {
  const { t } = useTranslation('wizards');
  const [templateData, setTemplateData] = useState({
    // Required fields
    name: data.name || '',
    checkType: data.checkType || 'product_quality',
    weight: data.weight || '5.0',

    // Basic fields
    templateCode: data.templateCode || '',
    description: data.description || '',
    applicableStages: data.applicableStages || '',

    // Check points configuration
    checkPoints: data.checkPoints || '',

    // Scoring configuration
    scoringMethod: data.scoringMethod || 'weighted_average',
    passThreshold: data.passThreshold || '70.0',
    isRequired: data.isRequired ?? false,
    frequencyDays: data.frequencyDays || '',

    // Advanced configuration (JSONB fields)
    parameters: data.parameters || '',
    thresholds: data.thresholds || '',
    scoringCriteria: data.scoringCriteria || '',

    // Status
    isActive: data.isActive ?? true,
    version: data.version || '1.0',

    // Helper fields for UI
    requiresPhoto: data.requiresPhoto ?? false,
    criticalControlPoint: data.criticalControlPoint ?? false,
    notifyOnFail: data.notifyOnFail ?? false,
    responsibleRole: data.responsibleRole || '',
    requiredEquipment: data.requiredEquipment || '',
    acceptanceCriteria: data.acceptanceCriteria || '',
    specificConditions: data.specificConditions || '',
  });

  // Update parent whenever local state changes
  const handleDataChange = (newTemplateData: any) => {
    setTemplateData(newTemplateData);
    onDataChange({ ...data, ...newTemplateData });
  };

  return (
    <div className="space-y-6">
      <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.templateDetails')}
        </h3>
        <p className="text-sm text-[var(--text-secondary)]">
          {t('qualityTemplate.fillRequiredInfo')}
        </p>
      </div>

      {/* Required Fields */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div className="md:col-span-2">
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
            {t('qualityTemplate.fields.name')} *
          </label>
          <input
            type="text"
            value={templateData.name}
            onChange={(e) => handleDataChange({ ...templateData, 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>

        <div>
          <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
            {t('qualityTemplate.fields.checkType')} *
          </label>
          <select
            value={templateData.checkType}
            onChange={(e) => handleDataChange({ ...templateData, checkType: 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="product_quality">{t('qualityTemplate.checkTypes.product_quality')}</option>
            <option value="process_hygiene">{t('qualityTemplate.checkTypes.process_hygiene')}</option>
            <option value="equipment">{t('qualityTemplate.checkTypes.equipment')}</option>
            <option value="safety">{t('qualityTemplate.checkTypes.safety')}</option>
            <option value="cleaning">{t('qualityTemplate.checkTypes.cleaning')}</option>
            <option value="temperature">{t('qualityTemplate.checkTypes.temperature')}</option>
            <option value="documentation">{t('qualityTemplate.checkTypes.documentation')}</option>
          </select>
        </div>

        <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={templateData.weight}
            onChange={(e) => handleDataChange({ ...templateData, weight: 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>
      </div>

      {/* Basic Information */}
      <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.basicInformation')}</h4>
        <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.templateCode')} ({t('common.optional')})
              <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={templateData.templateCode}
              onChange={(e) => handleDataChange({ ...templateData, 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>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              {t('qualityTemplate.fields.version')}
            </label>
            <input
              type="text"
              value={templateData.version}
              onChange={(e) => handleDataChange({ ...templateData, version: e.target.value })}
              placeholder="1.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 className="md:col-span-2">
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              {t('qualityTemplate.fields.description')}
            </label>
            <textarea
              value={templateData.description}
              onChange={(e) => handleDataChange({ ...templateData, description: e.target.value })}
              placeholder={t('qualityTemplate.fields.descriptionPlaceholder')}
              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 className="md:col-span-2">
            <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>
            <input
              type="text"
              value={templateData.applicableStages}
              onChange={(e) => handleDataChange({ ...templateData, applicableStages: e.target.value })}
              placeholder={t('qualityTemplate.fields.applicablePlaceholder')}
              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>

      {/* Scoring Configuration */}
      <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.scoringConfiguration')}</h4>
        <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.scoringMethods.scoringMethod')}
            </label>
            <select
              value={templateData.scoringMethod}
              onChange={(e) => handleDataChange({ ...templateData, 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>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              {t('qualityTemplate.advancedFields.passThresholdPercent')}
              <Tooltip content={t('tooltips.passThreshold')}>
                <Info className="inline w-4 h-4 ml-1 text-[var(--text-tertiary)]" />
              </Tooltip>
            </label>
            <input
              type="number"
              value={templateData.passThreshold}
              onChange={(e) => handleDataChange({ ...templateData, passThreshold: 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>

          <div>
            <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
              {t('qualityTemplate.advancedFields.frequencyDays')}
              <Tooltip content={t('tooltips.frequencyDays')}>
                <Info className="inline w-4 h-4 ml-1 text-[var(--text-tertiary)]" />
              </Tooltip>
            </label>
            <input
              type="number"
              value={templateData.frequencyDays}
              onChange={(e) => handleDataChange({ ...templateData, frequencyDays: e.target.value })}
              placeholder={t('qualityTemplate.advancedFields.frequencyPlaceholder')}
              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 className="flex items-center gap-2">
            <input
              type="checkbox"
              checked={templateData.isRequired}
              onChange={(e) => handleDataChange({ ...templateData, 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.advancedFields.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.advancedFields.checkPointsJsonArray')}
                <Tooltip content={t('qualityTemplate.advancedFields.checkPointsTooltip')}>
                  <Info className="inline w-4 h-4 ml-1 text-[var(--text-tertiary)]" />
                </Tooltip>
              </label>
              <textarea
                value={templateData.checkPoints}
                onChange={(e) => handleDataChange({ ...templateData, checkPoints: e.target.value })}
                placeholder={t('qualityTemplate.advancedFields.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.advancedFields.acceptanceCriteria')}
              </label>
              <textarea
                value={templateData.acceptanceCriteria}
                onChange={(e) => handleDataChange({ ...templateData, acceptanceCriteria: e.target.value })}
                placeholder={t('qualityTemplate.advancedFields.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="grid grid-cols-1 gap-4">
            <div>
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                {t('qualityTemplate.advancedFields.parametersJson')}
                <Tooltip content={t('qualityTemplate.advancedFields.parametersTooltip')}>
                  <Info className="inline w-4 h-4 ml-1 text-[var(--text-tertiary)]" />
                </Tooltip>
              </label>
              <textarea
                value={templateData.parameters}
                onChange={(e) => handleDataChange({ ...templateData, parameters: e.target.value })}
                placeholder={t('qualityTemplate.advancedFields.parametersPlaceholder')}
                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)] font-mono text-xs"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                {t('qualityTemplate.advancedFields.thresholdsJson')}
                <Tooltip content={t('qualityTemplate.advancedFields.thresholdsTooltip')}>
                  <Info className="inline w-4 h-4 ml-1 text-[var(--text-tertiary)]" />
                </Tooltip>
              </label>
              <textarea
                value={templateData.thresholds}
                onChange={(e) => handleDataChange({ ...templateData, thresholds: e.target.value })}
                placeholder={t('qualityTemplate.advancedFields.thresholdsPlaceholder')}
                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)] font-mono text-xs"
              />
            </div>

            <div>
              <label className="block text-sm font-medium text-[var(--text-secondary)] mb-2">
                {t('qualityTemplate.advancedFields.scoringCriteriaJson')}
                <Tooltip content={t('qualityTemplate.advancedFields.scoringCriteriaTooltip')}>
                  <Info className="inline w-4 h-4 ml-1 text-[var(--text-tertiary)]" />
                </Tooltip>
              </label>
              <textarea
                value={templateData.scoringCriteria}
                onChange={(e) => handleDataChange({ ...templateData, scoringCriteria: e.target.value })}
                placeholder={t('qualityTemplate.advancedFields.scoringCriteriaPlaceholder')}
                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)] font-mono text-xs"
              />
            </div>
          </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.advancedFields.responsibleRole')}
              </label>
              <input
                type="text"
                value={templateData.responsibleRole}
                onChange={(e) => handleDataChange({ ...templateData, responsibleRole: e.target.value })}
                placeholder={t('qualityTemplate.advancedFields.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.advancedFields.requiredEquipment')}
              </label>
              <input
                type="text"
                value={templateData.requiredEquipment}
                onChange={(e) => handleDataChange({ ...templateData, requiredEquipment: e.target.value })}
                placeholder={t('qualityTemplate.advancedFields.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.advancedFields.specificConditions')}
              </label>
              <textarea
                value={templateData.specificConditions}
                onChange={(e) => handleDataChange({ ...templateData, specificConditions: e.target.value })}
                placeholder={t('qualityTemplate.advancedFields.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={templateData.isActive}
                onChange={(e) => handleDataChange({ ...templateData, 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.advancedFields.activeTemplate')}
              </label>
            </div>

            <div className="flex items-center gap-2">
              <input
                type="checkbox"
                checked={templateData.requiresPhoto}
                onChange={(e) => handleDataChange({ ...templateData, 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.advancedFields.requiresPhotoEvidence')}
              </label>
            </div>

            <div className="flex items-center gap-2">
              <input
                type="checkbox"
                checked={templateData.criticalControlPoint}
                onChange={(e) => handleDataChange({ ...templateData, criticalControlPoint: 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.advancedFields.criticalControlPoint')}
              </label>
            </div>

            <div className="flex items-center gap-2">
              <input
                type="checkbox"
                checked={templateData.notifyOnFail}
                onChange={(e) => handleDataChange({ ...templateData, 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.advancedFields.notifyOnFailure')}
              </label>
            </div>
          </div>
        </div>
      </AdvancedOptionsSection>
    </div>
  );
};

export const QualityTemplateWizardSteps = (
  data: Record<string, any>,
  setData: (data: Record<string, any>) => void
): WizardStep[] => [
  {
    id: 'template-details',
    title: 'qualityTemplate.advancedFields.templateDetailsTitle',
    component: (props) => <QualityTemplateDetailsStep {...props} data={data} onDataChange={setData} />,
    validate: () => {
      return !!(data.name && data.checkType && data.weight);
    },
  },
];
