/**
 * Linked Field Editor Component
 * 
 * Core component for the Link/Unlink system.
 * - Color fields: link to global color values via a popup picker (unchanged).
 * - Non-color fields: simple toggle between inheriting from the default preset
 *   or using a custom value.
 */

import React, { useState, useRef, useEffect, useCallback } from 'react';
import { createPortal } from 'react-dom';
import { t, sprintf } from '@/lib/i18n';
import { 
    FieldValue, 
    PresetGlobalValues, 
    isGlobalRef, 
    isCustomValue,
    isDefaultRef,
    createGlobalRef,
    createCustomValue,
    createDefaultRef,
    resolveFieldValue 
} from '../../../types/appearance';
import { ColorPicker } from '../../common/ColorPicker';

export type FieldType = 'color' | 'size' | 'text' | 'select';

interface LinkedFieldEditorProps {
    label: string;
    value: FieldValue;
    globalValues: PresetGlobalValues;
    onChange: (value: FieldValue) => void;
    fieldType: FieldType;
    allowGlobalLink?: boolean;
    selectOptions?: { value: string; label: string }[];
    placeholder?: string;
    disabled?: boolean;
    description?: string;
    /** True when editing the default preset — no toggle shown, fields are always concrete */
    isDefaultPreset?: boolean;
    /** The resolved value from the default preset for this field path (for display) */
    defaultPresetValue?: string;
}

function getGlobalRefLabel(ref: string): string {
    const labels: Record<string, string> = {
        'colors.primary': t('Primary Color'),
        'colors.secondary': t('Secondary Color'),
        'colors.accent': t('Accent Color'),
        'colors.text': t('Text Color'),
        'colors.textLight': t('Light Text'),
        'colors.textMuted': t('Muted Text'),
        'colors.background': t('Background'),
        'colors.backgroundDark': t('Dark Background'),
        'colors.surface': t('Surface'),
        'colors.border': t('Borders'),
        'colors.success': t('Success'),
        'colors.successLight': t('Light Success'),
        'colors.warning': t('Warning'),
        'colors.error': t('Error'),
        'colors.transparent': t('Transparent'),
        'colors.overlayLight': t('Light Overlay'),
        'colors.borderSoft': t('Soft Border'),
        'colors.primaryHover': t('Primary Hover Color'),
        'colors.whatsappHover': t('WhatsApp Hover'),
        'typography.fontFamily': t('Font Family'),
        'typography.heading.fontSize': t('Heading Font Size'),
        'typography.heading.fontWeight': t('Heading Font Weight'),
        'typography.heading.lineHeight': t('Heading Line Height'),
        'typography.body.fontSize': t('Body Font Size'),
        'typography.body.fontWeight': t('Body Font Weight'),
        'typography.body.lineHeight': t('Body Line Height'),
        'typography.small.fontSize': t('Small Font Size'),
        'typography.small.fontWeight': t('Small Font Weight'),
        'typography.button.fontSize': t('Button Font Size'),
        'typography.button.fontWeight': t('Button Font Weight'),
    };
    if (ref in labels) return labels[ref];
    if (ref.startsWith('colors.custom.')) return ref;
    return ref;
}

/**
 * Get available color refs for the global color picker popup.
 * Only used for color fields — non-color fields use the default-preset toggle.
 */
function getAvailableColorRefs(
    globalValues: PresetGlobalValues
): { category: string; refs: { path: string; label: string; value: string }[] }[] {
    const categories: { category: string; refs: { path: string; label: string; value: string }[] }[] = [];
    
    const colorRefs = Object.entries(globalValues.colors || {})
        .filter(([key, val]) => key !== 'custom' && key !== 'customColors' && typeof val === 'string')
        .map(([key, value]) => ({
            path: `colors.${key}`,
            label: getGlobalRefLabel(`colors.${key}`),
            value: value as string,
        }));
    
    const customColors = globalValues.colors?.custom ?? [];
    customColors.forEach((color) => {
        colorRefs.push({
            path: `colors.custom.${color.id}.value`,
            label: color.name,
            value: color.value,
        });
    });
    
    if (colorRefs.length > 0) {
        categories.push({ category: t('Colors'), refs: colorRefs });
    }
    
    return categories;
}

