/**
 * Bot Appearance Override Component
 * 
 * Allows overriding specific appearance settings at the bot level.
 * Shows which settings are inherited from the preset vs custom.
 * 
 * @since 1.5.0
 */

import React, { useState, useMemo } from 'react';
import { 
    Link2, 
    Unlink, 
    Palette, 
    Type, 
    ChevronDown,
    ChevronUp,
    RotateCcw,
    AlertCircle,
    Check
} from 'lucide-react';
import { t, sprintf } from '@/lib/i18n';
import { 
    PresetGlobalValues, 
    ElementSettings,
    DEFAULT_GLOBAL_VALUES
} from '../../../types/appearance';

// ============================================================
// Types
// ============================================================

export interface AppearanceOverrides {
    colors?: {
        primary?: string;
        secondary?: string;
        [key: string]: string | undefined;
    };
    typography?: {
        fontFamily?: string;
        [key: string]: string | undefined;
    };
    elements?: Partial<ElementSettings>;
}

export interface BotAppearanceOverrideProps {
    presetId?: number | null;
    presetName?: string;
    presetGlobalValues?: PresetGlobalValues | null;
    presetElementSettings?: ElementSettings | null;
    overrides: AppearanceOverrides | null;
    onChange: (overrides: AppearanceOverrides | null) => void;
    onNavigateToPreset?: () => void;
}

interface OverrideFieldProps {
    label: string;
    path: string;
    presetValue: string;
    overrideValue?: string;
    type: 'color' | 'text' | 'size';
    onOverride: (path: string, value: string | null) => void;
}

// ============================================================
// Override Field Component
// ============================================================

const OverrideField: React.FC<OverrideFieldProps> = ({
    label,
    path,
    presetValue,
    overrideValue,
    type,
    onOverride,
}) => {
    const [isHovered, setIsHovered] = useState(false);
    const isOverridden = overrideValue !== undefined;
    const displayValue = isOverridden ? overrideValue : presetValue;

    const handleToggleOverride = () => {
        if (isOverridden) {
            // Remove override (reset to preset)
            onOverride(path, null);
        } else {
            // Create override with current preset value
            onOverride(path, presetValue);
        }
    };

    const handleValueChange = (newValue: string) => {
        onOverride(path, newValue);
    };

    return (
        <div 
            className="override-field"
            onMouseEnter={() => setIsHovered(true)}
            onMouseLeave={() => setIsHovered(false)}
            style={{
                display: 'flex',
                alignItems: 'center',
                gap: '12px',
                padding: '10px 12px',
                background: isOverridden ? '#FEF3C7' : isHovered ? '#F9FAFB' : 'transparent',
                borderRadius: '8px',
                transition: 'all 0.2s ease',
                border: isOverridden ? '1px solid #F59E0B' : '1px solid transparent',
            }}
        >
            {/* Link/Unlink Button */}
            <button
                onClick={handleToggleOverride}
                title={isOverridden ? t('Remove override (revert to Preset)') : t('Override this value')}
                style={{
                    width: '32px',
                    height: '32px',
                    borderRadius: '6px',
                    border: 'none',
                    background: isOverridden ? '#F59E0B' : '#E5E7EB',
                    color: isOverridden ? '#FFFFFF' : '#6B7280',
                    cursor: 'pointer',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    transition: 'all 0.2s ease',
                    flexShrink: 0,
                }}
            >
                {isOverridden ? <Unlink size={16} /> : <Link2 size={16} />}
            </button>

            {/* Label */}
            <div style={{ flex: 1, minWidth: 0 }}>
                <div 
                    style={{ 
                        fontSize: '13px', 
                        fontWeight: 500, 
                        color: '#374151',
                        marginBottom: '2px',
                    }}
                >
                    {label}
                </div>
                {!isOverridden && (
                    <div style={{ fontSize: '11px', color: '#9CA3AF' }}>
                        {t('From Preset')}
                    </div>
                )}
            </div>

            {/* Value Editor */}
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                {type === 'color' && (
                    <>
                        <input
                            type="color"
                            value={displayValue}
                            onChange={(e) => handleValueChange(e.target.value)}
                            disabled={!isOverridden}
                            style={{
                                width: '32px',
                                height: '32px',
                                borderRadius: '6px',
                                border: '2px solid #E5E7EB',
                                cursor: isOverridden ? 'pointer' : 'not-allowed',
                                opacity: isOverridden ? 1 : 0.7,
                            }}
                        />
                        <input
                            type="text"
                            value={displayValue}
                            onChange={(e) => handleValueChange(e.target.value)}
                            disabled={!isOverridden}
                            style={{
                                width: '80px',
                                padding: '6px 8px',
                                borderRadius: '6px',
                                border: '1px solid #E5E7EB',
                                fontSize: '12px',
                                fontFamily: 'monospace',
                                textTransform: 'uppercase',
                                background: isOverridden ? '#FFFFFF' : '#F9FAFB',
                            }}
                        />
                    </>
                )}

                {type === 'text' && (
                    <input
                        type="text"
                        value={displayValue}
                        onChange={(e) => handleValueChange(e.target.value)}
                        disabled={!isOverridden}
                        style={{
                            width: '150px',
                            padding: '6px 10px',
                            borderRadius: '6px',
                            border: '1px solid #E5E7EB',
                            fontSize: '13px',
                            background: isOverridden ? '#FFFFFF' : '#F9FAFB',
                        }}
                    />
                )}

                {type === 'size' && (
                    <input
                        type="text"
                        value={displayValue}
                        onChange={(e) => handleValueChange(e.target.value)}
                        disabled={!isOverridden}
                        style={{
                            width: '80px',
                            padding: '6px 10px',
                            borderRadius: '6px',
                            border: '1px solid #E5E7EB',
                            fontSize: '13px',
                            fontFamily: 'monospace',
                            background: isOverridden ? '#FFFFFF' : '#F9FAFB',
                        }}
                    />
                )}
            </div>

            {/* Override Indicator */}
            {isOverridden && (
                <div 
                    style={{
                        fontSize: '10px',
                        color: '#F59E0B',
                        fontWeight: 600,
                        textTransform: 'uppercase',
                    }}
                >
                    {t('Overridden')}
                </div>
            )}
        </div>
    );
};

