import { registerBlockType } from '@wordpress/blocks';

import { __ } from '@wordpress/i18n';
import { useState } from '@wordpress/element';
import { InspectorControls, useBlockProps, MediaUpload, MediaUploadCheck } from '@wordpress/block-editor';
import { PanelBody, SelectControl, TextControl, TextareaControl, RadioControl, Button } from '@wordpress/components';
import { applyFilters } from '@wordpress/hooks';
import { StyleControl } from '@agencenous/blocss';
import { save_null } from '../common';

const DASHICON_OPTIONS = [
    { label: 'Chat', value: 'format-chat' },
    { label: 'Admin Comments', value: 'admin-comments' },
    { label: 'Testimonial', value: 'testimonial' },
    { label: 'Editor Help', value: 'editor-help' },
    { label: 'Info', value: 'info' },
    { label: 'Info Outline', value: 'info-outline' },
    { label: 'Smiley', value: 'smiley' },
    { label: 'Microphone', value: 'microphone' },
    { label: 'Megaphone', value: 'megaphone' },
    { label: 'Email', value: 'email' },
    { label: 'Email Alt', value: 'email-alt' },
    { label: 'Businessman', value: 'businessman' },
    { label: 'Businesswoman', value: 'businesswoman' },
    { label: 'Nametag', value: 'nametag' },
    { label: 'Welcome Learn More', value: 'welcome-learn-more' },
];

const sectionTitleStyle = {
    fontSize: '11px',
    fontWeight: '600',
    textTransform: 'uppercase',
    letterSpacing: '0.5px',
    color: '#1e1e1e',
    marginTop: '16px',
    marginBottom: '8px',
    paddingBottom: '4px',
    borderBottom: '1px solid #e0e0e0',
};

const iconPreviewStyle = {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    padding: '16px',
    backgroundColor: '#f0f0f0',
    borderRadius: '8px',
    marginTop: '12px',
    marginBottom: '12px',
};

const svgPreviewStyle = {
    width: '32px',
    height: '32px',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
};

const imagePreviewContainerStyle = {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    gap: '8px',
    marginTop: '12px',
};

const imagePreviewStyle = {
    width: '48px',
    height: '48px',
    objectFit: 'contain',
    borderRadius: '4px',
    border: '1px solid #ddd',
};

