/**
 * Gallery Widget Section
 * 
 * Settings for image gallery displayed in chat.
 * 
 * @since 1.5.0
 */

import React from 'react';
import { Image, Grid, Palette, Type, Maximize } from 'lucide-react';
import { WidgetSectionBase, WidgetSectionTab } from './WidgetSectionBase';
import { LinkedFieldEditor } from '../LinkedFieldEditor';
import { TypographyControl, TypographySettings } from '../TypographyControl';
import { GalleryPreview } from '../PreviewElements';
import {
    GalleryWidgetSettings,
    PresetGlobalValues,
    DEFAULT_WIDGET_SETTINGS,
    FieldValue,
    ElementTypography,
    createCustomValue,
    createGlobalRef,
} from '../../../types/appearance';
import { BoxShadowFieldEditor } from '../../common/BoxShadowFieldEditor';
import { BorderRadiusFieldEditor } from '../../common/BorderRadiusFieldEditor';
import { PaddingFieldEditor } from '../../common/PaddingFieldEditor';
import { BorderWidthEditor } from '../../common/BorderWidthEditor';
import { BorderStyleSelect } from '../../common/BorderStyleSelect';
import { OverlayColorFieldEditor } from '../../common/OverlayColorFieldEditor';
import { HoverScaleControl } from '../../common/HoverScaleControl';
import { deepMerge } from '../../../utils/appearanceMerge';
import { LucideIconPicker } from '../../common/LucideIconPicker';
import { ColumnCountSelect } from '../../common/ColumnCountSelect';
import { SelectField } from '../../common/SelectField';
import type { HeaderAvatarIconName } from '../../../types/appearance';
import { t } from '@/lib/i18n';
import { useLanguage } from '@/contexts/LanguageContext';

