/**
 * YouTube Widget Section
 * 
 * Settings for YouTube video embed displayed in chat.
 * 
 * @since 1.5.0
 */

import React from 'react';
import { Play, Palette, Type, Image } from 'lucide-react';
import { WidgetSectionBase, WidgetSectionTab } from './WidgetSectionBase';
import { LinkedFieldEditor } from '../LinkedFieldEditor';
import { TypographyControl, TypographySettings } from '../TypographyControl';
import { YouTubePreview } from '../PreviewElements';
import { 
    YouTubeWidgetSettings, 
    PresetGlobalValues, 
    DEFAULT_WIDGET_SETTINGS,
    FieldValue,
    ElementTypography,
    createCustomValue,
    createDefaultButtonStyle,
} from '../../../types/appearance';
import { BoxShadowFieldEditor } from '../../common/BoxShadowFieldEditor';
import { BorderRadiusFieldEditor } from '../../common/BorderRadiusFieldEditor';
import { OverlayColorFieldEditor } from '../../common/OverlayColorFieldEditor';
import { PaddingFieldEditor } from '../../common/PaddingFieldEditor';
import { BorderWidthEditor } from '../../common/BorderWidthEditor';
import { HoverScaleControl } from '../../common/HoverScaleControl';
import { IconOnlyButtonStyleControl } from '../../common/IconOnlyButtonStyleControl';
import { BorderStyleSelect } from '../../common/BorderStyleSelect';
import { deepMerge } from '../../../utils/appearanceMerge';
import { t } from '@/lib/i18n';
import { useLanguage } from '@/contexts/LanguageContext';

interface YouTubeSectionProps {
    settings: YouTubeWidgetSettings | null;
    globalValues: PresetGlobalValues;
    onChange: (settings: YouTubeWidgetSettings) => void;
    disabled?: boolean;
    /** When true, make settings pane non-clickable (pointer-events: none) */
    disableSettingsPointerEvents?: boolean;
    /** Optional action when locked overlay button is clicked */
    onLockedHoverActionClick?: () => void;
}