// ============================================================
// Override Section Component
// ============================================================

interface OverrideSectionProps {
    title: string;
    icon: React.ReactNode;
    children: React.ReactNode;
    overrideCount: number;
    defaultOpen?: boolean;
}

const OverrideSection: React.FC<OverrideSectionProps> = ({
    title,
    icon,
    children,
    overrideCount,
    defaultOpen = false,
}) => {
    const [isOpen, setIsOpen] = useState(defaultOpen);

    return (
        <div 
            style={{
                border: '1px solid #E5E7EB',
                borderRadius: '12px',
                overflow: 'hidden',
                marginBottom: '12px',
            }}
        >
            {/* Header */}
            <button
                onClick={() => setIsOpen(!isOpen)}
                style={{
                    width: '100%',
                    display: 'flex',
                    alignItems: 'center',
                    gap: '12px',
                    padding: '14px 16px',
                    background: overrideCount > 0 ? '#FFFBEB' : '#F9FAFB',
                    border: 'none',
                    cursor: 'pointer',
                    textAlign: 'right',
                }}
            >
                <div style={{ color: '#6B7280' }}>{icon}</div>
                <span style={{ flex: 1, fontWeight: 500, color: '#374151' }}>
                    {title}
                </span>
                {overrideCount > 0 && (
                    <span 
                        style={{
                            background: '#F59E0B',
                            color: '#FFFFFF',
                            fontSize: '11px',
                            fontWeight: 600,
                            padding: '2px 8px',
                            borderRadius: '10px',
                        }}
                    >
                        {sprintf(t('%s overrides'), overrideCount)}
                    </span>
                )}
                {isOpen ? <ChevronUp size={18} /> : <ChevronDown size={18} />}
            </button>

            {/* Content */}
            {isOpen && (
                <div style={{ padding: '12px' }}>
                    {children}
                </div>
            )}
        </div>
    );
};

// ============================================================
// Main Component
// ============================================================

