const { registerBlockType } = wp.blocks;
const { createElement, Fragment, useState, useEffect } = wp.element;
const { InspectorControls } = wp.blockEditor || wp.editor; // For backward compatibility
const { PanelBody, SelectControl, TextControl, ToggleControl, ColorPalette } = wp.components;

registerBlockType('ciwp/whatsapp-icon', {
    title: 'CIWS WhatsApp Icon',
    icon: 'whatsapp',
    category: 'widgets',
    attributes: {
        accountName: { type: 'string', default: 'John Doe' },
        buttonLabel: { type: 'string', default: 'Chat with us!' },
        desktopURLType: { type: 'string', default: 'web' },
        mobileURLType: { type: 'string', default: 'web' },
        template: { type: 'string', default: 'ciws-template-1' },
        openInNewTab: { type: 'boolean', default: true },
        customClass: { type: 'string', default: '' },
        accountId: { type: 'string', default: '' },
        buttonFillColor: { type: 'string', default: '#5bd26d' },
        buttonTextColor: { type: 'string', default: '#ffffff' },
        phoneNumber: { type: 'string', default: '' },
        defaultMessage: { type: 'string', default: 'Hello, I need assistance!' },
    },

    edit: (props) => {
        const { attributes, setAttributes } = props;
        const [accounts, setAccounts] = useState([]);
        const [isLoading, setIsLoading] = useState(true);

        useEffect(() => {
            wp.apiRequest({ path: '/ciws/v1/accounts' }).then((data) => {
                setAccounts(data);
                setIsLoading(false);
            }).catch((error) => {
                console.error('Error fetching accounts:', error);
                setIsLoading(false);
            });
        }, []);

        const handleAccountChange = (accountId) => {
            const selectedAccount = accounts.find(account => account.id === accountId);
            if (selectedAccount) {
                setAttributes({
                    accountId: selectedAccount.id,
                    accountName: selectedAccount.name,
                    phoneNumber: selectedAccount.number,
                    defaultMessage: selectedAccount.default_msg,
                    desktopURLType: selectedAccount.number,
                });
            }
        };

        return createElement(
            Fragment,
            {},
            createElement(
                InspectorControls,
                {},
                createElement(
                    PanelBody,
                    { title: 'WhatsApp Button Settings', initialOpen: true },
                    createElement(SelectControl, {
                        label: 'Select Account',
                        value: attributes.accountId,
                        options: [
                            { label: 'Select an Account', value: '' },
                            ...accounts.map(account => ({
                                label: account.name,
                                value: account.id,
                            }))
                        ],
                        onChange: handleAccountChange,
                        disabled: isLoading,
                    }),
                    createElement(TextControl, {
                        label: 'Button Label',
                        value: attributes.buttonLabel,
                        onChange: (value) => setAttributes({ buttonLabel: value }),
                    }),
                    createElement(SelectControl, {
                        label: 'Desktop URL Type',
                        value: attributes.desktopURLType,
                        options: [
                            { label: 'Web WhatsApp', value: 'web' },
                            { label: 'API (Desktop App)', value: 'api' },
                        ],
                        onChange: (value) => setAttributes({ desktopURLType: value }),
                    }),
                    createElement(SelectControl, {
                        label: 'Mobile URL Type',
                        value: attributes.mobileURLType,
                        options: [
                            { label: 'Web WhatsApp', value: 'web' },
                            { label: 'API (Mobile App)', value: 'api' },
                        ],
                        onChange: (value) => setAttributes({ mobileURLType: value }),
                    }),
                    createElement(ToggleControl, {
                        label: 'Open in New Tab',
                        checked: attributes.openInNewTab,
                        onChange: (value) => setAttributes({ openInNewTab: value }),
                    }),
                    createElement(TextControl, {
                        label: 'Custom Class',
                        value: attributes.customClass,
                        onChange: (value) => setAttributes({ customClass: value }),
                    }),
                    createElement(TextControl, {
                        label: 'Phone Number',
                        value: attributes.phoneNumber,
                        onChange: (value) => setAttributes({ phoneNumber: value }),
                    }),
                    createElement(TextControl, {
                        label: 'Default Message',
                        value: attributes.defaultMessage,
                        onChange: (value) => setAttributes({ defaultMessage: value }),
                    })
                ),
                createElement(
                    PanelBody,
                    { title: 'Color Customization', initialOpen: false },
                    createElement('p', {}, 'Button Fill Color'),
                    createElement(ColorPalette, {
                        value: attributes.buttonFillColor,
                        onChange: (value) => setAttributes({ buttonFillColor: value }),
                    }),
                    createElement('p', {}, 'Button Text Color'),
                    createElement(ColorPalette, {
                        value: attributes.buttonTextColor,
                        onChange: (value) => setAttributes({ buttonTextColor: value }),
                    })
                ),
                createElement(
                    PanelBody,
                    { title: 'Template', initialOpen: false },
                    createElement(SelectControl, {
                        label: 'Select Template',
                        value: attributes.template,
                        options: [
                            { label: 'Template 1', value: 'ciws-template-1' },
                            { label: 'Template 2', value: 'ciws-template-2' },
                            { label: 'Template 3', value: 'ciws-template-3' },
                        ],
                        onChange: (value) => setAttributes({ template: value }),
                    })
                )
            ),
            createElement(
                'div',
                {
                    className: `ciws-button-wrapper ${attributes.template} ${attributes.customClass}`,
                },
                createElement(
                    'div',
                    { className: 'ciws-button', style: { backgroundColor: attributes.buttonFillColor } },
                    createElement(
                        'a',
                        {
                            href:
                                attributes.desktopURLType === 'web'
                                    ? `https://web.whatsapp.com/send?phone=${attributes.phoneNumber}&text=${encodeURIComponent(attributes.defaultMessage)}`
                                    : `https://api.whatsapp.com/send?phone=${attributes.phoneNumber}&text=${encodeURIComponent(attributes.defaultMessage)}`,
                            target: attributes.openInNewTab ? '_blank' : '',
                            className: 'ciws-btn-content-wrap ciws-computer-url',
                            style: { color: attributes.buttonTextColor },
                        },
                        createElement(
                            'div',
                            { className: 'ciws-icon-wrap' },
                            createElement('img', {
                                src: ciwsData.imageUrl + '/ciws-whatsapp.svg',
                                alt: 'WhatsApp Icon',
                            })
                        ),
                        createElement(
                            'div',
                            { className: 'ciws-btn-info-wrap' },
                            createElement(
                                'div',
                                { className: 'ciws-btn-info' },
                                createElement(
                                    'div',
                                    { className: 'ciws-account-name', style: { color: attributes.buttonTextColor } },
                                    attributes.accountName
                                ),
                                // Adding the new element after account name
                                createElement('div', { className: 'ciws-status' })
                            ),
                            createElement(
                                'div',
                                { className: 'ciws-btn-title', style: { color: attributes.buttonTextColor } },
                                attributes.buttonLabel
                            )
                        )
                    )
                )
            )
        );
    },

    save: (props) => {
        const { attributes } = props;

        return createElement(
            'div',
            {
                className: `ciws-button-wrapper ${attributes.template} ${attributes.customClass}`,
            },
            createElement(
                'div',
                { className: 'ciws-button', style: { backgroundColor: attributes.buttonFillColor } },
                createElement(
                    'a',
                    {
                        href: attributes.desktopURLType === 'web'
                            ? `https://web.whatsapp.com/send?phone=${attributes.phoneNumber}&text=${encodeURIComponent(attributes.defaultMessage)}`
                            : `https://api.whatsapp.com/send?phone=${attributes.phoneNumber}&text=${encodeURIComponent(attributes.defaultMessage)}`,
                        target: attributes.openInNewTab ? '_blank' : '',
                        className: 'ciws-btn-content-wrap ciws-computer-url',
                        style: { color: attributes.buttonTextColor },
                    },
                    createElement(
                        'div',
                        { className: 'ciws-icon-wrap' },
                        createElement('img', {
                            src: ciwsData.imageUrl + '/ciws-whatsapp.svg',
                            alt: 'WhatsApp Icon',
                        })
                    ),
                    createElement(
                        'div',
                        { className: 'ciws-btn-info-wrap' },
                        createElement(
                            'div',
                            { className: 'ciws-btn-info' },
                            createElement(
                                'div',
                                { className: 'ciws-account-name', style: { color: attributes.buttonTextColor } },
                                attributes.accountName
                            ),
                            // Adding the new element after account name
                            createElement('div', { className: 'ciws-status' })
                        ),
                        createElement(
                            'div',
                            { className: 'ciws-btn-title', style: { color: attributes.buttonTextColor } },
                            attributes.buttonLabel
                        )
                    )
                )
            )
        );
    },
});