export const YouTubeSection: React.FC<YouTubeSectionProps> = ({
    settings,
    globalValues,
    onChange,
    disabled = false,
    disableSettingsPointerEvents = false,
    onLockedHoverActionClick,
}) => {
    const { currentLanguage } = useLanguage();
    const isRTL = currentLanguage === 'he';

    const currentSettings = React.useMemo(
        () => deepMerge(DEFAULT_WIDGET_SETTINGS.youtube, settings),
        [settings]
    );

    const handleFieldChange = <K extends keyof YouTubeWidgetSettings>(
        sectionKey: K,
        fieldKey: keyof YouTubeWidgetSettings[K],
        value: FieldValue | string | number
    ) => {
        onChange({
            ...currentSettings,
            [sectionKey]: {
                ...currentSettings[sectionKey],
                [fieldKey]: value,
            },
        });
    };

    // Handler for typography changes
    const handleTypographyChange = (
        sectionKey: 'title' | 'description',
        typography: TypographySettings
    ) => {
        onChange({
            ...currentSettings,
            [sectionKey]: {
                ...(currentSettings as any)[sectionKey],
                typography: typography as ElementTypography,
            },
        } as any);
    };

    const tabs: WidgetSectionTab[] = [
        {
            id: 'container',
            label: t('Container'),
            icon: <Palette size={14} />,
            content: (
                <div className="space-y-6">
                    <div>
                        <h4 className="text-sm font-medium text-gray-700 mb-3">{t('General Styling')}</h4>
                        <div className="space-y-3">
                            <LinkedFieldEditor
                                label={t('Background Color')}
                                value={currentSettings.container.background}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('container', 'background', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <PaddingFieldEditor
                                label={t('Padding')}
                                value={(currentSettings.container as any).padding}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('container', 'padding' as never, v)}
                                disabled={disabled}
                                fallback="12px"
                            />
                            <BorderRadiusFieldEditor
                                label={t('Border Radius')}
                                value={currentSettings.container.borderRadius}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('container', 'borderRadius', v)}
                                disabled={disabled}
                                defaultGlobalRef="effects.borderRadiusMedium"
                            />
                            <div className="pt-2 border-t border-gray-100">
                                <div className="text-sm font-medium text-gray-700 mb-2">{t('Border')}</div>
                                <div className="space-y-3">
                                    <BorderStyleSelect
                                        label={t('Border Style')}
                                        value={((currentSettings.container as any).borderStyle || 'none') as 'none' | 'solid' | 'dashed' | 'dotted'}
                                        onChange={(v) => handleFieldChange('container', 'borderStyle' as never, v)}
                                        disabled={disabled}
                                    />
                                    <div>
                                        <label className="block text-sm font-medium text-gray-700 mb-1">{t('Border Width')}</label>
                                        <BorderWidthEditor
                                            value={(() => {
                                                const bw = (currentSettings.container as any).borderWidth;
                                                if (bw && typeof bw === 'object') {
                                                    const o = bw as Record<string, unknown>;
                                                    if (typeof o.top === 'string' && typeof o.right === 'string' && typeof o.bottom === 'string' && typeof o.left === 'string') {
                                                        return { top: o.top, right: o.right, bottom: o.bottom, left: o.left };
                                                    }
                                                }
                                                return { top: '0px', right: '0px', bottom: '0px', left: '0px' };
                                            })()}
                                            onChange={(v) => handleFieldChange('container', 'borderWidth' as never, v as unknown as never)}
                                            disabled={disabled}
                                            label=""
                                        />
                                    </div>
                                    <LinkedFieldEditor
                                        label={t('Border Color')}
                                        value={(currentSettings.container as any).borderColor || createCustomValue('transparent')}
                                        globalValues={globalValues}
                                        onChange={(v) => handleFieldChange('container', 'borderColor' as never, v)}
                                        fieldType="color"
                                        disabled={disabled}
                                    />
                                </div>
                            </div>
                            <BoxShadowFieldEditor
                                label={t('Shadow')}
                                value={currentSettings.container.shadow}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('container', 'shadow', v)}
                                disabled={disabled}
                                defaultGlobalRef="effects.shadowSmall"
                            />
                        </div>
                    </div>
                </div>
            ),
        },
        {
            id: 'thumbnail',
            label: t('Thumbnail'),
            icon: <Image size={14} />,
            content: (
                <div className="space-y-6">
                    <div>
                        <h4 className="text-sm font-medium text-gray-700 mb-3">{t('Thumbnail Styling')}</h4>
                        <div className="space-y-6">
                            <div className="space-y-3">
                            <OverlayColorFieldEditor
                                label={t('Overlay Background')}
                                value={currentSettings.thumbnail.overlayBackground}
                                opacity={(currentSettings.thumbnail as any).overlayOpacity}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('thumbnail', 'overlayBackground', v)}
                                onOpacityChange={(pct) => handleFieldChange('thumbnail', 'overlayOpacity' as never, pct)}
                                disabled={disabled}
                                fallbackColorRef="colors.text"
                                fallbackOpacity={30}
                            />
                            </div>

                            <div className="space-y-3 pt-2 border-t border-gray-100">
                                <div className="text-sm font-medium text-gray-700">{t('Hover')}</div>
                                <HoverScaleControl
                                    label={t('Hover Scale (Image)')}
                                    value={(currentSettings.thumbnail as any).hoverScale}
                                    onChange={(v) => handleFieldChange('thumbnail', 'hoverScale' as never, v)}
                                    disabled={disabled}
                                    min={1}
                                    max={1.3}
                                />
                            </div>

                            <div className="space-y-3 pt-2 border-t border-gray-100">
                                <div className="text-sm font-medium text-gray-700">{t('Play Button')}</div>
                                <HoverScaleControl
                                    label={t('Hover Scale')}
                                    value={(currentSettings.thumbnail as any).playButtonHoverScale}
                                    onChange={(v) => handleFieldChange('thumbnail', 'playButtonHoverScale' as never, v)}
                                    disabled={disabled}
                                    min={1}
                                    max={1.5}
                                />

                                <IconOnlyButtonStyleControl
                                    label={t('Button Styling')}
                                    globalValues={globalValues}
                                    disabled={disabled}
                                    value={{
                                        icon: ((currentSettings.thumbnail as any).playButtonIcon || 'play') as any,
                                        style: ((currentSettings.thumbnail as any).playButtonStyle as any) || createDefaultButtonStyle('ghost', true),
                                    }}
                                    onChange={(next) => {
                                        handleFieldChange('thumbnail', 'playButtonIcon' as never, next.icon as unknown as never);
                                        handleFieldChange('thumbnail', 'playButtonStyle' as never, next.style as unknown as never);
                                    }}
                                />
                            </div>

                        </div>
                    </div>
                </div>
            ),
        },
        {
            id: 'title',
            label: t('Text'),
            icon: <Type size={14} />,
            content: (
                <div className="space-y-6">
                    <div>
                        <h4 className="text-sm font-medium text-gray-700 mb-3">{t('Text')}</h4>
                        <div className="space-y-6">
                            <PaddingFieldEditor
                                label={t('Content Padding')}
                                value={(currentSettings.title as any)?.padding}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('title', 'padding' as never, v)}
                                disabled={disabled}
                                fallback="12px"
                            />
                            <div className="space-y-3">
                                <div className="text-sm font-medium text-gray-700">{t('Title')}</div>
                            <LinkedFieldEditor
                                label={t('Color')}
                                value={currentSettings.title.color}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('title', 'color', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <div className="mt-3">
                            <TypographyControl
                                label={t('Title Text Styling')}
                                value={currentSettings.title.typography as TypographySettings || {}}
                                globalValues={globalValues}
                                onChange={(typography) => handleTypographyChange('title', typography)}
                                disabled={disabled}
                            />
                            </div>
                            </div>

                            <div className="space-y-3">
                                <div className="text-sm font-medium text-gray-700">{t('Description')}</div>
                                <LinkedFieldEditor
                                    label={t('Color')}
                                    value={(currentSettings as any).description?.color}
                                    globalValues={globalValues}
                                    onChange={(v) => handleFieldChange('description' as any, 'color' as any, v)}
                                    fieldType="color"
                                    disabled={disabled}
                                />
                                <div className="mt-3">
                                    <TypographyControl
                                        label={t('Description Text Styling')}
                                        value={((currentSettings as any).description?.typography as TypographySettings) || {}}
                                        globalValues={globalValues}
                                        onChange={(typography) => handleTypographyChange('description', typography)}
                                        disabled={disabled}
                                    />
                                </div>
                            </div>

                        </div>
                    </div>
                </div>
            ),
        },
    ];

    return (
        <WidgetSectionBase
            title={`▶️ ${t('YouTube')}`}
            description={t('YouTube video embed styling')}
            icon={<Play size={24} />}
            tabs={tabs}
            disableSettingsPointerEvents={disableSettingsPointerEvents}
            onLockedHoverActionClick={onLockedHoverActionClick}
            preview={
                <YouTubePreview 
                    globalValues={globalValues} 
                    widgetSettings={currentSettings}
                    isRTL={isRTL}
                    language={currentLanguage}
                />
            }
            defaultCollapsed={true}
        />
    );
};

export default YouTubeSection;