interface GallerySectionProps {
    settings: GalleryWidgetSettings | null;
    globalValues: PresetGlobalValues;
    onChange: (settings: GalleryWidgetSettings) => 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 GallerySection: React.FC<GallerySectionProps> = ({
    settings,
    globalValues,
    onChange,
    disabled = false,
    disableSettingsPointerEvents = false,
    onLockedHoverActionClick,
}) => {
    const { currentLanguage } = useLanguage();
    const isRTL = currentLanguage === 'he';

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

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

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

    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}
                            />
                            <BorderRadiusFieldEditor
                                label={t('Border Radius')}
                                value={currentSettings.container.borderRadius}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('container', 'borderRadius', v)}
                                disabled={disabled}
                                defaultGlobalRef="effects.borderRadiusMedium"
                            />
                            <PaddingFieldEditor
                                label={t('Padding')}
                                value={currentSettings.container.padding}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('container', 'padding', v)}
                                disabled={disabled}
                                fallback="8px"
                            />
                            <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 || createGlobalRef('colors.transparent')}
                                        globalValues={globalValues}
                                        onChange={(v) => handleFieldChange('container', 'borderColor' as never, v)}
                                        fieldType="color"
                                        disabled={disabled}
                                    />
                                </div>
                            </div>
                            <BoxShadowFieldEditor
                                label={t('Shadow')}
                                value={(currentSettings.container as any).shadow}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('container', 'shadow' as never, v)}
                                disabled={disabled}
                                defaultGlobalRef="effects.shadowSmall"
                            />
                        </div>
                    </div>
                </div>
            ),
        },
        {
            id: 'grid',
            label: t('Grid'),
            icon: <Grid size={14} />,
            content: (
                <div className="space-y-6">
                    <div>
                        <h4 className="text-sm font-medium text-gray-700 mb-3">{t('Grid Settings')}</h4>
                        <div className="space-y-3">
                            <ColumnCountSelect
                                label={t('Column Count')}
                                value={currentSettings.grid.columns}
                                onChange={(v) => handleFieldChange('grid', 'columns', v)}
                                disabled={disabled}
                            />
                            <LinkedFieldEditor
                                label={t('Gap')}
                                value={currentSettings.grid.gap ?? createCustomValue('8px')}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('grid', 'gap', v)}
                                fieldType="size"
                                allowGlobalLink={true}
                                disabled={disabled}
                                placeholder="8px"
                            />
                        </div>
                    </div>
                </div>
            ),
        },
        {
            id: 'image',
            label: t('Image'),
            icon: <Image size={14} />,
            content: (
                <div className="space-y-6">
                    <div>
                        <h4 className="text-sm font-medium text-gray-700 mb-3">{t('Image Styling')}</h4>
                        <div className="space-y-3">
                            <BorderRadiusFieldEditor
                                label={t('Border Radius')}
                                value={currentSettings.image.borderRadius}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('image', 'borderRadius', v)}
                                disabled={disabled}
                                defaultGlobalRef="effects.borderRadiusMedium"
                            />
                            <LinkedFieldEditor
                                label={t('Image Height')}
                                value={currentSettings.image.height ?? createGlobalRef('sizes.galleryImageHeight')}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('image', 'height', v)}
                                fieldType="size"
                                allowGlobalLink={true}
                                disabled={disabled}
                                placeholder="80px"
                            />
                            <HoverScaleControl
                                label={t('Hover Scale')}
                                value={currentSettings.image.hoverScale}
                                onChange={(v) => handleFieldChange('image', 'hoverScale', v)}
                                disabled={disabled}
                            />
                            <BoxShadowFieldEditor
                                label={t('Shadow')}
                                value={currentSettings.image.shadow}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('image', 'shadow', v)}
                                disabled={disabled}
                                defaultGlobalRef="effects.shadowSmall"
                            />
                        </div>
                    </div>
                </div>
            ),
        },
        {
            id: 'caption',
            label: t('Caption'),
            icon: <Type size={14} />,
            content: (
                <div className="space-y-6">
                    <div>
                        <h4 className="text-sm font-medium text-gray-700 mb-3">{t('Title (Name + Description)')}</h4>
                        <div className="space-y-3">
                            <div>
                                <label className="block text-xs text-gray-500 mb-1">{t('Icon')}</label>
                                <LucideIconPicker
                                    value={(((currentSettings.header as any)?.titleIcon || 'image') as HeaderAvatarIconName)}
                                    onChange={(icon) => onChange({
                                        ...currentSettings,
                                        header: {
                                            ...(currentSettings.header || {}),
                                            titleIcon: icon,
                                        },
                                    })}
                                    disabled={disabled}
                                />
                            </div>

                            <LinkedFieldEditor
                                label={t('Title Color')}
                                value={(currentSettings.header as any)?.titleColor || createGlobalRef('colors.textLight')}
                                globalValues={globalValues}
                                onChange={(v) => onChange({
                                    ...currentSettings,
                                    header: {
                                        ...(currentSettings.header || {}),
                                        titleColor: v,
                                    },
                                })}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <LinkedFieldEditor
                                label={t('Icon Color')}
                                value={(currentSettings.header as any)?.titleIconColor || createGlobalRef('colors.text')}
                                globalValues={globalValues}
                                onChange={(v) => onChange({
                                    ...currentSettings,
                                    header: {
                                        ...(currentSettings.header || {}),
                                        titleIconColor: v,
                                    },
                                })}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <LinkedFieldEditor
                                label={t('Icon Size')}
                                value={(currentSettings.header as any)?.titleIconSize ?? createGlobalRef('sizes.iconLarge')}
                                globalValues={globalValues}
                                onChange={(v) => onChange({
                                    ...currentSettings,
                                    header: {
                                        ...(currentSettings.header || {}),
                                        titleIconSize: v,
                                    },
                                })}
                                fieldType="size"
                                allowGlobalLink={true}
                                disabled={disabled}
                                placeholder="28px"
                            />
                            <LinkedFieldEditor
                                label={t('Gap Between Icon and Text')}
                                value={(currentSettings.header as any)?.titleGap ?? createGlobalRef('spacing.sm')}
                                globalValues={globalValues}
                                onChange={(v) => onChange({
                                    ...currentSettings,
                                    header: {
                                        ...(currentSettings.header || {}),
                                        titleGap: v,
                                    },
                                })}
                                fieldType="size"
                                allowGlobalLink={true}
                                disabled={disabled}
                                placeholder="8px"
                            />

                            <SelectField
                                label={t('Icon Position')}
                                value={String(((currentSettings.header as any)?.titleIconPosition || 'after') as 'before' | 'after')}
                                onChange={(pos) => onChange({
                                    ...currentSettings,
                                    header: {
                                        ...(currentSettings.header || {}),
                                        titleIconPosition: (pos as 'before' | 'after'),
                                    },
                                })}
                                disabled={disabled}
                                description={t('Semantic position (RTL/LTR safe): "Before text" is always before text in reading direction.')}
                                options={[
                                    { value: 'before', label: t('Before Text') },
                                    { value: 'after', label: t('After Text') },
                                ]}
                            />
                        </div>
                        <div className="mt-3 space-y-3">
                            <TypographyControl
                                label={t('Title Typography')}
                                value={((currentSettings.header as any)?.titleTypography as TypographySettings) || {}}
                                globalValues={globalValues}
                                onChange={(typography) => onChange({
                                    ...currentSettings,
                                    header: {
                                        ...(currentSettings.header || {}),
                                        titleTypography: typography as any,
                                    },
                                })}
                                disabled={disabled}
                                context="header"
                            />
                            <LinkedFieldEditor
                                label={t('Description Color')}
                                value={(currentSettings.header as any)?.descriptionColor || createGlobalRef('colors.textLight')}
                                globalValues={globalValues}
                                onChange={(v) => onChange({
                                    ...currentSettings,
                                    header: {
                                        ...(currentSettings.header || {}),
                                        descriptionColor: v,
                                    },
                                })}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <TypographyControl
                                label={t('Description Typography')}
                                value={((currentSettings.header as any)?.descriptionTypography as TypographySettings) || {}}
                                globalValues={globalValues}
                                onChange={(typography) => onChange({
                                    ...currentSettings,
                                    header: {
                                        ...(currentSettings.header || {}),
                                        descriptionTypography: typography as any,
                                    },
                                })}
                                disabled={disabled}
                                context="small"
                            />
                        </div>
                    </div>

                    <div>
                        <h4 className="text-sm font-medium text-gray-700 mb-3">{t('Caption Styling')}</h4>
                        <div className="space-y-3">
                            <LinkedFieldEditor
                                label={t('Background Color')}
                                value={currentSettings.caption.background}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('caption', 'background', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <LinkedFieldEditor
                                label={t('Text Color')}
                                value={currentSettings.caption.color}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('caption', 'color', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <PaddingFieldEditor
                                label={t('Padding')}
                                value={currentSettings.caption.padding}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('caption', 'padding', v)}
                                disabled={disabled}
                                fallback="8px"
                            />
                            <LinkedFieldEditor
                                label={t('Hover Opacity')}
                                value={currentSettings.caption.hoverOpacity ?? createCustomValue('1')}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('caption', 'hoverOpacity', v)}
                                fieldType="text"
                                allowGlobalLink={false}
                                disabled={disabled}
                                placeholder="1"
                            />
                            <LinkedFieldEditor
                                label={t('Hover Vertical Offset')}
                                value={currentSettings.caption.hoverOffset ?? createCustomValue('100%')}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('caption', 'hoverOffset', v)}
                                fieldType="size"
                                allowGlobalLink={false}
                                disabled={disabled}
                                placeholder="100%"
                            />
                        </div>
                        <div className="mt-3">
                            <TypographyControl
                                label={t('Caption Text Styling')}
                                value={currentSettings.caption.typography as TypographySettings || {}}
                                globalValues={globalValues}
                                onChange={(typography) => handleTypographyChange('caption', typography)}
                                disabled={disabled}
                            />
                        </div>
                    </div>
                </div>
            ),
        },
        {
            id: 'lightbox',
            label: t('Lightbox'),
            icon: <Maximize size={14} />,
            content: (
                <div className="space-y-6">
                    <div>
                        <h4 className="text-sm font-medium text-gray-700 mb-3">{t('Enlarged View')}</h4>
                        <div className="space-y-3">
                            <OverlayColorFieldEditor
                                label={t('Overlay Background')}
                                value={currentSettings.lightbox.overlayBackground}
                                opacity={(currentSettings.lightbox as any).overlayOpacity}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('lightbox', 'overlayBackground', v)}
                                onOpacityChange={(pct) => handleFieldChange('lightbox', 'overlayOpacity' as never, pct)}
                                disabled={disabled}
                                fallbackColorRef="colors.backgroundDark"
                                fallbackOpacity={25}
                            />
                        </div>
                    </div>

                    <div className="pt-2 border-t border-gray-100">
                        <div className="text-sm font-medium text-gray-700 mb-2">{t('Buttons (Icon Only)')}</div>
                        <p className="text-xs text-gray-500">
                            {t('Close/navigation buttons are functional parts of the Lightbox and are not stylable via the preset (by product decision).')}
                        </p>
                    </div>

                    <div className="pt-2 border-t border-gray-100">
                        <div className="text-sm font-medium text-gray-700 mb-2">{t('Caption (Lightbox)')}</div>
                        <div className="space-y-3">
                            <LinkedFieldEditor
                                label={t('Title Color')}
                                value={(currentSettings.lightbox as any).captionTitleColor || createCustomValue('#FFFFFF')}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('lightbox', 'captionTitleColor' as never, v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <LinkedFieldEditor
                                label={t('Description Color')}
                                value={(currentSettings.lightbox as any).captionDescriptionColor || createCustomValue('rgba(255,255,255,0.80)')}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('lightbox', 'captionDescriptionColor' as never, v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <TypographyControl
                                label={t('Caption Typography')}
                                value={((currentSettings.lightbox as any).captionTypography as TypographySettings) || {}}
                                globalValues={globalValues}
                                onChange={(typography) => handleFieldChange('lightbox', 'captionTypography' as never, typography as unknown as never)}
                                disabled={disabled}
                            />
                        </div>
                    </div>

                    {/* Link button intentionally removed from product; no style controls */}
                </div>
            ),
        },
    ];

    return (
        <WidgetSectionBase
            title={`🖼️ ${t('Gallery')}`}
            description={t('Image gallery styling')}
            icon={<Image size={24} />}
            tabs={tabs}
            disableSettingsPointerEvents={disableSettingsPointerEvents}
            onLockedHoverActionClick={onLockedHoverActionClick}
            preview={
                <GalleryPreview 
                    globalValues={globalValues} 
                    widgetSettings={currentSettings}
                    isRTL={isRTL}
                    language={currentLanguage}
                />
            }
            defaultCollapsed={true}
        />
    );
};

export default GallerySection;