export const BotAppearanceOverride: React.FC<BotAppearanceOverrideProps> = ({
    presetId,
    presetName,
    presetGlobalValues,
    // presetElementSettings - reserved for future use
    overrides,
    onChange,
    onNavigateToPreset,
}) => {
    const globalValues = presetGlobalValues ?? DEFAULT_GLOBAL_VALUES;
    
    // Count overrides per section
    const overrideCounts = useMemo(() => {
        if (!overrides) return { colors: 0, typography: 0, elements: 0 };
        return {
            colors: Object.keys(overrides.colors || {}).length,
            typography: Object.keys(overrides.typography || {}).length,
            elements: Object.keys(overrides.elements || {}).length,
        };
    }, [overrides]);

    const totalOverrides = overrideCounts.colors + overrideCounts.typography + overrideCounts.elements;

    // Handle field override
    const handleOverride = (section: string, path: string, value: string | null) => {
        const newOverrides = { ...overrides } as AppearanceOverrides;
        
        if (value === null) {
            // Remove override
            if (section === 'colors' && newOverrides.colors) {
                delete newOverrides.colors[path];
                if (Object.keys(newOverrides.colors).length === 0) {
                    delete newOverrides.colors;
                }
            } else if (section === 'typography' && newOverrides.typography) {
                delete newOverrides.typography[path];
                if (Object.keys(newOverrides.typography).length === 0) {
                    delete newOverrides.typography;
                }
            }
        } else {
            // Add/update override
            if (section === 'colors') {
                newOverrides.colors = { ...(newOverrides.colors || {}), [path]: value };
            } else if (section === 'typography') {
                newOverrides.typography = { ...(newOverrides.typography || {}), [path]: value };
            }
        }

        // If no overrides left, set to null
        if (Object.keys(newOverrides).length === 0) {
            onChange(null);
        } else {
            onChange(newOverrides);
        }
    };

    // Reset all overrides
    const handleResetAll = () => {
        if (confirm(t('Remove all overrides and revert to Preset settings?'))) {
            onChange(null);
        }
    };

    if (!presetId) {
        return (
            <div 
                style={{
                    padding: '24px',
                    background: '#FEF3C7',
                    borderRadius: '12px',
                    textAlign: 'center',
                }}
            >
                <AlertCircle size={32} color="#F59E0B" style={{ marginBottom: '12px' }} />
                <p style={{ margin: 0, color: '#92400E' }}>
                    {t('Select an appearance Preset to enable overrides')}
                </p>
            </div>
        );
    }

    return (
        <div className="bot-appearance-override">
            {/* Header */}
            <div 
                style={{
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    marginBottom: '20px',
                    padding: '16px',
                    background: '#F0FDF4',
                    borderRadius: '12px',
                    border: '1px solid #86EFAC',
                }}
            >
                <div>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                        <Check size={18} color="#22C55E" />
                        <span style={{ fontWeight: 500, color: '#166534' }}>
                            {sprintf(t('Active Preset: %s'), presetName || `#${presetId}`)}
                        </span>
                    </div>
                    <p style={{ margin: '4px 0 0', fontSize: '13px', color: '#16A34A' }}>
                        {totalOverrides === 0 
                            ? t('All settings are inherited from the Preset') 
                            : sprintf(t('%s settings overridden at bot level'), totalOverrides)}
                    </p>
                </div>

                <div style={{ display: 'flex', gap: '8px' }}>
                    {totalOverrides > 0 && (
                        <button
                            onClick={handleResetAll}
                            style={{
                                display: 'flex',
                                alignItems: 'center',
                                gap: '6px',
                                padding: '8px 12px',
                                background: '#FFFFFF',
                                border: '1px solid #E5E7EB',
                                borderRadius: '8px',
                                fontSize: '13px',
                                color: '#6B7280',
                                cursor: 'pointer',
                            }}
                        >
                            <RotateCcw size={14} />
                            {t('Reset All')}
                        </button>
                    )}
                    {onNavigateToPreset && (
                        <button
                            onClick={onNavigateToPreset}
                            style={{
                                display: 'flex',
                                alignItems: 'center',
                                gap: '6px',
                                padding: '8px 12px',
                                background: '#22C55E',
                                border: 'none',
                                borderRadius: '8px',
                                fontSize: '13px',
                                color: '#FFFFFF',
                                cursor: 'pointer',
                            }}
                        >
                            {t('Edit Preset')}
                        </button>
                    )}
                </div>
            </div>

            {/* Colors Section */}
            <OverrideSection
                title={t('Colors')}
                icon={<Palette size={18} />}
                overrideCount={overrideCounts.colors}
                defaultOpen={overrideCounts.colors > 0}
            >
                <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
                    <OverrideField
                        label={t('Primary Color')}
                        path="primary"
                        presetValue={globalValues.colors.primary}
                        overrideValue={overrides?.colors?.primary}
                        type="color"
                        onOverride={(path, value) => handleOverride('colors', path, value)}
                    />
                    <OverrideField
                        label={t('Secondary Color')}
                        path="secondary"
                        presetValue={globalValues.colors.secondary}
                        overrideValue={overrides?.colors?.secondary}
                        type="color"
                        onOverride={(path, value) => handleOverride('colors', path, value)}
                    />
                    <OverrideField
                        label={t('Background Color')}
                        path="background"
                        presetValue={globalValues.colors.background}
                        overrideValue={overrides?.colors?.background}
                        type="color"
                        onOverride={(path, value) => handleOverride('colors', path, value)}
                    />
                    <OverrideField
                        label={t('Text Color')}
                        path="text"
                        presetValue={globalValues.colors.text}
                        overrideValue={overrides?.colors?.text}
                        type="color"
                        onOverride={(path, value) => handleOverride('colors', path, value)}
                    />
                </div>
            </OverrideSection>

            {/* Typography Section */}
            <OverrideSection
                title={t('Typography')}
                icon={<Type size={18} />}
                overrideCount={overrideCounts.typography}
            >
                <div style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}>
                    <OverrideField
                        label={t('Font Family')}
                        path="fontFamily"
                        presetValue={globalValues.typography.fontFamily}
                        overrideValue={overrides?.typography?.fontFamily}
                        type="text"
                        onOverride={(path, value) => handleOverride('typography', path, value)}
                    />
                </div>
            </OverrideSection>

            {/* Info */}
            <div 
                style={{
                    padding: '12px 16px',
                    background: '#F3F4F6',
                    borderRadius: '8px',
                    fontSize: '12px',
                    color: '#6B7280',
                    marginTop: '16px',
                }}
            >
                <strong>💡 {t('Tip:')}</strong> {t('Click the 🔗 button to override a value. Bot-level overrides allow you to customize specific styling without changing the Preset itself.')}
            </div>
        </div>
    );
};

export default BotAppearanceOverride;

