/**
 * Contact Card Widget Section
 * 
 * Settings for contact cards displayed in chat.
 * 
 * @since 1.5.0
 */

import React from 'react';
import { UserCircle, Palette, User, Phone, Mail } from 'lucide-react';
import { WidgetSectionBase, WidgetSectionTab } from './WidgetSectionBase';
import { LinkedFieldEditor } from '../LinkedFieldEditor';
import { TypographyControl, TypographySettings } from '../TypographyControl';
import { ContactCardPreview } from '../PreviewElements';
import { ButtonStyleEditor, ButtonStyleValue } from '../../common/ButtonStyleEditor';
import { PaddingFieldEditor } from '../../common/PaddingFieldEditor';
import { BoxShadowFieldEditor } from '../../common/BoxShadowFieldEditor';
import { BorderStyleSelect } from '../../common/BorderStyleSelect';
import { 
    ContactCardWidgetSettings, 
    PresetGlobalValues, 
    DEFAULT_WIDGET_SETTINGS,
    FieldValue,
    ElementTypography,
    ButtonStyleSettings,
    createCustomValue,
    createGlobalRef,
} from '../../../types/appearance';
import { BorderRadiusFieldEditor } from '../../common/BorderRadiusFieldEditor';
import { deepMerge } from '../../../utils/appearanceMerge';
import { t } from '@/lib/i18n';
import { useLanguage } from '@/contexts/LanguageContext';