registerBlockType('faqtastic/chatbot', {
    edit: (props) => {
        const { className, setAttributes, attributes } = props;
        const [open, setOpen] = useState(false);
        const {
            btnStyle,
            chatbotHeaderText,
            chatbotHeaderSubtitle,
            chatbotFirstMsg,
            chatInputPlaceholder,
            chatbotPosition,
            toggleIconType,
            toggleIconDashicon,
            toggleIconSvg,
            toggleIconImageId,
            toggleIconImageUrl,
        } = attributes;
        const blockProps = useBlockProps();

        const isReactElement = (element) => {
            if (element && element.$$typeof && element.$$typeof.toString() === 'Symbol(react.element)') {
                return element;
            }
            return null;
        }

        const onSelectImage = (media) => {
            setAttributes({
                toggleIconImageId: media.id,
                toggleIconImageUrl: media.url,
            });
        };

        const onRemoveImage = () => {
            setAttributes({
                toggleIconImageId: 0,
                toggleIconImageUrl: '',
            });
        };

        const renderToggleIcon = () => {
            if (toggleIconType === 'image' && toggleIconImageUrl) {
                return <img src={toggleIconImageUrl} alt="" style={{ width: '24px', height: '24px', objectFit: 'contain' }} />;
            }
            if (toggleIconType === 'svg' && toggleIconSvg) {
                return <span dangerouslySetInnerHTML={{ __html: toggleIconSvg }} style={svgPreviewStyle} />;
            }
            return <span className={`dashicons dashicons-${toggleIconDashicon || 'format-chat'}`}></span>;
        };

        const renderIconPreview = () => {
            if (toggleIconType === 'image' && toggleIconImageUrl) {
                return (
                    <div style={iconPreviewStyle}>
                        <img src={toggleIconImageUrl} alt="" style={{ width: '32px', height: '32px', objectFit: 'contain' }} />
                    </div>
                );
            }
            if (toggleIconType === 'svg' && toggleIconSvg) {
                return (
                    <div style={iconPreviewStyle}>
                        <div
                            dangerouslySetInnerHTML={{ __html: toggleIconSvg }}
                            style={{ width: '32px', height: '32px' }}
                        />
                    </div>
                );
            }
            return (
                <div style={iconPreviewStyle}>
                    <span
                        className={`dashicons dashicons-${toggleIconDashicon || 'format-chat'}`}
                        style={{ fontSize: '32px', width: '32px', height: '32px' }}
                    ></span>
                </div>
            );
        };

        return (
            <div className={className} {...blockProps}>
                <InspectorControls>
                    {isReactElement(applyFilters('editor.faqtastic.chatbot.inspector.settings.before', props))}
                    <PanelBody title={__('Settings')} initialOpen={true}>
                        {isReactElement(applyFilters('editor.faqtastic.chatbot.inspector.settings.start', props))}
                        <SelectControl
                            label={__('Position')}
                            value={chatbotPosition}
                            options={[
                                { value: 'bottom-right', label: __('Bottom Right') },
                                { value: 'bottom-left', label: __('Bottom Left') },
                                { value: 'top-right', label: __('Top Right') },
                                { value: 'top-left', label: __('Top Left') },
                                { value: 'relative', label: __('Relative') },
                            ]}
                            onChange={(value) => setAttributes({ chatbotPosition: value })}
                        />
                        <TextControl
                            label={__('Title', 'faqtastic')}
                            value={chatbotHeaderText}
                            onChange={(value) => setAttributes({ chatbotHeaderText: value })}
                        />
                        <TextControl
                            label={__('Subtitle', 'faqtastic')}
                            value={chatbotHeaderSubtitle}
                            onChange={(value) => setAttributes({ chatbotHeaderSubtitle: value })}
                            help={__('Optional subtitle displayed below the title', 'faqtastic')}
                        />
                        {isReactElement(applyFilters('editor.faqtastic.chatbot.inspector.settings.end', props))}
                    </PanelBody>
                    {isReactElement(applyFilters('editor.faqtastic.chatbot.inspector.settings.after', props))}
                    {isReactElement(applyFilters('editor.faqtastic.chatbot.inspector.messages.before', props))}
                    <PanelBody title={__('Messages', 'faqtastic')} initialOpen={false}>
                        {isReactElement(applyFilters('editor.faqtastic.chatbot.inspector.messages.start', props))}
                        <TextControl
                            label={__('First Message', 'faqtastic')}
                            value={chatbotFirstMsg}
                            onChange={(value) => setAttributes({ chatbotFirstMsg: value })}
                        />
                        {isReactElement(applyFilters('editor.faqtastic.chatbot.inspector.messages.middle', props))}
                        <TextControl
                            label={__('Input placeholder', 'faqtastic')}
                            value={chatInputPlaceholder}
                            onChange={(value) => setAttributes({ chatInputPlaceholder: value })}
                        />
                        {isReactElement(applyFilters('editor.faqtastic.chatbot.inspector.messages.end', props))}
                    </PanelBody>
                    {isReactElement(applyFilters('editor.faqtastic.chatbot.inspector.messages.after', props))}
                </InspectorControls>
                <InspectorControls group="styles">
                    {isReactElement(applyFilters('editor.faqtastic.chatbot.inspector.styles.before', props))}
                    <PanelBody title={__('Button & Header', 'faqtastic')} initialOpen={true}>
                        {isReactElement(applyFilters('editor.faqtastic.chatbot.inspector.styles.start', props))}
                        <StyleControl
                            value={btnStyle}
                            font={{ size: true }}
                            color={{ text: true, background: true }}
                            onChange={(newValue) => {
                                setAttributes({ btnStyle: newValue });
                            }}
                        />

                        <p style={sectionTitleStyle}>{__('Toggle Button Icon', 'faqtastic')}</p>

                        <RadioControl
                            label={__('Icon Type', 'faqtastic')}
                            selected={toggleIconType || 'dashicon'}
                            options={[
                                { label: __('Dashicon', 'faqtastic'), value: 'dashicon' },
                                { label: __('Custom SVG', 'faqtastic'), value: 'svg' },
                                { label: __('Image', 'faqtastic'), value: 'image' },
                            ]}
                            onChange={(value) => setAttributes({ toggleIconType: value })}
                        />

                        {toggleIconType === 'dashicon' && (
                            <SelectControl
                                label={__('Select Icon', 'faqtastic')}
                                value={toggleIconDashicon || 'format-chat'}
                                options={DASHICON_OPTIONS}
                                onChange={(value) => setAttributes({ toggleIconDashicon: value })}
                            />
                        )}

                        {toggleIconType === 'svg' && (
                            <TextareaControl
                                label={__('SVG Code', 'faqtastic')}
                                value={toggleIconSvg}
                                onChange={(value) => setAttributes({ toggleIconSvg: value })}
                                help={__('Paste your SVG code here. Make sure it includes width and height attributes or viewBox.', 'faqtastic')}
                                rows={6}
                                placeholder='<svg viewBox="0 0 24 24" fill="currentColor">...</svg>'
                            />
                        )}

                        {toggleIconType === 'image' && (
                            <div style={imagePreviewContainerStyle}>
                                <MediaUploadCheck>
                                    <MediaUpload
                                        onSelect={onSelectImage}
                                        allowedTypes={['image']}
                                        value={toggleIconImageId}
                                        render={({ open }) => (
                                            <>
                                                {toggleIconImageUrl ? (
                                                    <>
                                                        <img src={toggleIconImageUrl} alt="" style={imagePreviewStyle} />
                                                        <div style={{ display: 'flex', gap: '8px' }}>
                                                            <Button variant="secondary" onClick={open}>
                                                                {__('Replace Image', 'faqtastic')}
                                                            </Button>
                                                            <Button variant="link" isDestructive onClick={onRemoveImage}>
                                                                {__('Remove', 'faqtastic')}
                                                            </Button>
                                                        </div>
                                                    </>
                                                ) : (
                                                    <Button variant="secondary" onClick={open}>
                                                        {__('Select Image', 'faqtastic')}
                                                    </Button>
                                                )}
                                            </>
                                        )}
                                    />
                                </MediaUploadCheck>
                            </div>
                        )}

                        {renderIconPreview()}
                        {isReactElement(applyFilters('editor.faqtastic.chatbot.inspector.styles.end', props))}
                    </PanelBody>
                    {isReactElement(applyFilters('editor.faqtastic.chatbot.inspector.styles.after', props))}
                </InspectorControls>
                <div className="faqtastic-chatbot-wrapper editor-preview" data-position={chatbotPosition}>
                    {open && (
                        <div className="faqtastic-chatbot-window" style={applyFilters('editor.faqtastic.chatbot.preview.window.style', {}, props)}>
                            <div className="faqtastic-chatbot-header" style={applyFilters('editor.faqtastic.chatbot.preview.header.style', btnStyle, props)}>
                                <div className="faqtastic-chatbot-header-text">
                                    <span className="faqtastic-chatbot-title">{chatbotHeaderText}</span>
                                    {chatbotHeaderSubtitle && (
                                        <span className="faqtastic-chatbot-subtitle">{chatbotHeaderSubtitle}</span>
                                    )}
                                </div>
                                <button className="faqtastic-close-btn">×</button>
                            </div>
                            <div className="faqtastic-chatbot-conversation" style={applyFilters('editor.faqtastic.chatbot.preview.conversation.style', {}, props)}>
                                <div className="faqtastic-chatbot-bubble bot" style={applyFilters('editor.faqtastic.chatbot.preview.bubble-bot.style', {}, props)}>
                                    {chatbotFirstMsg}
                                </div>
                                <div className="faqtastic-chatbot-bubble user" style={applyFilters('editor.faqtastic.chatbot.preview.bubble-user.style', {}, props)}>
                                    {__('Example user message', 'faqtastic')}
                                </div>
                            </div>
                            <input
                                className="faqtastic-chatbot-input"
                                placeholder={chatInputPlaceholder}
                                disabled
                                style={applyFilters('editor.faqtastic.chatbot.preview.input.style', {}, props)}
                            />
                            <ul className="faqtastic-chatbot-suggestions" style={applyFilters('editor.faqtastic.chatbot.preview.suggestions.style', {}, props)}>
                                <li>Suggestion 1</li>
                                <li>Suggestion 2</li>
                            </ul>
                             {isReactElement(applyFilters('faqtastic.chatbot.suggestions.after', props))}
                        </div>
                    )}
                    <button className="faqtastic-chatbot-toggle" style={applyFilters('editor.faqtastic.chatbot.preview.toggle.style', btnStyle, props)} onClick={() => setOpen(!open)}>
                        {renderToggleIcon()}
                    </button>
                </div>
            </div>
        );
    },
    save: save_null,
});