/**
 * OverlayColorFieldEditor
 * Canonical editor for overlay colors:
 * - Base color is a FieldValue (can link to global colors)
 * - Opacity is stored separately as 0-100
 *
 * Used for things like:
 * - YouTube thumbnail overlay background
 * - Gallery lightbox overlay background
 *
 * Backward compatibility:
 * - If a legacy `rgba(...)` string is provided, we parse it into { color, opacity }.
 */
import { t } from '@/lib/i18n'
import { FieldValue, PresetGlobalValues, createCustomValue, resolveFieldValue } from '../../types/appearance'
import LinkedFieldEditor from '../appearance/LinkedFieldEditor'

export interface OverlayColorFieldEditorProps {
    label?: string
    value: FieldValue | string | undefined
    opacity?: number
    globalValues: PresetGlobalValues
    onChange: (value: FieldValue) => void
    onOpacityChange: (opacity: number) => void
    disabled?: boolean
    /** Used when legacy/empty value is provided */
    fallbackColorRef?: string
    fallbackOpacity?: number
    description?: string
}

function clamp(n: number, min: number, max: number) {
    return Math.min(Math.max(n, min), max)
}

function parseLegacyRgba(input: string): { color: string; opacity: number } | null {
    const safe = input.trim()
    const m = safe.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)/i)
    if (!m) return null
    const r = clamp(Number.parseInt(m[1] || '0', 10), 0, 255)
    const g = clamp(Number.parseInt(m[2] || '0', 10), 0, 255)
    const b = clamp(Number.parseInt(m[3] || '0', 10), 0, 255)
    const a = m[4] !== undefined ? Number.parseFloat(m[4]) : 1
    const opacity = clamp(Math.round((Number.isFinite(a) ? a : 1) * 100), 0, 100)
    const hex = `#${[r, g, b].map((x) => x.toString(16).padStart(2, '0')).join('')}`
    return { color: hex, opacity }
}

export function OverlayColorFieldEditor({
    label = t('Overlay Background'),
    value,
    opacity,
    globalValues,
    onChange,
    onOpacityChange,
    disabled = false,
    fallbackColorRef = 'colors.text',
    fallbackOpacity = 30,
    description,
}: OverlayColorFieldEditorProps) {
    // Normalize legacy string (rgba) into a custom FieldValue + opacity
    let normalizedValue: FieldValue
    let normalizedOpacity: number

    if (typeof value === 'string') {
        const parsed = parseLegacyRgba(value)
        if (parsed) {
            normalizedValue = createCustomValue(parsed.color)
            normalizedOpacity = opacity ?? parsed.opacity
        } else {
            // Treat any other legacy string as a custom color (best-effort)
            normalizedValue = createCustomValue(value.trim() || '#000000')
            normalizedOpacity = opacity ?? fallbackOpacity
        }
    } else if (value && typeof value === 'object') {
        normalizedValue = value
        normalizedOpacity = opacity ?? fallbackOpacity
    } else {
        normalizedValue = createCustomValue(resolveFieldValue({ type: 'global', ref: fallbackColorRef }, globalValues) || '#000000')
        normalizedOpacity = opacity ?? fallbackOpacity
    }

    const safeOpacity = clamp(Math.round(normalizedOpacity), 0, 100)

    return (
        <div className="space-y-1.5" dir="rtl">
            {label && <label className="block text-xs text-gray-500">{label}</label>}
            {description && <p className="text-xs text-gray-400">{description}</p>}
            <div className="space-y-2">
                <LinkedFieldEditor
                    label={t('Overlay Color')}
                    value={normalizedValue}
                    globalValues={globalValues}
                    onChange={onChange}
                    fieldType="color"
                    disabled={disabled}
                />

                <div className="space-y-1">
                    <div className="flex items-center justify-between gap-3">
                        <span className="text-xs text-gray-500">{t('Opacity')}</span>
                        <span className="text-xs text-gray-400">{safeOpacity}%</span>
                    </div>
                    <div className="flex items-center gap-3" dir="ltr">
                        <input
                            type="range"
                            min={0}
                            max={100}
                            step={1}
                            value={safeOpacity}
                            onChange={(e) => onOpacityChange(clamp(Number.parseInt(e.target.value || '0', 10), 0, 100))}
                            disabled={disabled}
                            className="flex-1"
                        />
                        <input
                            type="number"
                            min={0}
                            max={100}
                            value={safeOpacity}
                            onChange={(e) => onOpacityChange(clamp(Number.parseInt(e.target.value || '0', 10), 0, 100))}
                            disabled={disabled}
                            className="w-20 px-2 py-1 border border-gray-300 rounded text-xs text-center"
                        />
                        <span className="text-xs text-gray-500">%</span>
                    </div>
                </div>
            </div>
        </div>
    )
}

export default OverlayColorFieldEditor