interface ContactCardSectionProps {
    settings: ContactCardWidgetSettings | null;
    globalValues: PresetGlobalValues;
    onChange: (settings: ContactCardWidgetSettings) => 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 ContactCardSection: React.FC<ContactCardSectionProps> = ({
    settings,
    globalValues,
    onChange,
    disabled = false,
    disableSettingsPointerEvents = false,
    onLockedHoverActionClick,
}) => {
    const { currentLanguage } = useLanguage();
    const isRTL = currentLanguage === 'he';
    const currentSettings = React.useMemo(
        () => deepMerge(DEFAULT_WIDGET_SETTINGS.contactCard, settings),
        [settings]
    );

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

    const handleTypographyChange = (
        sectionKey: 'name' | 'title',
        typography: TypographySettings
    ) => {
        onChange({
            ...currentSettings,
            [sectionKey]: {
                ...currentSettings[sectionKey],
                typography: typography as ElementTypography,
            },
        });
    };

    // Handler for typography changes in nested sections
    const handleTypographyFieldChange = (
        sectionKey: 'fields',
        fieldKey: 'labelTypography' | 'valueTypography',
        typography: TypographySettings
    ) => {
        onChange({
            ...currentSettings,
            [sectionKey]: {
                ...currentSettings[sectionKey],
                [fieldKey]: typography as ElementTypography,
            },
        });
    };

    // Handler for primary button style changes
    const handlePrimaryButtonStyleChange = (buttonStyle: ButtonStyleValue) => {
        onChange({
            ...currentSettings,
            buttons: {
                ...currentSettings.buttons,
                primaryButtonStyle: buttonStyle as ButtonStyleSettings,
            },
        });
    };

    // Handler for secondary button style changes
    const handleSecondaryButtonStyleChange = (buttonStyle: ButtonStyleValue) => {
        onChange({
            ...currentSettings,
            buttons: {
                ...currentSettings.buttons,
                secondaryButtonStyle: buttonStyle as ButtonStyleSettings,
            },
        });
    };

    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.borderRadiusLarge"
                            />
                            <BoxShadowFieldEditor
                                label={t('Shadow')}
                                value={currentSettings.container.shadow}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('container', 'shadow', v)}
                                disabled={disabled}
                                defaultGlobalRef="effects.shadowMedium"
                            />
                            <PaddingFieldEditor
                                label={t('Padding')}
                                value={currentSettings.container.padding}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('container', 'padding', v)}
                                disabled={disabled}
                                fallback="16px 20px 20px"
                            />
                        </div>
                    </div>
                    <div>
                        <h4 className="text-sm font-medium text-gray-700 mb-3">{t('Header')}</h4>
                        <div className="space-y-3">
                            <LinkedFieldEditor
                                label={t('Background Color')}
                                value={currentSettings.header.background}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('header', 'background', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <LinkedFieldEditor
                                label={t('Gradient End Color')}
                                value={
                                    typeof currentSettings.header.gradientEnd === 'string'
                                        ? createCustomValue(currentSettings.header.gradientEnd)
                                        : (currentSettings.header.gradientEnd ?? createCustomValue('#2BA8B5'))
                                }
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('header', 'gradientEnd' as any, v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                        </div>
                    </div>
                </div>
            ),
        },
        {
            id: 'avatar',
            label: t('Avatar'),
            icon: <User size={14} />,
            content: (
                <div className="space-y-6">
                    <div>
                        <h4 className="text-sm font-medium text-gray-700 mb-3">{t('Profile Picture')}</h4>
                        <div className="space-y-3">
                            <LinkedFieldEditor
                                label={t('Size')}
                                value={currentSettings.avatar.size ?? createGlobalRef('sizes.avatarLarge')}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('avatar', 'size', v)}
                                fieldType="size"
                                allowGlobalLink={true}
                                disabled={disabled}
                                placeholder="80px"
                            />
                            <BorderRadiusFieldEditor
                                label={t('Border Radius')}
                                value={currentSettings.avatar.borderRadius}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('avatar', 'borderRadius', v)}
                                disabled={disabled}
                                defaultGlobalRef="effects.borderRadiusFull"
                            />
                            <BorderStyleSelect
                                label={t('Border Style')}
                                value={currentSettings.avatar.borderStyle || 'solid'}
                                onChange={(v) => handleFieldChange('avatar', 'borderStyle' as any, v)}
                                disabled={disabled}
                            />
                            <LinkedFieldEditor
                                label={t('Border Thickness')}
                                value={currentSettings.avatar.borderWidth ?? createGlobalRef('sizes.avatarBorderWidth')}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('avatar', 'borderWidth' as any, v)}
                                fieldType="size"
                                allowGlobalLink={true}
                                disabled={disabled}
                                placeholder="4px"
                            />
                            <LinkedFieldEditor
                                label={t('Border Color')}
                                value={currentSettings.avatar.borderColor}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('avatar', 'borderColor', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <LinkedFieldEditor
                                label={t('Background Color')}
                                value={currentSettings.avatar.background}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('avatar', 'background', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <LinkedFieldEditor
                                label={t('Icon Color')}
                                value={currentSettings.avatar.iconColor ?? createGlobalRef('colors.primary')}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('avatar', 'iconColor' as any, v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <LinkedFieldEditor
                                label={t('Icon Size')}
                                value={currentSettings.avatar.iconSize ?? createGlobalRef('sizes.avatarIcon')}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('avatar', 'iconSize' as any, v)}
                                fieldType="size"
                                allowGlobalLink={true}
                                disabled={disabled}
                                placeholder="36px"
                            />
                            <BoxShadowFieldEditor
                                label={t('Shadow')}
                                value={currentSettings.avatar.shadow ?? createGlobalRef('effects.shadowSmall')}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('avatar', 'shadow' as any, v)}
                                disabled={disabled}
                                defaultGlobalRef="effects.shadowSmall"
                            />
                        </div>
                    </div>
                </div>
            ),
        },
        {
            id: 'info',
            label: t('Details'),
            icon: <Phone size={14} />,
            content: (
                <div className="space-y-6">
                    <div>
                        <h4 className="text-sm font-medium text-gray-700 mb-3">{t('Name')}</h4>
                        <div className="space-y-3">
                            <LinkedFieldEditor
                                label={t('Color')}
                                value={currentSettings.name.color}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('name', 'color', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                        </div>
                        <div className="mt-3">
                            <h4 className="text-sm font-medium text-gray-700 mb-3">{t('Typography')}</h4>
                            <TypographyControl
                                label={t('Name Text Styling')}
                                value={currentSettings.name.typography as TypographySettings || {}}
                                globalValues={globalValues}
                                onChange={(typography) => handleTypographyChange('name', typography)}
                                disabled={disabled}
                            />
                        </div>
                    </div>
                    <div>
                        <h4 className="text-sm font-medium text-gray-700 mb-3">{t('Role')}</h4>
                        <div className="space-y-3">
                            <LinkedFieldEditor
                                label={t('Color')}
                                value={currentSettings.title.color}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('title', 'color', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                        </div>
                        <div className="mt-3">
                            <h4 className="text-sm font-medium text-gray-700 mb-3">{t('Typography')}</h4>
                            <TypographyControl
                                label={t('Role Text Styling')}
                                value={currentSettings.title.typography as TypographySettings || {}}
                                globalValues={globalValues}
                                onChange={(typography) => handleTypographyChange('title', typography)}
                                disabled={disabled}
                            />
                        </div>
                    </div>
                    <div>
                        <h4 className="text-sm font-medium text-gray-700 mb-3">{t('Info Fields')}</h4>
                        <div className="space-y-3">
                            <LinkedFieldEditor
                                label={t('Icon Color')}
                                value={currentSettings.fields.iconColor}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('fields', 'iconColor', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <LinkedFieldEditor
                                label={t('Label Color')}
                                value={currentSettings.fields.labelColor}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('fields', 'labelColor', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <LinkedFieldEditor
                                label={t('Value Color')}
                                value={currentSettings.fields.valueColor}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('fields', 'valueColor', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                        </div>
                        <div className="mt-3 space-y-3">
                            <TypographyControl
                                label={t('Labels Typography')}
                                value={currentSettings.fields.labelTypography as TypographySettings || {}}
                                globalValues={globalValues}
                                onChange={(typography) => handleTypographyFieldChange('fields', 'labelTypography', typography)}
                                disabled={disabled}
                            />
                            <TypographyControl
                                label={t('Values Typography')}
                                value={currentSettings.fields.valueTypography as TypographySettings || {}}
                                globalValues={globalValues}
                                onChange={(typography) => handleTypographyFieldChange('fields', 'valueTypography', typography)}
                                disabled={disabled}
                            />
                        </div>
                    </div>
                </div>
            ),
        },
        {
            id: 'buttons',
            label: t('Buttons'),
            icon: <Mail size={14} />,
            content: (
                <div className="space-y-6">
                    <div>
                        <h4 className="text-sm font-medium text-gray-700 mb-3">{t('Primary Button')}</h4>
                        <ButtonStyleEditor
                            value={
                                (currentSettings.buttons.primaryButtonStyle as ButtonStyleValue) ||
                                (DEFAULT_WIDGET_SETTINGS.contactCard.buttons.primaryButtonStyle as ButtonStyleValue)
                            }
                            onChange={handlePrimaryButtonStyleChange}
                            globalValues={globalValues}
                            label=""
                            disabled={disabled}
                            showIcon={true}
                            showIconPicker={true}
                            showTypography={true}
                        />
                    </div>
                    <div className="border-t pt-6">
                        <h4 className="text-sm font-medium text-gray-700 mb-3">{t('Secondary Button')}</h4>
                        <ButtonStyleEditor
                            value={
                                (currentSettings.buttons.secondaryButtonStyle as ButtonStyleValue) ||
                                (DEFAULT_WIDGET_SETTINGS.contactCard.buttons.secondaryButtonStyle as ButtonStyleValue)
                            }
                            onChange={handleSecondaryButtonStyleChange}
                            globalValues={globalValues}
                            label=""
                            disabled={disabled}
                            showIcon={true}
                            showIconPicker={true}
                            showTypography={true}
                        />
                    </div>
                </div>
            ),
        },
    ];

    return (
        <WidgetSectionBase
            title={`👤 ${t('Contact Card')}`}
            description={t('Contact card styling for chat conversations')}
            icon={<UserCircle size={24} />}
            tabs={tabs}
            disableSettingsPointerEvents={disableSettingsPointerEvents}
            onLockedHoverActionClick={onLockedHoverActionClick}
            preview={
                <ContactCardPreview
                    globalValues={globalValues}
                    widgetSettings={currentSettings}
                    isRTL={isRTL}
                    language={currentLanguage}
                />
            }
            defaultCollapsed={true}
        />
    );
};

export default ContactCardSection;
