/**
 * ButtonIconEditor Component
 * Controls for button icon settings: position, size, color, spacing
 * Follows Elementor-style UI pattern
 * 
 * Updated to use FieldValue for colors to support global value linking
 */

import { useState, useRef, useEffect } from 'react'
import { t } from '@/lib/i18n'
import { ChevronDown, MoveLeft, MoveRight, Image } from 'lucide-react'
import { NumberWithUnitInput, CSSUnit } from './NumberWithUnitInput'
import { LucideIconPicker } from './LucideIconPicker'
import {
    FieldValue,
    PresetGlobalValues,
    createCustomValue,
    type HeaderAvatarIconName,
} from '../../types/appearance'
import LinkedFieldEditor from '../appearance/LinkedFieldEditor'

export type IconPosition = 'before' | 'after' | 'only'

export interface ButtonIconValue {
    /** Optional icon selection (Template: IconTemplate). */
    icon?: HeaderAvatarIconName
    position: IconPosition
    size: string
    color: FieldValue
    spacing: string
    hoverColor?: FieldValue
}

interface ButtonIconEditorProps {
    value: ButtonIconValue
    onChange: (value: ButtonIconValue) => void
    globalValues: PresetGlobalValues
    label?: string
    disabled?: boolean
    showHoverColor?: boolean
    allowedUnits?: CSSUnit[]
    /** When true, show the icon picker (content selection). */
    showIconPicker?: boolean
    /** When true, hide the position selector (for icon-only buttons with no text). */
    hidePosition?: boolean
}

const DEFAULT_VALUE: ButtonIconValue = {
    icon: 'send',
    position: 'before',
    size: '16px',
    color: createCustomValue('#FFFFFF'),
    spacing: '8px',
    hoverColor: createCustomValue('#FFFFFF'),
}

const POSITION_OPTIONS: { value: IconPosition; labelKey: string; icon: React.ReactNode }[] = [
    { value: 'before', labelKey: 'Before Text', icon: <MoveLeft size={14} /> },
    { value: 'after', labelKey: 'After Text', icon: <MoveRight size={14} /> },
    { value: 'only', labelKey: 'Icon Only', icon: <Image size={14} /> },
]

