import { useBlockProps, InspectorControls, PanelColorSettings, MediaUpload } from '@wordpress/block-editor';
import { PanelBody, TextControl, SelectControl, TextareaControl, Button, ToggleControl, Notice } from '@wordpress/components';
import { useSelect } from '@wordpress/data';
import { useEffect } from '@wordpress/element';
import ServerSideRender from '@wordpress/server-side-render';

import './editor.scss';

export default function Edit({ attributes, setAttributes }) {
    const {
        logoText,
        menu1Slug,
        menu1Title,
        menu2Slug,
        menu2Title,
        copyrightText,
        footerBgColor,
        textColor,
        headingColor,
        blockId,
        footerStyle,
        bioText,
        logoType,
        logoImageId,
        logoImageUrl,
        footerTitleColor,
        footerTitleHoverColor,
        socialIconColor,
        socialIconHoverColor,
        showCurve,
        curveColor
    } = attributes;

    const menus = useSelect((select) => {
        return select('core').getEntityRecords('root', 'menu', { per_page: -1 });
    }, []);

    const menuOptions = menus ? [
        { label: 'Select a Menu', value: '' },
        ...menus.map((menu) => ({ label: menu.name, value: menu.slug }))
    ] : [{ label: 'Loading...', value: '' }];

    useEffect(() => {
        if (!blockId) {
            setAttributes({ blockId: `footer-${Math.random().toString(36).substr(2, 9)}` });
        }
    }, [blockId]);

    const onSelectLogo = (media) => {
        setAttributes({
            logoImageId: media.id,
            logoImageUrl: media.url,
        });
    };

    const previewStyle = {
        '--awt-footer-bg': footerBgColor,
        '--awt-footer-text': textColor,
        '--awt-heading-color': headingColor,
        '--awt-title-color': footerTitleColor || 'inherit',
        '--awt-title-hover': footerTitleHoverColor || footerTitleColor || 'inherit',
        '--awt-social-color': socialIconColor || textColor,
        '--awt-social-hover': socialIconHoverColor || headingColor,
        '--awt-curve-color': curveColor || '#FFF8E7'
    };

    return (
        <div {...useBlockProps()}>
            <InspectorControls>
                <PanelBody title="Content Settings" initialOpen={true}>

                    <SelectControl
                        label="Layout Style"
                        value={footerStyle}
                        options={[
                            { label: 'Fun (Default)', value: 'fun' },
                            { label: 'Elegant', value: 'elegant' }
                        ]}
                        onChange={(value) => setAttributes({ footerStyle: value })}
                    />

                    <hr style={{ margin: '20px 0' }} />

                    <h3>Logo Settings</h3>
                    <SelectControl
                        label="Logo Type"
                        value={logoType}
                        options={[
                            { label: 'Custom Text', value: 'custom' },
                            { label: 'Site Title', value: 'site_title' },
                            { label: 'Image', value: 'image' }
                        ]}
                        onChange={(value) => setAttributes({ logoType: value })}
                    />

                    {logoType === 'custom' && (
                        <TextControl
                            label="Logo Text"
                            value={logoText}
                            onChange={(value) => setAttributes({ logoText: value })}
                        />
                    )}

                    {logoType === 'image' && (
                        <div className="awt-logo-upload">
                            <MediaUpload
                                onSelect={onSelectLogo}
                                allowedTypes={['image']}
                                value={logoImageId}
                                render={({ open }) => (
                                    <Button variant="secondary" onClick={open}>
                                        {logoImageId ? 'Change Logo' : 'Upload Logo'}
                                    </Button>
                                )}
                            />
                            {logoImageUrl && (
                                <img src={logoImageUrl} alt="Logo Preview" style={{ marginTop: '10px', maxWidth: '100%', height: 'auto' }} />
                            )}
                        </div>
                    )}

                    <hr style={{ margin: '20px 0' }} />

                    <TextareaControl
                        label="Author Bio"
                        value={bioText}
                        onChange={(value) => setAttributes({ bioText: value })}
                        help="Short bio text appearing in the footer."
                    />

                    <hr style={{ margin: '20px 0' }} />

                    {/* Social Media Notice */}
                    <Notice status="info" isDismissible={false}>
                        <p>Social Media links are now managed globally.</p>
                        <p>Go to <strong>Dashboard &gt; Settings &gt; Author Templates &gt; Social Media</strong> tab to configure your icons.</p>
                    </Notice>

                    <hr style={{ margin: '20px 0' }} />

                    <TextControl
                        label="Menu 1 Heading"
                        value={menu1Title}
                        onChange={(value) => setAttributes({ menu1Title: value })}
                    />
                    <SelectControl
                        label="Select Menu 1"
                        value={menu1Slug}
                        options={menuOptions}
                        onChange={(value) => setAttributes({ menu1Slug: value })}
                    />

                    <hr />

                    <TextControl
                        label="Menu 2 Heading"
                        value={menu2Title}
                        onChange={(value) => setAttributes({ menu2Title: value })}
                    />
                    <SelectControl
                        label="Select Menu 2"
                        value={menu2Slug}
                        options={menuOptions}
                        onChange={(value) => setAttributes({ menu2Slug: value })}
                    />
                </PanelBody>

                <PanelBody title="Footer Bottom">
                    <TextControl
                        label="Copyright Text"
                        value={copyrightText}
                        onChange={(value) => setAttributes({ copyrightText: value })}
                        help="Year and Site Title are automatically added."
                    />
                </PanelBody>
            </InspectorControls>

            <InspectorControls group="styles">
                <PanelColorSettings
                    title="Footer Colors"
                    initialOpen={true}
                    colorSettings={[
                        {
                            value: footerBgColor,
                            onChange: (value) => setAttributes({ footerBgColor: value }),
                            label: 'Background Color',
                        },
                        {
                            value: textColor,
                            onChange: (value) => setAttributes({ textColor: value }),
                            label: 'Text Color',
                        },
                        {
                            value: headingColor,
                            onChange: (value) => setAttributes({ headingColor: value }),
                            label: 'Heading Color',
                        },
                        {
                            value: footerTitleColor,
                            onChange: (value) => setAttributes({ footerTitleColor: value }),
                            label: 'Logo/Title Color',
                        },
                        {
                            value: footerTitleHoverColor,
                            onChange: (value) => setAttributes({ footerTitleHoverColor: value }),
                            label: 'Logo Hover Color',
                        },
                        {
                            value: socialIconColor,
                            onChange: (value) => setAttributes({ socialIconColor: value }),
                            label: 'Social Icons Color',
                        },
                        {
                            value: socialIconHoverColor,
                            onChange: (value) => setAttributes({ socialIconHoverColor: value }),
                            label: 'Social Icons Hover Color',
                        },
                        {
                            value: curveColor,
                            onChange: (value) => setAttributes({ curveColor: value }),
                            label: 'Top Curve Color',
                        }
                    ]}
                />
                {footerStyle === 'fun' && (
                    <PanelBody title="Layout Options">
                        <ToggleControl
                            label="Show Top Curve"
                            checked={showCurve}
                            onChange={(value) => setAttributes({ showCurve: value })}
                        />
                    </PanelBody>
                )}
            </InspectorControls>

            {/* Canvas Preview */}
            <div style={previewStyle}>
                <ServerSideRender
                    block="awt/child-author-footer"
                    attributes={attributes}
                />
            </div>
        </div>
    );
}
