/**
 * PresetColorField - Color field with system global values linking & opacity
 * 
 * Allows preset color fields to be linked to system-wide global values.
 * When linked, the field uses the system's global value.
 * When unlinked, the field has its own custom value.
 * 
 * Layout matches ColorsSection for consistency.
 */

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

interface PresetColorFieldProps {
    label: string;
    description?: string;
    value: string;
    colorKey: 'primary' | 'secondary' | 'background' | 'text' | 'accent' | 'textMuted' | 'textLight' | 'backgroundDark' | 'surface' | 'border' | 'success' | 'warning' | 'error';
    systemGlobalValues: PresetGlobalValues | null;
    onChange: (value: string) => void;
    linkedRef?: string | null;
    onLinkChange?: (ref?: string | null) => void;
    defaultValue?: string;
}

const colorLabels: Record<string, string> = {
    'primary': t('Primary Color'),
    'secondary': t('Secondary Color'),
    'accent': t('Accent Color'),
    'text': t('Text Color'),
    'textMuted': t('Muted Text'),
    'textLight': t('Light Text'),
    'background': t('Background Color'),
    'backgroundDark': t('Dark Background'),
    'surface': t('Surface Color'),
    'border': t('Border Color'),
    'success': t('Success'),
    'warning': t('Warning'),
    'error': t('Error'),
};

export const PresetColorField: React.FC<PresetColorFieldProps> = ({
    label,
    description,
    value,
    colorKey,
    systemGlobalValues,
    onChange,
    linkedRef,
    onLinkChange,
    defaultValue = '#3BC2D0',
}) => {
    const [isDropdownOpen, setIsDropdownOpen] = useState(false);
    const dropdownRef = useRef<HTMLDivElement>(null);
    
    const systemValue = systemGlobalValues?.colors?.[colorKey] ?? defaultValue;
    const isLinked = Boolean(linkedRef) || (value?.toLowerCase() === systemValue?.toLowerCase());
    
    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);
    }, []);
    
    const systemColors = systemGlobalValues?.colors
        ? Object.entries(systemGlobalValues.colors)
              .filter(([key, val]) => key !== 'custom' && key !== 'customColors' && typeof val === 'string')
              .map(([key, val]) => ({
                  key,
                  ref: `colors.${key}`,
                  label: colorLabels[key] || key,
                  value: val as string,
              }))
        : [];
    
    return (
        <div className="bg-white border border-gray-200 rounded-lg p-3 hover:border-gray-300 hover:shadow-sm transition-all">
            {/* Header: Label + Link Toggle */}
            <div className="flex items-center justify-between mb-1">
                <label className="block text-sm font-semibold text-gray-800">
                    {label}
                </label>
                
                <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'), colorLabels[colorKey]) : 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="M3.055 11H5a2 2 0 012 2v1a2 2 0 002 2 2 2 0 012 2v2.945M8 3.935V5.5A2.5 2.5 0 0010.5 8h.5a2 2 0 012 2 2 2 0 104 0 2 2 0 012-2h1.064M15 20.488V18a2 2 0 012-2h3.064M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                                </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 end-0 mt-1 w-64 bg-white rounded-lg shadow-lg border border-gray-200 z-50 max-h-80 overflow-y-auto">
                            <div 
                                className={`px-3 py-2 hover:bg-gray-50 cursor-pointer border-b border-gray-100 ${!isLinked ? 'bg-primary/5' : ''}`}
                                onClick={() => {
                                    if (linkedRef) onLinkChange?.(null);
                                    setIsDropdownOpen(false);
                                }}
                            >
                                <div className="flex items-center gap-2">
                                    <svg className="w-4 h-4 text-gray-400" 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>
                                    <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 preset')}</div>
                                    </div>
                                </div>
                            </div>
                            
                            <div className="px-3 py-1.5 bg-gray-50 text-xs font-semibold text-gray-500 sticky top-0">
                                {t('System Global Values')}
                            </div>
                            {systemColors.map((color) => (
                                <div
                                    key={color.key}
                                    className={`
                                        px-3 py-2 hover:bg-gray-50 cursor-pointer flex items-center justify-between
                                        ${(linkedRef && linkedRef === color.ref) || (!linkedRef && colorKey === color.key && isLinked) ? 'bg-primary/5' : ''}
                                    `}
                                    onClick={() => {
                                        onLinkChange?.(color.ref);
                                        onChange(color.value);
                                        setIsDropdownOpen(false);
                                    }}
                                >
                                    <div className="flex items-center gap-2">
                                        <div 
                                            className="w-4 h-4 rounded border border-gray-200 flex-shrink-0"
                                            style={{ backgroundColor: color.value }}
                                        />
                                        <span className="text-sm text-gray-700">{color.label}</span>
                                        {colorKey === color.key && (
                                            <span className="text-xs text-primary font-medium">({t('default')})</span>
                                        )}
                                    </div>
                                    <code className="text-xs text-gray-400 font-mono">
                                        {color.value}
                                    </code>
                                </div>
                            ))}
                        </div>
                    )}
                </div>
            </div>
            
            {/* Description */}
            {description && (
                <p className="text-xs text-gray-400 mb-1">{description}</p>
            )}
            
            {/* Link ref badge */}
            {isLinked && (
                <code className="text-[10px] bg-gray-100 px-1.5 py-0.5 rounded font-mono text-gray-500 mb-2 inline-block">
                    {linkedRef || `colors.${colorKey}`}
                </code>
            )}
            
            {/* Color Picker with opacity */}
            <div className="relative">
                {isLinked && (
                    <div className="absolute -top-1 -end-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>
                )}
                <ColorPicker
                    value={value || defaultValue}
                    onChange={(newValue) => {
                        if (linkedRef) onLinkChange?.(null);
                        onChange(newValue);
                    }}
                    showOpacity
                />
            </div>
        </div>
    );
};

export default PresetColorField;
