/**
 * PresetTypographyField - Typography field with system global values linking
 * 
 * Allows preset typography fields to be linked to system-wide global values.
 * When linked, the field will use the system's global value.
 * When unlinked, the field has its own custom value.
 */

import React, { useState, useRef, useEffect, useMemo } from 'react';
import { t, sprintf } from '@/lib/i18n';
import type { PresetGlobalValues, TypographySettings } from '@/types/appearance';

function getBaseFontFamilies() {
    return [
        { value: '"Open Sans", sans-serif', label: 'Open Sans' },
        { value: '"Heebo", sans-serif', label: `Heebo (${t('Hebrew')})` },
        { value: '"Assistant", sans-serif', label: `Assistant (${t('Hebrew')})` },
        { value: '"Rubik", sans-serif', label: `Rubik (${t('Hebrew')})` },
        { value: '"David Libre", serif', label: `David Libre (${t('Hebrew')})` },
        { value: '"Frank Ruhl Libre", serif', label: `Frank Ruhl Libre (${t('Hebrew')})` },
        { value: '"Secular One", sans-serif', label: `Secular One (${t('Hebrew')})` },
        { value: '"Varela Round", sans-serif', label: 'Varela Round' },
        { value: '"Arial", sans-serif', label: 'Arial' },
        { value: '"Roboto", sans-serif', label: 'Roboto' },
        { value: '"Inter", sans-serif', label: 'Inter' },
        { value: '"Montserrat", sans-serif', label: 'Montserrat' },
    ];
}

interface PresetTypographyFieldProps {
    label: string;
    /** Current typography settings for this preset */
    value: TypographySettings | null;
    /** System global values (from API) */
    systemGlobalValues: PresetGlobalValues | null;
    /** Called when value changes */
    onChange: (value: TypographySettings) => void;
    /** Default typography settings */
    defaultValue?: TypographySettings;
}

