import { cn } from '@/lib/utils'
import { Check, Wand2, Settings2, Ban, Eye } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import type { PreprocessingMode, PreprocessingConfig, PreprocessingContrast } from '@/types/apiV2'

interface PreprocessingSettingsProps {
  mode: PreprocessingMode
  config: PreprocessingConfig
  onModeChange: (mode: PreprocessingMode) => void
  onConfigChange: (config: PreprocessingConfig) => void
  onPreview?: () => void
  disabled?: boolean
  className?: string
}

const MODE_ICONS: Record<PreprocessingMode, React.ReactNode> = {
  auto: <Wand2 className="w-5 h-5" />,
  manual: <Settings2 className="w-5 h-5" />,
  disabled: <Ban className="w-5 h-5" />,
}

export default function PreprocessingSettings({
  mode,
  config,
  onModeChange,
  onConfigChange,
  onPreview,
  disabled = false,
  className,
}: PreprocessingSettingsProps) {
  const { t } = useTranslation()
  const modes: PreprocessingMode[] = ['auto', 'manual', 'disabled']
  const contrastOptions: PreprocessingContrast[] = ['none', 'histogram', 'clahe', 'document']

  const getModeInfo = (m: PreprocessingMode) => ({
    label: t(`processing.preprocessing.mode.${m}`),
    description: t(`processing.preprocessing.mode.${m}Desc`),
  })

  const handleConfigChange = (field: keyof PreprocessingConfig, value: any) => {
    onConfigChange({ ...config, [field]: value })
  }

  const getStrengthLabel = (value: number, type: 'contrast' | 'sharpen') => {
    if (type === 'contrast') {
      if (value <= 0.75) return t('processing.preprocessing.strength.subtle')
      if (value <= 1.25) return t('processing.preprocessing.strength.normal')
      if (value <= 2.0) return t('processing.preprocessing.strength.strong')
      return t('processing.preprocessing.strength.maximum')
    } else {
      if (value <= 0.75) return t('processing.preprocessing.strength.subtle')
      if (value <= 1.25) return t('processing.preprocessing.strength.normal')
      if (value <= 1.5) return t('processing.preprocessing.strength.strong')
      return t('processing.preprocessing.strength.maximum')
    }
  }

  return (
    <div className={cn('border rounded-lg p-4 bg-white', className)}>
      {/* Header */}
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center gap-2">
          <Wand2 className="w-5 h-5 text-gray-600" />
          <h3 className="text-lg font-semibold text-gray-900">
            {t('processing.preprocessing.title')}
          </h3>
        </div>
        {onPreview && mode !== 'disabled' && (
          <button
            type="button"
            onClick={onPreview}
            disabled={disabled}
            className={cn(
              'flex items-center gap-2 px-3 py-1.5 text-sm rounded-md transition-colors',
              'bg-gray-100 hover:bg-gray-200 text-gray-700',
              disabled && 'opacity-50 cursor-not-allowed'
            )}
          >
            <Eye className="w-4 h-4" />
            {t('processing.preprocessing.preview')}
          </button>
        )}
      </div>

      {/* Mode Selection */}
      <div className="space-y-2 mb-4">
        {modes.map((m) => {
          const info = getModeInfo(m)
          const isSelected = mode === m

          return (
            <button
              key={m}
              type="button"
              disabled={disabled}
              onClick={() => onModeChange(m)}
              className={cn(
                'w-full flex items-start gap-3 p-3 rounded-lg border transition-all text-left',
                isSelected
                  ? 'border-blue-500 bg-blue-50'
                  : 'border-gray-200 hover:border-gray-300 hover:bg-gray-50',
                disabled && 'opacity-50 cursor-not-allowed'
              )}
            >
              {/* Icon */}
              <div
                className={cn(
                  'p-1.5 rounded-md flex-shrink-0',
                  isSelected ? 'bg-blue-100 text-blue-600' : 'bg-gray-100 text-gray-500'
                )}
              >
                {MODE_ICONS[m]}
              </div>

              {/* Content */}
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2">
                  <span
                    className={cn(
                      'font-medium text-sm',
                      isSelected ? 'text-blue-700' : 'text-gray-900'
                    )}
                  >
                    {info.label}
                  </span>
                  {m === 'auto' && (
                    <span className="text-xs bg-green-100 text-green-700 px-1.5 py-0.5 rounded-full">
                      {t('processing.preprocessing.recommended')}
                    </span>
                  )}
                </div>
                <p className="text-xs text-gray-500 mt-0.5">{info.description}</p>
              </div>

              {/* Check mark */}
              {isSelected && (
                <div className="flex-shrink-0">
                  <Check className="w-4 h-4 text-blue-600" />
                </div>
              )}
            </button>
          )
        })}
      </div>

      {/* Manual Configuration (shown only when mode is 'manual') */}
      {mode === 'manual' && (
        <div className="mt-4 p-3 bg-gray-50 rounded-lg border border-gray-200 space-y-4">
          <h4 className="text-sm font-medium text-gray-700">
            {t('processing.preprocessing.manualConfig')}
          </h4>

          {/* Contrast Enhancement */}
          <div className="space-y-2">
            <label className="block text-xs font-medium text-gray-600">
              {t('processing.preprocessing.contrast.label')}
            </label>
            <select
              value={config.contrast}
              onChange={(e) => handleConfigChange('contrast', e.target.value as PreprocessingContrast)}
              disabled={disabled}
              className={cn(
                'w-full px-3 py-2 text-sm border rounded-md',
                'focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500',
                disabled && 'opacity-50 cursor-not-allowed'
              )}
            >
              {contrastOptions.map((opt) => (
                <option key={opt} value={opt}>
                  {t(`processing.preprocessing.contrast.${opt}`)}
                </option>
              ))}
            </select>

            {/* Contrast Strength Slider */}
            {config.contrast !== 'none' && (
              <div className="pt-1">
                <div className="flex justify-between text-xs text-gray-500 mb-1">
                  <span>{t('processing.preprocessing.strength.label')}</span>
                  <span className="font-medium text-gray-700">
                    {config.contrast_strength.toFixed(1)} ({getStrengthLabel(config.contrast_strength, 'contrast')})
                  </span>
                </div>
                <input
                  type="range"
                  min="0.5"
                  max="3.0"
                  step="0.1"
                  value={config.contrast_strength}
                  onChange={(e) => handleConfigChange('contrast_strength', parseFloat(e.target.value))}
                  disabled={disabled}
                  className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer accent-blue-600"
                />
                <div className="flex justify-between text-xs text-gray-400 mt-0.5">
                  <span>0.5</span>
                  <span>3.0</span>
                </div>
              </div>
            )}
          </div>

          {/* Sharpen Section */}
          <div className="space-y-2">
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                type="checkbox"
                checked={config.sharpen}
                onChange={(e) => handleConfigChange('sharpen', e.target.checked)}
                disabled={disabled}
                className="w-4 h-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
              />
              <span className="text-sm text-gray-700">
                {t('processing.preprocessing.sharpen')}
              </span>
            </label>

            {/* Sharpen Strength Slider */}
            {config.sharpen && (
              <div className="pl-6 pt-1">
                <div className="flex justify-between text-xs text-gray-500 mb-1">
                  <span>{t('processing.preprocessing.strength.label')}</span>
                  <span className="font-medium text-gray-700">
                    {config.sharpen_strength.toFixed(1)} ({getStrengthLabel(config.sharpen_strength, 'sharpen')})
                  </span>
                </div>
                <input
                  type="range"
                  min="0.5"
                  max="2.0"
                  step="0.1"
                  value={config.sharpen_strength}
                  onChange={(e) => handleConfigChange('sharpen_strength', parseFloat(e.target.value))}
                  disabled={disabled}
                  className="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer accent-blue-600"
                />
                <div className="flex justify-between text-xs text-gray-400 mt-0.5">
                  <span>0.5</span>
                  <span>2.0</span>
                </div>
              </div>
            )}
          </div>

          {/* Scan Artifact Removal Toggle */}
          <div className="space-y-2">
            <label className="flex items-center gap-2 cursor-pointer">
              <input
                type="checkbox"
                checked={config.remove_scan_artifacts}
                onChange={(e) => handleConfigChange('remove_scan_artifacts', e.target.checked)}
                disabled={disabled}
                className="w-4 h-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
              />
              <span className="text-sm text-gray-700">
                {t('processing.preprocessing.removeScanArtifacts')}
              </span>
            </label>
            <p className="text-xs text-gray-500 pl-6">
              {t('processing.preprocessing.removeScanArtifactsDesc')}
            </p>
          </div>

          {/* Binarize Toggle - Hidden by default, shown only in advanced mode */}
          <details className="pt-2">
            <summary className="text-xs text-gray-500 cursor-pointer hover:text-gray-700">
              {t('processing.preprocessing.advanced')}
            </summary>
            <div className="mt-2 pl-2 border-l-2 border-gray-200">
              <label className="flex items-center gap-2 cursor-pointer">
                <input
                  type="checkbox"
                  checked={config.binarize}
                  onChange={(e) => handleConfigChange('binarize', e.target.checked)}
                  disabled={disabled}
                  className="w-4 h-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                />
                <span className="text-sm text-gray-700">
                  {t('processing.preprocessing.binarize')}
                </span>
                <span className="text-xs text-orange-600">
                  ({t('processing.preprocessing.binarizeWarning')})
                </span>
              </label>
            </div>
          </details>
        </div>
      )}

      {/* Info Note */}
      <div className="mt-4 p-3 bg-blue-50 border border-blue-200 rounded-md">
        <p className="text-sm text-blue-800">
          {t('processing.preprocessing.note')}
        </p>
      </div>
    </div>
  )
}