export function ButtonIconEditor({
    value = DEFAULT_VALUE,
    onChange,
    globalValues,
    label = t('Icon Settings'),
    disabled = false,
    showHoverColor = true,
    allowedUnits = ['px', 'em', 'rem'],
    showIconPicker = false,
    hidePosition = false,
}: ButtonIconEditorProps) {
    const [isPositionOpen, setIsPositionOpen] = useState(false)
    const positionRef = useRef<HTMLDivElement>(null)

    // Close dropdown when clicking outside
    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (positionRef.current && !positionRef.current.contains(event.target as Node)) {
                setIsPositionOpen(false)
            }
        }
        document.addEventListener('mousedown', handleClickOutside)
        return () => document.removeEventListener('mousedown', handleClickOutside)
    }, [])

    // Ensure value has FieldValue structure for colors (handle legacy string values)
    const normalizedValue: ButtonIconValue = {
        ...value,
        icon: (value as any)?.icon || DEFAULT_VALUE.icon,
        color: typeof value.color === 'string' 
            ? createCustomValue(value.color) 
            : (value.color || createCustomValue('#FFFFFF')),
        hoverColor: typeof value.hoverColor === 'string'
            ? createCustomValue(value.hoverColor)
            : (value.hoverColor || value.color || createCustomValue('#FFFFFF')),
    }

    const handleIconChange = (icon: HeaderAvatarIconName) => {
        onChange({
            ...normalizedValue,
            icon,
        })
    }

    const handlePositionChange = (position: IconPosition) => {
        onChange({
            ...normalizedValue,
            position,
        })
    }

    const handleSizeChange = (size: string) => {
        onChange({
            ...normalizedValue,
            size,
        })
    }

    const handleSpacingChange = (spacing: string) => {
        onChange({
            ...normalizedValue,
            spacing,
        })
    }

    const handleColorChange = (color: FieldValue) => {
        onChange({
            ...normalizedValue,
            color,
        })
    }

    const handleHoverColorChange = (hoverColor: FieldValue) => {
        onChange({
            ...normalizedValue,
            hoverColor,
        })
    }

    const currentPositionOpt = POSITION_OPTIONS.find((p) => p.value === normalizedValue.position) || POSITION_OPTIONS[0]

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

            {/* Icon Picker (optional) */}
            {showIconPicker && (
                <div className="space-y-1.5">
                    <span className="text-xs text-gray-500">{t('Icon')}</span>
                    <LucideIconPicker
                        value={(normalizedValue.icon || DEFAULT_VALUE.icon) as HeaderAvatarIconName}
                        onChange={handleIconChange}
                        disabled={disabled}
                    />
                </div>
            )}

            {/* Icon Position Selector - hidden for icon-only buttons with no text */}
            {!hidePosition && (
                <div className="space-y-1.5">
                    <span className="text-xs text-gray-500">{t('Position')}</span>
                    <div className="relative" ref={positionRef}>
                        <button
                            type="button"
                            onClick={() => !disabled && setIsPositionOpen(!isPositionOpen)}
                            disabled={disabled}
                            className="
                                w-full px-3 py-2 text-sm
                                border border-gray-300 rounded-md
                                bg-white hover:bg-gray-50
                                flex items-center justify-between gap-2
                                disabled:bg-gray-100 disabled:cursor-not-allowed
                                transition-colors
                            "
                        >
                            <span className="flex items-center gap-2">
                                {currentPositionOpt.icon}
                                <span>{t(currentPositionOpt.labelKey)}</span>
                            </span>
                            <ChevronDown className="w-4 h-4 text-gray-500" />
                        </button>

                        {isPositionOpen && (
                            <div className="
                                absolute top-full left-0 right-0 mt-1 z-50
                                bg-white border border-gray-200 rounded-md shadow-lg
                                py-1
                            ">
                                {POSITION_OPTIONS.map((option) => (
                                    <button
                                        key={option.value}
                                        type="button"
                                        onClick={() => {
                                            handlePositionChange(option.value)
                                            setIsPositionOpen(false)
                                        }}
                                        className={`
                                            w-full px-3 py-2 text-sm text-right
                                            hover:bg-gray-100 transition-colors
                                            flex items-center gap-2
                                            ${option.value === normalizedValue.position
                                                ? 'bg-primary-50 text-primary-700 font-medium'
                                                : 'text-gray-700'
                                            }
                                        `}
                                    >
                                        {option.icon}
                                        <span>{(option as any).label || t((option as any).labelKey)}</span>
                                    </button>
                                ))}
                            </div>
                        )}
                    </div>
                </div>
            )}

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

            {/* Icon Spacing (only if not icon-only) */}
            {normalizedValue.position !== 'only' && (
                <div className="space-y-1.5">
                    <span className="text-xs text-gray-500">{t('Spacing')}</span>
                    <NumberWithUnitInput
                        value={normalizedValue.spacing}
                        onChange={handleSpacingChange}
                        disabled={disabled}
                        allowedUnits={allowedUnits}
                    />
                </div>
            )}

            {/* Icon Color - Now uses LinkedFieldEditor for global value linking */}
            <LinkedFieldEditor
                label={t('Icon Color')}
                value={normalizedValue.color}
                globalValues={globalValues}
                onChange={handleColorChange}
                fieldType="color"
                disabled={disabled}
            />

            {/* Hover Color (optional) - Now uses LinkedFieldEditor for global value linking */}
            {showHoverColor && (
                <LinkedFieldEditor
                    label={t('Icon Color (Hover)')}
                    value={normalizedValue.hoverColor || normalizedValue.color}
                    globalValues={globalValues}
                    onChange={handleHoverColorChange}
                    fieldType="color"
                    disabled={disabled}
                />
            )}
        </div>
    )
}

export default ButtonIconEditor
