/**
 * WhatsApp Widget Section
 * 
 * Settings for WhatsApp button displayed in chat.
 * 
 * @since 1.5.0
 */

import React from 'react';
import { MessageCircle, Type, MousePointer } from 'lucide-react';
import { WidgetSectionBase, WidgetSectionTab } from './WidgetSectionBase';
import { LinkedFieldEditor } from '../LinkedFieldEditor';
import { TypographyControl, TypographySettings } from '../TypographyControl';
import { WhatsAppPreview } from '../PreviewElements';
import { ButtonStyleEditor, ButtonStyleValue } from '../../common/ButtonStyleEditor';
import { deepMerge } from '../../../utils/appearanceMerge';
import { 
    WhatsAppWidgetSettings, 
    PresetGlobalValues, 
    DEFAULT_WIDGET_SETTINGS,
    FieldValue,
    ElementTypography,
    ButtonStyleSettings,
    createDefaultButtonStyle,
    createGlobalRef,
} from '../../../types/appearance';
import { t } from '@/lib/i18n';
import { useLanguage } from '@/contexts/LanguageContext';

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

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

    const patchSettings = (partial: Partial<WhatsAppWidgetSettings>) => {
        onChange({
            ...currentSettings,
            ...partial,
        });
    };

    const handleFieldChange = <K extends keyof WhatsAppWidgetSettings>(
        sectionKey: K,
        fieldKey: keyof WhatsAppWidgetSettings[K],
        value: FieldValue | string
    ) => {
        patchSettings({
            [sectionKey]: {
                ...(currentSettings as any)[sectionKey],
                [fieldKey]: value,
            },
        } as any);
    };

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


    const handleIconColorChange = (colorValue: FieldValue) => {
        const nextIcon = { ...(currentSettings.icon as any), color: colorValue };
        const nextButtonStyle = currentSettings.button?.buttonStyle
            ? ({
                ...(currentSettings.button.buttonStyle as any),
                icon: {
                    ...((currentSettings.button.buttonStyle as any).icon || {}),
                    color: colorValue,
                },
            } as ButtonStyleSettings)
            : currentSettings.button?.buttonStyle;

        patchSettings({
            icon: nextIcon,
            button: {
                ...currentSettings.button,
                buttonStyle: nextButtonStyle,
            },
        } as any);
    };

    // Handler for button style changes (full ButtonStyleSettings)
    const handleButtonStyleChange = (buttonStyle: ButtonStyleValue) => {
        onChange({
            ...currentSettings,
            button: {
                ...currentSettings.button,
                buttonStyle: buttonStyle as ButtonStyleSettings,
            },
        });
    };

    const tabs: WidgetSectionTab[] = [
        {
            id: 'button',
            label: t('Button'),
            icon: <MousePointer size={14} />,
            content: (
                <div className="space-y-6">
                    <div>
                        <h4 className="text-sm font-medium text-gray-700 mb-3">{t('Button Styling')}</h4>
                        <ButtonStyleEditor
                            value={(currentSettings.button.buttonStyle as ButtonStyleValue) || createDefaultButtonStyle('primary')}
                            onChange={handleButtonStyleChange}
                            globalValues={globalValues}
                            label=""
                            disabled={disabled}
                            showIcon={true}
                            showTypography={true}
                        />
                    </div>
                </div>
            ),
        },
        {
            id: 'icon',
            label: t('Icon'),
            icon: <MessageCircle size={14} />,
            content: (
                <div className="space-y-6">
                    <div>
                        <h4 className="text-sm font-medium text-gray-700 mb-3">{t('Icon Styling')}</h4>
                        <div className="space-y-3">
                            <LinkedFieldEditor
                                label={t('Size')}
                                value={currentSettings.icon.size ?? createGlobalRef('sizes.iconLarge')}
                                globalValues={globalValues}
                                onChange={(v) => onChange({
                                    ...currentSettings,
                                    icon: {
                                        ...currentSettings.icon,
                                        size: v,
                                    },
                                })}
                                fieldType="size"
                                allowGlobalLink={true}
                                disabled={disabled}
                                placeholder="28px"
                            />
                            <LinkedFieldEditor
                                label={t('Color')}
                                value={currentSettings.icon.color}
                                globalValues={globalValues}
                                onChange={(v) => handleIconColorChange(v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                        </div>
                    </div>
                </div>
            ),
        },
        {
            id: 'text',
            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 Styling')}</h4>
                        <div className="space-y-3">
                            <LinkedFieldEditor
                                label={t('Color')}
                                value={currentSettings.text.color}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('text', 'color', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                        </div>
                        <div className="mt-3">
                            <TypographyControl
                                label={t('Button Text Styling')}
                                value={currentSettings.text.typography as TypographySettings || {}}
                                globalValues={globalValues}
                                onChange={(typography) => handleTypographyChange('text', typography)}
                                disabled={disabled}
                            />
                        </div>
                    </div>
                </div>
            ),
        },
    ];

    return (
        <WidgetSectionBase
            title={`💬 ${t('WhatsApp')}`}
            description={t('WhatsApp chat button styling')}
            icon={<MessageCircle size={24} />}
            tabs={tabs}
            disableSettingsPointerEvents={disableSettingsPointerEvents}
            onLockedHoverActionClick={onLockedHoverActionClick}
            preview={
                <WhatsAppPreview 
                    globalValues={globalValues} 
                    widgetSettings={currentSettings}
                    isRTL={isRTL}
                    language={currentLanguage}
                />
            }
            defaultCollapsed={true}
        />
    );
};

export default WhatsAppSection;
