import { t } from '@/lib/i18n'
import { NumberWithUnitInput, type CSSUnit } from './NumberWithUnitInput'
import { LucideIconPicker } from './LucideIconPicker'
import { createCustomValue, type FieldValue, type HeaderAvatarIconName, type PresetGlobalValues } from '../../types/appearance'
import LinkedFieldEditor from '../appearance/LinkedFieldEditor'

export interface IconStyleValue {
  icon: HeaderAvatarIconName
  size: string
  color: FieldValue
  hoverColor?: FieldValue
}

export interface IconStyleEditorProps {
  label?: string
  value: IconStyleValue
  onChange: (value: IconStyleValue) => void
  globalValues: PresetGlobalValues
  disabled?: boolean
  showHoverColor?: boolean
  allowedUnits?: CSSUnit[]
}

const DEFAULT_VALUE: IconStyleValue = {
  icon: 'send',
  size: '16px',
  color: createCustomValue('#FFFFFF'),
  hoverColor: createCustomValue('#FFFFFF'),
}

/**
 * Template: IconTemplate (standalone)
 * - Icon selection (Lucide)
 * - Size (with units)
 * - Color (+ optional hover color) with global linking
 */
export function IconStyleEditor({
  label = t('Icon'),
  value,
  onChange,
  globalValues,
  disabled = false,
  showHoverColor = true,
  allowedUnits = ['px', 'em', 'rem'],
}: IconStyleEditorProps) {
  const v: IconStyleValue = {
    ...DEFAULT_VALUE,
    ...value,
    color: typeof value?.color === 'string' ? createCustomValue(value.color) : (value?.color || DEFAULT_VALUE.color),
    hoverColor:
      typeof value?.hoverColor === 'string'
        ? createCustomValue(value.hoverColor)
        : (value?.hoverColor || value?.color || DEFAULT_VALUE.hoverColor),
  }

  return (
    <div className="space-y-3" dir="rtl">
      {label ? <div className="text-sm font-medium text-gray-700">{label}</div> : null}

      <div className="space-y-1.5">
        <span className="text-xs text-gray-500">{t('Choose Icon')}</span>
        <LucideIconPicker value={v.icon} onChange={(icon) => onChange({ ...v, icon })} disabled={disabled} />
      </div>

      <div className="space-y-1.5">
        <span className="text-xs text-gray-500">{t('Size')}</span>
        <NumberWithUnitInput value={v.size} onChange={(size) => onChange({ ...v, size })} disabled={disabled} allowedUnits={allowedUnits} />
      </div>

      <LinkedFieldEditor
        label={t('Color')}
        value={v.color}
        globalValues={globalValues}
        onChange={(color) => onChange({ ...v, color })}
        fieldType="color"
        disabled={disabled}
      />

      {showHoverColor ? (
        <LinkedFieldEditor
          label={t('Hover Color')}
          value={v.hoverColor || v.color}
          globalValues={globalValues}
          onChange={(hoverColor) => onChange({ ...v, hoverColor })}
          fieldType="color"
          disabled={disabled}
        />
      ) : null}
    </div>
  )
}

export default IconStyleEditor