const LinkIcon = () => (
    <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" />
    </svg>
);

const UnlinkIcon = () => (
    <svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 21a4 4 0 01-4-4V5a2 2 0 012-2h4a2 2 0 012 2v12a4 4 0 01-4 4zm0 0h12a2 2 0 002-2v-4a2 2 0 00-2-2h-2.343M11 7.343l1.657-1.657a2 2 0 012.828 0l2.829 2.829a2 2 0 010 2.828l-8.486 8.485M7 17h.01" />
    </svg>
);

export const LinkedFieldEditor: React.FC<LinkedFieldEditorProps> = ({
    label,
    value,
    globalValues,
    onChange,
    fieldType,
    allowGlobalLink,
    selectOptions,
    placeholder,
    disabled = false,
    description,
    isDefaultPreset = false,
    defaultPresetValue,
}) => {
    const [isDropdownOpen, setIsDropdownOpen] = useState(false);
    const dropdownRef = useRef<HTMLDivElement>(null);
    const triggerRef = useRef<HTMLButtonElement>(null);
    const portalRef = useRef<HTMLDivElement>(null);
    const [popoverPosition, setPopoverPosition] = useState({ top: 0, left: 0 });

    const isColorField = fieldType === 'color';

    // For color fields, keep the old allowGlobalLink logic
    const allowColorLink = isColorField && (
        typeof allowGlobalLink === 'boolean' ? allowGlobalLink : true
    );

    // For non-color fields on non-default presets, show the default-preset toggle
    const showDefaultToggle = !isColorField && !isDefaultPreset && (
        typeof allowGlobalLink === 'boolean' ? allowGlobalLink : false
    );

    const resolvedValue = resolveFieldValue(value, globalValues);
    const isLinkedToGlobal = allowColorLink && isGlobalRef(value);
    const isLinkedToDefault = isDefaultRef(value);
    
    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            const target = event.target as Node;
            if (
                dropdownRef.current &&
                !dropdownRef.current.contains(target) &&
                triggerRef.current &&
                !triggerRef.current.contains(target) &&
                portalRef.current &&
                !portalRef.current.contains(target)
            ) {
                setIsDropdownOpen(false);
            }
        };
        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, []);

    const portalContainer =
        (document.querySelector('.boostbot-admin') as HTMLElement | null) ||
        (document.getElementById('boostbot-admin-root') as HTMLElement | null) ||
        document.body;

    const updatePopoverPosition = useCallback(() => {
        if (!triggerRef.current) return;
        const rect = triggerRef.current.getBoundingClientRect();
        const popoverWidth = 320;
        const popoverHeight = 320;
        const viewportWidth = window.innerWidth;
        const viewportHeight = window.innerHeight;

        let top = rect.bottom + 8;
        if (top + popoverHeight > viewportHeight - 16) {
            top = rect.top - popoverHeight - 8;
        }
        const maxTop = Math.max(16, viewportHeight - popoverHeight - 16);
        top = Math.min(Math.max(16, top), maxTop);

        let left = rect.right - popoverWidth;
        const maxLeft = Math.max(16, viewportWidth - popoverWidth - 16);
        left = Math.min(Math.max(16, left), maxLeft);

        setPopoverPosition({ top, left });
    }, []);

    useEffect(() => {
        if (!isDropdownOpen) return;
        updatePopoverPosition();
        window.addEventListener('scroll', updatePopoverPosition, true);
        window.addEventListener('resize', updatePopoverPosition);
        return () => {
            window.removeEventListener('scroll', updatePopoverPosition, true);
            window.removeEventListener('resize', updatePopoverPosition);
        };
    }, [isDropdownOpen, updatePopoverPosition]);

    useEffect(() => {
        if (!isDropdownOpen) return;
        const handleKeyDown = (e: KeyboardEvent) => {
            if (e.key === 'Escape') setIsDropdownOpen(false);
        };
        document.addEventListener('keydown', handleKeyDown);
        return () => document.removeEventListener('keydown', handleKeyDown);
    }, [isDropdownOpen]);
    
    const handleUnlink = () => {
        onChange(createCustomValue(resolvedValue));
        setIsDropdownOpen(false);
    };
    
    const handleLink = (ref: string) => {
        onChange(createGlobalRef(ref));
        setIsDropdownOpen(false);
    };
    
    const handleCustomValueChange = (newValue: string) => {
        onChange(createCustomValue(newValue));
    };

    const handleToggleDefault = () => {
        if (isLinkedToDefault) {
            // Switch from default → custom, pre-fill with default preset's value
            onChange(createCustomValue(defaultPresetValue || resolvedValue || ''));
        } else {
            onChange(createDefaultRef());
        }
    };

    const availableRefs = isColorField ? getAvailableColorRefs(globalValues) : [];

    const displayValue = isLinkedToDefault ? (defaultPresetValue || '') : resolvedValue;
    
    return (
        <div className="linked-field-editor">
            <div className="flex items-center justify-between mb-1">
                <label className="text-sm font-medium text-gray-700">
                    {label}
                </label>
                
                {/* Color fields: keep the global color popup */}
                {allowColorLink && (
                    <div className="relative" ref={dropdownRef}>
                        <button
                            ref={triggerRef}
                            type="button"
                            onClick={() => setIsDropdownOpen(!isDropdownOpen)}
                            disabled={disabled}
                            className={`
                                flex items-center gap-1 px-2 py-1 text-xs rounded-md transition-colors
                                ${isLinkedToGlobal 
                                    ? 'bg-primary/10 text-primary hover:bg-primary/20' 
                                    : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                                }
                                ${disabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}
                            `}
                            title={isLinkedToGlobal ? sprintf(t('Linked to: %s'), getGlobalRefLabel((value as any).ref)) : t('Custom value')}
                        >
                            {isLinkedToGlobal ? (
                                <>
                                    <LinkIcon />
                                    <span className="hidden sm:inline">{t('Linked')}</span>
                                </>
                            ) : (
                                <>
                                    <UnlinkIcon />
                                    <span className="hidden sm:inline">{t('Custom')}</span>
                                </>
                            )}
                            <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                            </svg>
                        </button>

                        {isDropdownOpen && createPortal(
                            <div
                                ref={portalRef}
                                className="w-80 bg-white rounded-lg shadow-lg border border-gray-200 max-h-80 overflow-y-auto"
                                style={{
                                    position: 'fixed',
                                    top: popoverPosition.top,
                                    left: popoverPosition.left,
                                    zIndex: 999999,
                                }}
                                dir="rtl"
                            >
                                <div
                                    className="px-3 py-2 hover:bg-gray-50 cursor-pointer border-b border-gray-100"
                                    onClick={handleUnlink}
                                >
                                    <div className="flex items-center gap-2">
                                        <UnlinkIcon />
                                        <div>
                                            <div className="text-sm font-medium text-gray-900">{t('Custom Value')}</div>
                                            <div className="text-xs text-gray-500">{t('Enter a unique value for this field')}</div>
                                        </div>
                                    </div>
                                </div>

                                {availableRefs.map((category) => (
                                    <div key={category.category}>
                                        <div className="px-3 py-1.5 bg-gray-50 text-xs font-semibold text-gray-500 sticky top-0">
                                            🌐 {category.category}
                                        </div>
                                        {category.refs.map((ref) => (
                                            <div
                                                key={ref.path}
                                                className={`
                                                    px-3 py-2 hover:bg-gray-50 cursor-pointer flex items-center justify-between
                                                    ${isLinkedToGlobal && (value as any).ref === ref.path ? 'bg-primary/5' : ''}
                                                `}
                                                onClick={() => handleLink(ref.path)}
                                            >
                                                <div className="flex items-center gap-2">
                                                    <div
                                                        className="w-4 h-4 rounded border border-gray-200"
                                                        style={{ backgroundColor: ref.value }}
                                                    />
                                                    <span className="text-sm text-gray-700">{ref.label}</span>
                                                </div>
                                                <code className="text-xs text-gray-400 font-mono">
                                                    {ref.value}
                                                </code>
                                            </div>
                                        ))}
                                    </div>
                                ))}
                            </div>,
                            portalContainer
                        )}
                    </div>
                )}

                {/* Non-color fields: simple default/custom toggle */}
                {showDefaultToggle && (
                    <button
                        type="button"
                        onClick={handleToggleDefault}
                        disabled={disabled}
                        className={`
                            flex items-center gap-1 px-2 py-1 text-xs rounded-md transition-colors
                            ${isLinkedToDefault
                                ? 'bg-primary/10 text-primary hover:bg-primary/20'
                                : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                            }
                            ${disabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer'}
                        `}
                        title={isLinkedToDefault ? t('Linked to default') : t('Custom value')}
                    >
                        {isLinkedToDefault ? (
                            <>
                                <LinkIcon />
                                <span className="hidden sm:inline">{t('Default')}</span>
                            </>
                        ) : (
                            <>
                                <UnlinkIcon />
                                <span className="hidden sm:inline">{t('Custom')}</span>
                            </>
                        )}
                    </button>
                )}
            </div>
            
            {description && (
                <p className="text-xs text-gray-400 mb-2">{description}</p>
            )}
            
            {/* Value Editor */}
            <div className="relative">
                {/* Linked-to-global overlay (colors) */}
                {isLinkedToGlobal && fieldType !== 'color' && (
                    <div className="absolute inset-0 bg-primary/5 rounded-lg border-2 border-dashed border-primary/30 flex items-center justify-center z-10">
                        <div className="text-center px-4">
                            <div className="text-xs font-medium text-primary">
                                {sprintf(t('Linked to: %s'), getGlobalRefLabel((value as any).ref))}
                            </div>
                            <div className="text-xs text-gray-500 mt-0.5">
                                {sprintf(t('Current value: %s'), resolvedValue)}
                            </div>
                        </div>
                    </div>
                )}

                {/* Linked-to-default overlay (non-color fields) */}
                {isLinkedToDefault && fieldType !== 'color' && (
                    <div className="absolute inset-0 bg-primary/5 rounded-lg border-2 border-dashed border-primary/30 flex items-center justify-center z-10">
                        <div className="text-center px-4">
                            <div className="text-xs font-medium text-primary">
                                {t('Linked to default')}
                            </div>
                            {defaultPresetValue && (
                                <div className="text-xs text-gray-500 mt-0.5">
                                    {sprintf(t('Current value: %s'), defaultPresetValue)}
                                </div>
                            )}
                        </div>
                    </div>
                )}
                
                <div className={(isLinkedToGlobal || isLinkedToDefault) && fieldType !== 'color' ? 'opacity-0 pointer-events-none' : ''}>
                    {fieldType === 'color' && (
                        <ColorPicker
                            value={displayValue || '#000000'}
                            onChange={handleCustomValueChange}
                            disabled={disabled}
                        />
                    )}
                    
                    {fieldType === 'size' && (
                        <input
                            type="text"
                            value={isCustomValue(value) ? value.value : ''}
                            onChange={(e) => handleCustomValueChange(e.target.value)}
                            placeholder={placeholder || '16px'}
                            disabled={disabled || isLinkedToGlobal || isLinkedToDefault}
                            className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary focus:border-primary disabled:bg-gray-100 disabled:opacity-50"
                        />
                    )}
                    
                    {fieldType === 'text' && (
                        <input
                            type="text"
                            value={isCustomValue(value) ? value.value : ''}
                            onChange={(e) => handleCustomValueChange(e.target.value)}
                            placeholder={placeholder}
                            disabled={disabled || isLinkedToGlobal || isLinkedToDefault}
                            className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary focus:border-primary disabled:bg-gray-100 disabled:opacity-50"
                        />
                    )}
                    
                    {fieldType === 'select' && selectOptions && (
                        <select
                            value={isCustomValue(value) ? value.value : ''}
                            onChange={(e) => handleCustomValueChange(e.target.value)}
                            disabled={disabled || isLinkedToGlobal || isLinkedToDefault}
                            className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary focus:border-primary disabled:bg-gray-100 disabled:opacity-50"
                        >
                            {selectOptions.map((opt) => (
                                <option key={opt.value} value={opt.value}>
                                    {opt.label}
                                </option>
                            ))}
                        </select>
                    )}
                </div>
            </div>
        </div>
    );
};

export default LinkedFieldEditor;