export const PresetTypographyField: React.FC<PresetTypographyFieldProps> = ({
    label,
    value,
    systemGlobalValues,
    onChange,
    defaultValue,
}) => {
    const [isDropdownOpen, setIsDropdownOpen] = useState(false);
    const dropdownRef = useRef<HTMLDivElement>(null);
    
    // Get default typography - create minimal entry helper
    const createMinimalEntry = (fontSize: string, fontWeight: string, lineHeight: string) => ({
        fontFamily: '"Open Sans", sans-serif',
        fontSize,
        fontWeight,
        textTransform: 'none' as const,
        fontStyle: 'normal' as const,
        textDecoration: 'none' as const,
        lineHeight,
        letterSpacing: '0px',
        wordSpacing: '0px',
    });
    
    const defaults: TypographySettings = defaultValue ?? systemGlobalValues?.typography ?? {
        fontFamily: '"Open Sans", sans-serif',
        // Headings (weight 600)
        headingLarge: createMinimalEntry('22px', '600', '1.2'),
        headingMedium: createMinimalEntry('18px', '600', '1.3'),
        headingSmall: createMinimalEntry('16px', '600', '1.3'),
        // Body (weight 400)
        bodyLarge: createMinimalEntry('16px', '400', '1.5'),
        body: createMinimalEntry('14px', '400', '1.5'),
        bodySmall: createMinimalEntry('12px', '400', '1.4'),
        // Buttons (weight 600)
        buttonLarge: createMinimalEntry('16px', '600', '1'),
        button: createMinimalEntry('14px', '600', '1'),
        buttonSmall: createMinimalEntry('12px', '600', '1'),
        // Labels (weight 500)
        labelLarge: createMinimalEntry('14px', '500', '1.4'),
        label: createMinimalEntry('12px', '500', '1.4'),
        labelSmall: createMinimalEntry('10px', '500', '1.4'),
        // Confirmation + micro (weight 600)
        confirmationText: createMinimalEntry('11px', '600', '1.1'),
        micro: createMinimalEntry('9px', '600', '1.1'),
        // Inputs (weight 400)
        inputLarge: createMinimalEntry('16px', '400', '1.5'),
        input: createMinimalEntry('14px', '400', '1.5'),
        inputSmall: createMinimalEntry('12px', '400', '1.4'),
        // Legacy
        heading: createMinimalEntry('18px', '600', '1.3'),
        small: createMinimalEntry('12px', '400', '1.4'),
    };
    
    // Current value or defaults
    const currentValue = value ?? defaults;
    
    // Get the system global font family
    const systemFontFamily = systemGlobalValues?.typography?.fontFamily ?? defaults.fontFamily;
    
    // Check if current font family matches system global value (is linked)
    const isLinked = currentValue.fontFamily === systemFontFamily;
    
    // Get the actual font to display (resolve 'inherit' to the system font)
    const resolvedFontFamily = currentValue.fontFamily === 'inherit' ? systemFontFamily : currentValue.fontFamily;
    
    // Close dropdown when clicking outside
    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
                setIsDropdownOpen(false);
            }
        };
        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, []);
    
    // Get display name for font family
    const getFontDisplayName = (fontFamily: string): string => {
        if (!fontFamily || fontFamily === 'inherit') {
            return t('Default');
        }
        const font = getBaseFontFamilies().find(f => f.value === fontFamily);
        if (font) {
            return font.label;
        }
        // Clean up the font name for display (remove quotes, get first part before comma)
        return fontFamily.replace(/["']/g, '').split(',')[0].trim();
    };
    
    // Build font options dynamically - include system font if not in base list
    const fontOptions = useMemo(() => {
        const options = [...getBaseFontFamilies()];
        
        // Add system global font if it's not in the base list (e.g., custom Elementor font)
        if (systemFontFamily && systemFontFamily !== 'inherit') {
            const isInList = options.some(o => o.value === systemFontFamily);
            if (!isInList) {
                const displayName = getFontDisplayName(systemFontFamily);
                options.unshift({ 
                    value: systemFontFamily, 
                    label: `${displayName} ★ (${t('imported')})` 
                });
            }
        }
        
        // Add current value font if it's not in the list
        if (currentValue.fontFamily && currentValue.fontFamily !== 'inherit' && currentValue.fontFamily !== systemFontFamily) {
            const isInList = options.some(o => o.value === currentValue.fontFamily);
            if (!isInList) {
                const displayName = getFontDisplayName(currentValue.fontFamily);
                options.unshift({ 
                    value: currentValue.fontFamily, 
                    label: `${displayName} ★` 
                });
            }
        }
        
        return options;
    }, [systemFontFamily, currentValue.fontFamily]);
    
    // Helper to update all typography entries with a new font family
    const updateAllFontFamilies = (newFontFamily: string) => {
        const updateEntry = (entry: typeof currentValue.body) => ({
            ...entry,
            fontFamily: newFontFamily,
        });
        
        return {
            ...currentValue,
            fontFamily: newFontFamily,
            // Headings
            headingLarge: updateEntry(currentValue.headingLarge),
            headingMedium: updateEntry(currentValue.headingMedium),
            headingSmall: updateEntry(currentValue.headingSmall),
            // Body
            bodyLarge: updateEntry(currentValue.bodyLarge),
            body: updateEntry(currentValue.body),
            bodySmall: updateEntry(currentValue.bodySmall),
            // Buttons
            buttonLarge: updateEntry(currentValue.buttonLarge),
            button: updateEntry(currentValue.button),
            buttonSmall: updateEntry(currentValue.buttonSmall),
            // Labels
            labelLarge: updateEntry(currentValue.labelLarge),
            label: updateEntry(currentValue.label),
            labelSmall: updateEntry(currentValue.labelSmall),
            // Inputs
            inputLarge: updateEntry(currentValue.inputLarge),
            input: updateEntry(currentValue.input),
            inputSmall: updateEntry(currentValue.inputSmall),
            // Legacy
            heading: updateEntry(currentValue.heading),
            small: updateEntry(currentValue.small),
        };
    };
    
    // Handle font family change
    const handleFontFamilyChange = (fontFamily: string) => {
        // When selecting the global value marker, use the system font
        const actualFontFamily = fontFamily === '__global__' ? systemFontFamily : fontFamily;
        onChange(updateAllFontFamilies(actualFontFamily));
    };
    
    // Link to global value
    const handleLinkToGlobal = () => {
        onChange(updateAllFontFamilies(systemFontFamily));
        setIsDropdownOpen(false);
    };
    
    // Current select value - show __global__ if linked
    const selectValue = isLinked ? '__global__' : currentValue.fontFamily;
    
    // Global font display name
    const globalFontDisplayName = getFontDisplayName(systemFontFamily);
    
    return (
        <div className="preset-typography-field">
            <div className="flex items-center justify-between mb-2">
                <label className="block text-sm font-medium text-gray-700">
                    {label}
                </label>
                
                {/* Link/Unlink Toggle */}
                <div className="relative" ref={dropdownRef}>
                    <button
                        type="button"
                        onClick={() => setIsDropdownOpen(!isDropdownOpen)}
                        className={`
                            flex items-center gap-1 px-2 py-0.5 text-xs rounded-md transition-colors
                            ${isLinked 
                                ? 'bg-primary/10 text-primary hover:bg-primary/20' 
                                : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                            }
                            cursor-pointer
                        `}
                        title={isLinked ? sprintf(t('Linked to global value: %s'), globalFontDisplayName) : t('Custom value')}
                    >
                        {isLinked ? (
                            <>
                                <svg className="w-3 h-3" 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>
                                <span>{t('Global')}</span>
                            </>
                        ) : (
                            <>
                                <svg className="w-3 h-3" 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>
                                <span>{t('Custom')}</span>
                            </>
                        )}
                        <svg className="w-2.5 h-2.5" 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>
                    
                    {/* Dropdown Menu */}
                    {isDropdownOpen && (
                        <div className="absolute left-0 mt-1 w-80 bg-white rounded-lg shadow-lg border border-gray-200 z-50 max-h-80 overflow-y-auto">
                            {/* Link to Global Value Option */}
                            <div 
                                className={`px-3 py-2 hover:bg-gray-50 cursor-pointer border-b border-gray-100 ${isLinked ? 'bg-primary/5' : ''}`}
                                onClick={handleLinkToGlobal}
                            >
                                <div className="flex items-center gap-2">
                                    <svg className="w-4 h-4 text-primary" 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>
                                    <div className="flex-1">
                                        <div className="text-sm font-medium text-gray-900">
                                            🌐 {t('Link to Global Value')}
                                        </div>
                                        <div className="text-xs text-gray-500">
                                            {t('Use font:')} <strong style={{ fontFamily: systemFontFamily }}>{globalFontDisplayName}</strong>
                                        </div>
                                    </div>
                                    {isLinked && (
                                        <svg className="w-4 h-4 text-primary" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                                        </svg>
                                    )}
                                </div>
                            </div>
                            
                            {/* Custom Value Option */}
                            <div className="px-3 py-1.5 bg-gray-50 text-xs font-semibold text-gray-500 sticky top-0">
                                🎨 {t('Choose a Custom Font')}
                            </div>
                            {fontOptions.map((font) => (
                                <div
                                    key={font.value}
                                    className={`
                                        px-3 py-2 hover:bg-gray-50 cursor-pointer flex items-center justify-between
                                        ${!isLinked && currentValue.fontFamily === font.value ? 'bg-primary/5' : ''}
                                    `}
                                    onClick={() => {
                                        handleFontFamilyChange(font.value);
                                        setIsDropdownOpen(false);
                                    }}
                                >
                                    <div className="flex items-center gap-2">
                                        <span 
                                            className="text-base w-8"
                                            style={{ fontFamily: font.value }}
                                        >
                                            {t('Aa')}
                                        </span>
                                        <span className="text-sm text-gray-700" style={{ fontFamily: font.value }}>
                                            {font.label}
                                        </span>
                                    </div>
                                    {!isLinked && currentValue.fontFamily === font.value && (
                                        <svg className="w-4 h-4 text-primary" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                                        </svg>
                                    )}
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            </div>
            
            {/* Font Family Selector */}
            <div className="relative">
                {isLinked && (
                    <div className="absolute -top-1 -right-1 w-4 h-4 bg-primary rounded-full flex items-center justify-center z-10 shadow-sm">
                        <svg className="w-2.5 h-2.5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={3} 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>
                    </div>
                )}
                <select
                    value={selectValue}
                    onChange={(e) => handleFontFamilyChange(e.target.value)}
                    className={`w-full px-3 py-2 border rounded-lg transition-all appearance-none bg-white cursor-pointer ${
                        isLinked 
                            ? 'border-primary/30 bg-primary/5 ring-2 ring-primary/20' 
                            : 'border-gray-300 hover:border-gray-400'
                    }`}
                    style={{ fontFamily: resolvedFontFamily }}
                >
                    {/* Global option always at top */}
                    <option 
                        value="__global__"
                        style={{ fontFamily: systemFontFamily }}
                    >
                        🌐 {sprintf(t('Inherit from System (%s)'), globalFontDisplayName)}
                    </option>
                    
                    {/* Font options */}
                    {fontOptions.map((font) => (
                        <option 
                            key={font.value} 
                            value={font.value}
                            style={{ fontFamily: font.value }}
                        >
                            {font.label}
                        </option>
                    ))}
                </select>
                
                {/* Font Preview - Always use the resolved font family */}
                <div 
                    className="mt-2 p-3 bg-gray-50 rounded-lg text-center"
                    style={{ fontFamily: resolvedFontFamily }}
                >
                    <div className="text-lg font-semibold mb-1">{t('Hello! How can I help?')}</div>
                    <div className="text-sm text-gray-600">{t('Hello! How can I help you today?')}</div>
                </div>
                
                {isLinked && (
                    <div className="text-xs text-primary mt-2 flex items-center gap-1">
                        <svg className="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                        </svg>
                        {t('Linked to global value:')} <strong className="mx-1">{globalFontDisplayName}</strong>
                    </div>
                )}
            </div>
        </div>
    );
};

export default PresetTypographyField;
