/**
 * Survey Widget Section
 * 
 * Settings for rating and survey widgets displayed in chat.
 * 
 * @since 1.5.0
 */

import React from 'react';
import { Star, Palette, Hash, Smile, MessageSquare, Send, ThumbsUp, CheckCircle2 } from 'lucide-react';
import { WidgetSectionBase, WidgetSectionTab } from './WidgetSectionBase';
import { LinkedFieldEditor } from '../LinkedFieldEditor';
import { TypographyControl, TypographySettings } from '../TypographyControl';
import { SurveyPreview } from '../PreviewElements';
import { ButtonStyleEditor, ButtonStyleValue } from '../../common/ButtonStyleEditor';
import { BorderRadiusFieldEditor } from '../../common/BorderRadiusFieldEditor';
import { PaddingFieldEditor } from '../../common/PaddingFieldEditor';
import { BoxShadowFieldEditor } from '../../common/BoxShadowFieldEditor';
import { HoverScaleControl } from '../../common/HoverScaleControl';
import { deepMerge } from '../../../utils/appearanceMerge';
import { 
    SurveyWidgetSettings, 
    PresetGlobalValues, 
    DEFAULT_WIDGET_SETTINGS,
    FieldValue,
    ElementTypography,
    ButtonStyleSettings,
    createDefaultButtonStyle,
    createCustomValue,
} from '../../../types/appearance';
import { t } from '@/lib/i18n';
import { useLanguage } from '@/contexts/LanguageContext';

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

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

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

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

    // Handler for optional section field changes (e.g., success section)
    const handleOptionalSectionChange = (
        sectionKey: 'success' | 'thumbs',
        fieldKey: string,
        value: FieldValue | string
    ) => {
        onChange({
            ...currentSettings,
            [sectionKey]: {
                ...((currentSettings as unknown as Record<string, Record<string, unknown> | undefined>)[sectionKey] || {}),
                [fieldKey]: value,
            },
        });
    };

    // Handler for submit button style changes (full ButtonStyleSettings)
    const handleButtonStyleChange = (buttonStyle: ButtonStyleValue) => {
        onChange({
            ...currentSettings,
            submit: {
                ...currentSettings.submit,
                buttonStyle: 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}
                            />
                            <LinkedFieldEditor
                                label={t('Border Color')}
                                value={currentSettings.container.borderColor}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('container', 'borderColor', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <LinkedFieldEditor
                                label={t('Border Width')}
                                value={currentSettings.container.borderWidth}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('container', 'borderWidth', v)}
                                fieldType="size"
                                allowGlobalLink={true}
                                disabled={disabled}
                                placeholder="0px"
                            />
                            <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="12px"
                            />
                            <BoxShadowFieldEditor
                                label={t('Shadow')}
                                value={currentSettings.container.shadow}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('container', 'shadow', v)}
                                disabled={disabled}
                                defaultGlobalRef="effects.shadowNone"
                            />
                        </div>
                    </div>
                    <div>
                        <h4 className="text-sm font-medium text-gray-700 mb-3">{t('Title')}</h4>
                        <div className="space-y-3">
                            <LinkedFieldEditor
                                label={t('Text Color')}
                                value={currentSettings.title.color}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('title', 'color', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                        </div>
                        <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>
                        <h4 className="text-sm font-medium text-gray-700 mb-3">{t('Question')}</h4>
                        <div className="space-y-3">
                            <LinkedFieldEditor
                                label={t('Text Color')}
                                value={currentSettings.question.color}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('question', 'color', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                        </div>
                        <div className="mt-3">
                            <TypographyControl
                                label={t('Question Text Styling')}
                                value={currentSettings.question.typography as TypographySettings || {}}
                                globalValues={globalValues}
                                onChange={(typography) => handleTypographyChange('question', typography)}
                                disabled={disabled}
                            />
                        </div>
                    </div>
                </div>
            ),
        },
        {
            id: 'stars',
            label: t('Stars'),
            icon: <Star size={14} />,
            content: (
                <div className="space-y-6">
                    <div>
                        <h4 className="text-sm font-medium text-gray-700 mb-3">{t('Star Rating')}</h4>
                        <div className="space-y-3">
                            <LinkedFieldEditor
                                label={t('Size')}
                                value={currentSettings.stars.size ?? createCustomValue('32px')}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('stars', 'size', v)}
                                fieldType="size"
                                allowGlobalLink={true}
                                disabled={disabled}
                                placeholder="32px"
                            />
                            <LinkedFieldEditor
                                label={t('Filled Star Color')}
                                value={currentSettings.stars.filledColor}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('stars', 'filledColor', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <LinkedFieldEditor
                                label={t('Empty Star Color')}
                                value={currentSettings.stars.emptyColor}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('stars', 'emptyColor', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <LinkedFieldEditor
                                label={t('Hover Color')}
                                value={currentSettings.stars.hoverColor ?? createCustomValue('#F59E0B')}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('stars', 'hoverColor', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <LinkedFieldEditor
                                label={t('Stroke Color')}
                                value={currentSettings.stars.strokeColor ?? createCustomValue('#D1D5DB')}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('stars', 'strokeColor', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <LinkedFieldEditor
                                label={t('Stroke Width')}
                                value={currentSettings.stars.strokeWidth ?? createCustomValue('1.5px')}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('stars', 'strokeWidth', v)}
                                fieldType="size"
                                allowGlobalLink={true}
                                disabled={disabled}
                                placeholder="1.5px"
                            />
                            <LinkedFieldEditor
                                label={t('Gap Between Stars')}
                                value={currentSettings.stars.gap ?? createCustomValue('8px')}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('stars', 'gap', v)}
                                fieldType="size"
                                allowGlobalLink={true}
                                disabled={disabled}
                                placeholder="8px"
                            />
                            <HoverScaleControl
                                label={t('Hover Scale')}
                                value={currentSettings.stars.hoverScale}
                                onChange={(v) => handleFieldChange('stars', 'hoverScale', v)}
                                disabled={disabled}
                            />
                        </div>
                    </div>
                </div>
            ),
        },
        {
            id: 'numbers',
            label: t('Numbers'),
            icon: <Hash size={14} />,
            content: (
                <div className="space-y-6">
                    <div>
                        <h4 className="text-sm font-medium text-gray-700 mb-3">{t('Numeric Rating (1-10)')}</h4>
                        <div className="space-y-3">
                            <LinkedFieldEditor
                                label={t('Background Color')}
                                value={currentSettings.numbers.background}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('numbers', 'background', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <LinkedFieldEditor
                                label={t('Text Color')}
                                value={currentSettings.numbers.color}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('numbers', 'color', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <LinkedFieldEditor
                                label={t('Selected Background')}
                                value={currentSettings.numbers.selectedBackground}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('numbers', 'selectedBackground', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <LinkedFieldEditor
                                label={t('Selected Text')}
                                value={currentSettings.numbers.selectedColor}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('numbers', 'selectedColor', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            {/* Unified radius template */}
                            <BorderRadiusFieldEditor
                                label={t('Border Radius')}
                                value={currentSettings.numbers.borderRadius}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('numbers', 'borderRadius', v)}
                                disabled={disabled}
                                defaultGlobalRef="effects.borderRadiusSmall"
                            />
                            <LinkedFieldEditor
                                label={t('Border Color')}
                                value={currentSettings.numbers.borderColor ?? createCustomValue('#E5E7EB')}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('numbers', 'borderColor', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                        </div>
                        <div className="mt-3">
                            <TypographyControl
                                label={t('Numbers Text Styling')}
                                value={currentSettings.numbers.typography as TypographySettings || {}}
                                globalValues={globalValues}
                                onChange={(typography) => handleTypographyChange('numbers' as never, typography)}
                                disabled={disabled}
                            />
                        </div>
                    </div>
                </div>
            ),
        },
        {
            id: 'emojis',
            label: t('Emoji'),
            icon: <Smile size={14} />,
            content: (
                <div className="space-y-6">
                    <div>
                        <h4 className="text-sm font-medium text-gray-700 mb-3">{t('Emoji Rating')}</h4>
                        <div className="space-y-3">
                            <LinkedFieldEditor
                                label={t('Size')}
                                value={currentSettings.emojis.size ?? createCustomValue('40px')}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('emojis', 'size', v)}
                                fieldType="size"
                                allowGlobalLink={true}
                                disabled={disabled}
                                placeholder="40px"
                            />
                            <LinkedFieldEditor
                                label={t('Gap')}
                                value={currentSettings.emojis.gap ?? createCustomValue('12px')}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('emojis', 'gap', v)}
                                fieldType="size"
                                allowGlobalLink={true}
                                disabled={disabled}
                                placeholder="12px"
                            />
                            <LinkedFieldEditor
                                label={t('Default Background')}
                                value={currentSettings.emojis.defaultColor}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('emojis', 'defaultColor', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <LinkedFieldEditor
                                label={t('Selected Background')}
                                value={currentSettings.emojis.selectedColor}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('emojis', 'selectedColor', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <HoverScaleControl
                                label={t('Hover Scale')}
                                value={currentSettings.emojis.hoverScale}
                                onChange={(v) => handleFieldChange('emojis', 'hoverScale', v)}
                                disabled={disabled}
                            />
                            <HoverScaleControl
                                label={t('Selection Scale')}
                                value={currentSettings.emojis.selectedScale}
                                onChange={(v) => handleFieldChange('emojis', 'selectedScale', v)}
                                disabled={disabled}
                            />
                            <LinkedFieldEditor
                                label={t('Container Padding')}
                                value={currentSettings.emojis.containerPadding ?? createCustomValue('0px')}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('emojis', 'containerPadding', v)}
                                fieldType="size"
                                allowGlobalLink={true}
                                disabled={disabled}
                                placeholder="0px"
                            />
                            <LinkedFieldEditor
                                label={t('Container Background')}
                                value={currentSettings.emojis.containerBackground}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('emojis', 'containerBackground', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <LinkedFieldEditor
                                label={t('Selected Border Color')}
                                value={currentSettings.emojis.selectedBorderColor}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('emojis', 'selectedBorderColor', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                        </div>
                    </div>
                </div>
            ),
        },
        {
            id: 'thumbs',
            label: t('Thumbs'),
            icon: <ThumbsUp size={14} />,
            content: (
                <div className="space-y-6">
                    <div>
                        <h4 className="text-sm font-medium text-gray-700 mb-3">{t('Thumbs Rating')}</h4>
                        <div className="space-y-3">
                            <LinkedFieldEditor
                                label={t('Size')}
                                value={currentSettings.thumbs?.size ?? createCustomValue('32px')}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('thumbs', 'size', v)}
                                fieldType="size"
                                allowGlobalLink={true}
                                disabled={disabled}
                                placeholder="32px"
                            />
                            <LinkedFieldEditor
                                label={t('Gap')}
                                value={currentSettings.thumbs?.gap ?? createCustomValue('24px')}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('thumbs', 'gap', v)}
                                fieldType="size"
                                allowGlobalLink={true}
                                disabled={disabled}
                                placeholder="24px"
                            />
                            <LinkedFieldEditor
                                label={t('Thumb Up Color')}
                                value={currentSettings.thumbs?.upColor ?? createCustomValue('#22C55E')}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('thumbs', 'upColor', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <LinkedFieldEditor
                                label={t('Thumb Down Color')}
                                value={currentSettings.thumbs?.downColor ?? createCustomValue('#EF4444')}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('thumbs', 'downColor', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <LinkedFieldEditor
                                label={t('Selected Background')}
                                value={currentSettings.thumbs?.selectedBackground ?? createCustomValue('rgba(34, 197, 94, 0.1)')}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('thumbs', 'selectedBackground', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                        </div>
                    </div>
                </div>
            ),
        },
        {
            id: 'success',
            label: t('Success'),
            icon: <CheckCircle2 size={14} />,
            content: (
                <div className="space-y-6">
                    <div>
                        <h4 className="text-sm font-medium text-gray-700 mb-3">{t('Success Screen')}</h4>
                        <div className="space-y-3">
                            <LinkedFieldEditor
                                label={t('Icon Color')}
                                value={currentSettings.success?.iconColor ?? createCustomValue('#22C55E')}
                                globalValues={globalValues}
                                onChange={(v) => handleOptionalSectionChange('success', 'iconColor', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <LinkedFieldEditor
                                label={t('Icon Size')}
                                value={currentSettings.success?.iconSize ?? createCustomValue('32px')}
                                globalValues={globalValues}
                                onChange={(v) => handleOptionalSectionChange('success', 'iconSize', v)}
                                fieldType="size"
                                allowGlobalLink={true}
                                disabled={disabled}
                                placeholder="32px"
                            />
                            <LinkedFieldEditor
                                label={t('Text Color')}
                                value={currentSettings.success?.textColor ?? createCustomValue('#111827')}
                                globalValues={globalValues}
                                onChange={(v) => handleOptionalSectionChange('success', 'textColor', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                        </div>
                        <div className="mt-3">
                            <TypographyControl
                                label={t('Success Text Styling')}
                                value={currentSettings.success?.typography as TypographySettings || {}}
                                globalValues={globalValues}
                                onChange={(typography) => handleTypographyChange('success' as never, typography)}
                                disabled={disabled}
                            />
                        </div>
                    </div>
                </div>
            ),
        },
        {
            id: 'feedback',
            label: t('Feedback'),
            icon: <MessageSquare size={14} />,
            content: (
                <div className="space-y-6">
                    <div>
                        <h4 className="text-sm font-medium text-gray-700 mb-3">{t('Text Feedback Field')}</h4>
                        <div className="space-y-3">
                            <LinkedFieldEditor
                                label={t('Background Color')}
                                value={currentSettings.feedback.background}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('feedback', 'background', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <LinkedFieldEditor
                                label={t('Border Color')}
                                value={currentSettings.feedback.border}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('feedback', 'border', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <LinkedFieldEditor
                                label={t('Text Color')}
                                value={currentSettings.feedback.color}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('feedback', 'color', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <LinkedFieldEditor
                                label={t('Placeholder Text Color')}
                                value={currentSettings.feedback.placeholderColor}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('feedback', 'placeholderColor', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            <LinkedFieldEditor
                                label={t('Focus Border Color')}
                                value={currentSettings.feedback.focusBorderColor}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('feedback', 'focusBorderColor', v)}
                                fieldType="color"
                                disabled={disabled}
                            />
                            {/* Unified radius template */}
                            <BorderRadiusFieldEditor
                                label={t('Border Radius')}
                                value={currentSettings.feedback.borderRadius}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('feedback', 'borderRadius', v)}
                                disabled={disabled}
                                defaultGlobalRef="effects.borderRadiusSmall"
                            />
                            <LinkedFieldEditor
                                label={t('Minimum Height')}
                                value={currentSettings.feedback.minHeight}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('feedback', 'minHeight', v)}
                                fieldType="size"
                                allowGlobalLink={true}
                                disabled={disabled}
                                placeholder="80px"
                            />
                            <PaddingFieldEditor
                                label={t('Padding')}
                                value={currentSettings.feedback.padding}
                                globalValues={globalValues}
                                onChange={(v) => handleFieldChange('feedback', 'padding', v)}
                                disabled={disabled}
                                fallback="12px 16px"
                            />
                        </div>
                        <div className="mt-3">
                            <TypographyControl
                                label={t('Feedback Text Styling')}
                                value={currentSettings.feedback.typography as TypographySettings || {}}
                                globalValues={globalValues}
                                onChange={(typography) => handleTypographyChange('feedback', typography)}
                                disabled={disabled}
                            />
                        </div>
                    </div>
                </div>
            ),
        },
        {
            id: 'submit',
            label: t('Submit'),
            icon: <Send size={14} />,
            content: (
                <div className="space-y-6">
                    <div>
                        <h4 className="text-sm font-medium text-gray-700 mb-3">{t('Submit Button')}</h4>
                        <ButtonStyleEditor
                            value={(currentSettings.submit.buttonStyle as ButtonStyleValue) || createDefaultButtonStyle('primary')}
                            onChange={handleButtonStyleChange}
                            globalValues={globalValues}
                            label=""
                            disabled={disabled}
                            showIcon={true}
                            showIconPicker={true}
                            showTypography={true}
                        />
                    </div>
                </div>
            ),
        },
    ];

    return (
        <WidgetSectionBase
            title={`⭐ ${t('Survey / Rating')}`}
            description={t('Rating and satisfaction survey styling')}
            icon={<Star size={24} />}
            tabs={tabs}
            disableSettingsPointerEvents={disableSettingsPointerEvents}
            onLockedHoverActionClick={onLockedHoverActionClick}
            preview={
                <SurveyPreview 
                    globalValues={globalValues} 
                    widgetSettings={currentSettings}
                    isRTL={isRTL}
                    language={currentLanguage}
                />
            }
            defaultCollapsed={true}
        />
    );
};

export default SurveySection;
