/**
 * Retrieves the translation of text.
 *
 * @see https://developer.wordpress.org/block-editor/packages/packages-i18n/
 */
import { __ } from '@wordpress/i18n';

/**
 * React hook that is used to mark the block wrapper element.
 * It provides all the necessary props like the class name.
 *
 * @see https://developer.wordpress.org/block-editor/packages/packages-block-editor/
 */
import {
    useBlockProps,
    InspectorControls,
    PanelColorSettings,
    MediaUpload,
    MediaUploadCheck,
} from '@wordpress/block-editor';

/**
 * WordPress dependencies
 */
import {
    PanelBody,
    TextControl,
    TextareaControl,
    Button,
    SelectControl,
} from '@wordpress/components';

import ServerSideRender from '@wordpress/server-side-render';
import { useSelect } from '@wordpress/data';
import { useEffect } from '@wordpress/element';

/**
 * Lets webpack process CSS, SASS or SCSS files referenced in JavaScript files.
 * Those files can contain any CSS code that gets applied to the editor.
 *
 * @see https://www.npmjs.com/package/@wordpress/scripts#using-css
 */
/* import './editor.scss'; */

/**
 * The edit function describes the structure of your block in the context of the
 * editor. This represents what the editor will render when the block is used.
 *
 * @see https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#edit
 *
 * @return {Element} Element to render.
 */
export default function Edit({ attributes, setAttributes }) {
    const {
        blockId,
        anchor,
        logoType,
        logoText,
        logoImageId,
        logoImageUrl,
        description,
        socialLinks,
        menu2Slug,
        menu3Slug,
        bottomMenuSlug,
        col2Title,
        col3Title,
        col4Title,
        contactDetails,
        copyrightText,
        footerBgColor,
        textColor,
        headingColor,
        accentColor,
        borderColor,
    } = attributes;

    // Fix: Use useEffect to set blockId on mount only
    useEffect(() => {
        if (!blockId) {
            setAttributes({ blockId: 'awt-footer-' + Math.floor(Math.random() * 10000) });
        }
    }, [blockId]);

    // Fetch Menus
    const menus = useSelect((select) => {
        return select('core').getEntityRecords('taxonomy', 'nav_menu', { per_page: -1 });
    }, []);

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

    // --- Social Links Logic ---
    const onChangeSocialLink = (index, key, value) => {
        const newSocialLinks = [...socialLinks];
        newSocialLinks[index][key] = value;
        setAttributes({ socialLinks: newSocialLinks });
    };

    const addSocialLink = () => {
        setAttributes({ socialLinks: [...socialLinks, { icon: 'facebook-f', url: '#', iconId: 0, iconUrl: '', svgContent: '' }] });
    };
    const removeSocialLink = (index) => {
        const newSocialLinks = [...socialLinks];
        newSocialLinks.splice(index, 1);
        setAttributes({ socialLinks: newSocialLinks });
    };


    // --- Contact Details Logic ---
    const onChangeContactDetail = (index, key, value) => {
        const newContactDetails = [...contactDetails];
        newContactDetails[index][key] = value;
        setAttributes({ contactDetails: newContactDetails });
    };

    const addContactDetail = () => {
        setAttributes({
            contactDetails: [...contactDetails, { icon: 'star', text: 'New Detail', url: '#', iconId: 0, iconUrl: '', svgContent: '' }],
        });
    };

    const removeContactDetail = (index) => {
        const newContactDetails = [...contactDetails];
        newContactDetails.splice(index, 1);
        setAttributes({ contactDetails: newContactDetails });
    };


    const blockProps = useBlockProps({
        id: anchor ? undefined : blockId
    });

    // Create inline styles object conditionally
    const inlineStyles = {};
    if (footerBgColor) {
        inlineStyles['--awt-footer-bg'] = footerBgColor;
    }
    if (textColor) {
        inlineStyles['--awt-text-color'] = textColor;
    }
    if (headingColor) {
        inlineStyles['--awt-heading-color'] = headingColor;
    }
    if (accentColor) {
        inlineStyles['--awt-accent-color'] = accentColor;
    }
    if (borderColor) {
        inlineStyles['--awt-border-color'] = borderColor;
    }

    return (
        <div {...blockProps}>
            { /* Editor Styles Wrapper */}
            <div style={inlineStyles}>
                <InspectorControls>
                    <PanelBody title={__('Logo Settings', 'author-website-templates')}>
                        <SelectControl
                            label={__('Logo Type', 'author-website-templates')}
                            value={logoType}
                            options={[
                                { label: 'Custom Text', value: 'custom' },
                                { label: 'Site Title', value: 'site_title' },
                                { label: 'Custom Image', value: 'image' },
                            ]}
                            onChange={(value) => setAttributes({ logoType: value })}
                        />
                        {logoType === 'custom' && (
                            <TextControl
                                label={__('Logo Text', 'author-website-templates')}
                                value={logoText}
                                onChange={(value) => setAttributes({ logoText: value })}
                            />
                        )}
                        {logoType === 'image' && (
                            <MediaUploadCheck>
                                <MediaUpload
                                    onSelect={(media) => setAttributes({ logoImageId: media.id, logoImageUrl: media.url })}
                                    allowedTypes={['image']}
                                    value={logoImageId}
                                    render={({ open }) => (
                                        <Button isPrimary onClick={open}>
                                            {logoImageUrl ? __('Replace Logo', 'author-website-templates') : __('Upload Logo', 'author-website-templates')}
                                        </Button>
                                    )}
                                />
                            </MediaUploadCheck>
                        )}
                    </PanelBody>

                    <PanelBody title={__('Content Settings', 'author-website-templates')}>
                        <TextareaControl
                            label={__('Description', 'author-website-templates')}
                            value={description}
                            onChange={(value) => setAttributes({ description: value })}
                        />
                        <TextControl
                            label={__('Copyright Text', 'author-website-templates')}
                            value={copyrightText}
                            onChange={(value) => setAttributes({ copyrightText: value })}
                        />
                        <hr />
                        <TextControl
                            label={__('Column 2 Title', 'author-website-templates')}
                            value={col2Title}
                            onChange={(value) => setAttributes({ col2Title: value })}
                        />
                        <SelectControl
                            label={__('Quick Links Menu', 'author-website-templates')}
                            value={menu2Slug}
                            options={menuOptions}
                            onChange={(value) => setAttributes({ menu2Slug: value })}
                        />
                        <hr />
                        <TextControl
                            label={__('Column 3 Title', 'author-website-templates')}
                            value={col3Title}
                            onChange={(value) => setAttributes({ col3Title: value })}
                        />
                        <SelectControl
                            label={__('Resources Menu', 'author-website-templates')}
                            value={menu3Slug}
                            options={menuOptions}
                            onChange={(value) => setAttributes({ menu3Slug: value })}
                        />
                        <hr />
                        <TextControl
                            label={__('Column 4 Title', 'author-website-templates')}
                            value={col4Title}
                            onChange={(value) => setAttributes({ col4Title: value })}
                        />
                        <SelectControl
                            label={__('Bottom Menu', 'author-website-templates')}
                            value={bottomMenuSlug}
                            options={menuOptions}
                            onChange={(value) => setAttributes({ bottomMenuSlug: value })}
                        />
                    </PanelBody>

                    <PanelBody title={__('Contact Info', 'author-website-templates')} initialOpen={false}>
                        {contactDetails.map((detail, index) => (
                            <div key={index} style={{ marginBottom: '20px', borderBottom: '1px solid #ccc', paddingBottom: '10px' }}>
                                <p className="mb-2"><strong>Contact Item #{index + 1}</strong></p>
                                <div className="mb-2">
                                    <label className="block text-xs font-bold text-gray-700 uppercase mb-1">Icon (Media or SVG)</label>
                                    <div className="flex gap-2 items-center flex-wrap">
                                        { /* Media Upload Preview */}
                                        {detail.iconUrl && (
                                            <div className="relative">
                                                <img src={detail.iconUrl} alt="Icon" className="w-8 h-8 object-contain bg-gray-100 rounded border border-gray-300" />
                                                <Button icon="no-alt" isDestructive isSmall className="absolute -top-2 -right-2 rounded-full p-0 min-w-[20px] h-[20px] flex items-center justify-center" onClick={() => {
                                                    onChangeContactDetail(index, 'iconId', 0);
                                                    onChangeContactDetail(index, 'iconUrl', '');
                                                }} />
                                            </div>
                                        )}

                                        { /* SVG Preview */}
                                        {!detail.iconUrl && detail.svgContent && (
                                            <div className="w-8 h-8 flex items-center justify-center bg-gray-100 rounded border border-gray-300 text-gray-800" dangerouslySetInnerHTML={{ __html: detail.svgContent }}></div>
                                        )}

                                        <MediaUploadCheck>
                                            <MediaUpload
                                                onSelect={(media) => {
                                                    onChangeContactDetail(index, 'iconId', media.id);
                                                    onChangeContactDetail(index, 'iconUrl', media.url);
                                                }}
                                                allowedTypes={['image']}
                                                value={detail.iconId}
                                                render={({ open }) => (
                                                    <Button isSecondary isSmall onClick={open}>
                                                        {detail.iconUrl ? 'Replace Image' : 'Upload Image'}
                                                    </Button>
                                                )}
                                            />
                                        </MediaUploadCheck>
                                    </div>
                                    <div className="mt-2">
                                        <TextareaControl
                                            label="SVG Code (Fallback if no image)"
                                            value={detail.svgContent || ''}
                                            onChange={(value) => onChangeContactDetail(index, 'svgContent', value)}
                                            rows={3}
                                            help="Paste raw SVG code here (starting with <svg...>)."
                                        />
                                    </div>
                                </div>
                                <TextControl
                                    label="Text (supports HTML)"
                                    value={detail.text}
                                    onChange={(value) => onChangeContactDetail(index, 'text', value)}
                                />
                                <Button isDestructive isSmall onClick={() => removeContactDetail(index)}>
                                    Remove Item
                                </Button>
                            </div>
                        ))}
                        <Button isSecondary onClick={addContactDetail}>
                            Add Contact Detail
                        </Button>
                    </PanelBody>

                    <PanelBody title={__('Social Links', 'author-website-templates')} initialOpen={false}>
                        {socialLinks.map((link, index) => (
                            <div key={index} style={{ marginBottom: '20px', borderBottom: '1px solid #ccc', paddingBottom: '10px' }}>
                                <p className="mb-2"><strong>Social Link #{index + 1}</strong></p>
                                <div className="mb-2">
                                    <label className="block text-xs font-bold text-gray-700 uppercase mb-1">Icon (Media or SVG)</label>
                                    <div className="flex gap-2 items-center flex-wrap">
                                        { /* Media Upload Preview */}
                                        {link.iconUrl && (
                                            <div className="relative">
                                                <img src={link.iconUrl} alt="Icon" className="w-8 h-8 object-contain bg-gray-100 rounded border border-gray-300" />
                                                <Button icon="no-alt" isDestructive isSmall className="absolute -top-2 -right-2 rounded-full p-0 min-w-[20px] h-[20px] flex items-center justify-center" onClick={() => {
                                                    onChangeSocialLink(index, 'iconId', 0);
                                                    onChangeSocialLink(index, 'iconUrl', '');
                                                }} />
                                            </div>
                                        )}

                                        { /* SVG Preview */}
                                        {!link.iconUrl && link.svgContent && (
                                            <div className="w-8 h-8 flex items-center justify-center bg-gray-100 rounded border border-gray-300 text-gray-800" dangerouslySetInnerHTML={{ __html: link.svgContent }}></div>
                                        )}

                                        <MediaUploadCheck>
                                            <MediaUpload
                                                onSelect={(media) => {
                                                    onChangeSocialLink(index, 'iconId', media.id);
                                                    onChangeSocialLink(index, 'iconUrl', media.url);
                                                }}
                                                allowedTypes={['image']}
                                                value={link.iconId}
                                                render={({ open }) => (
                                                    <Button isSecondary isSmall onClick={open}>
                                                        {link.iconUrl ? 'Replace Image' : 'Upload Image'}
                                                    </Button>
                                                )}
                                            />
                                        </MediaUploadCheck>
                                    </div>
                                    <div className="mt-2">
                                        <TextareaControl
                                            label="SVG Code (Fallback if no image)"
                                            value={link.svgContent || ''}
                                            onChange={(value) => onChangeSocialLink(index, 'svgContent', value)}
                                            rows={3}
                                            help="Paste raw SVG code here (starting with <svg...>)."
                                        />
                                    </div>
                                </div>
                                <TextControl
                                    label="URL"
                                    value={link.url}
                                    onChange={(value) => onChangeSocialLink(index, 'url', value)}
                                />
                                <Button isDestructive isSmall onClick={() => removeSocialLink(index)}>
                                    Remove Link
                                </Button>
                            </div>
                        ))}
                        <Button isSecondary onClick={addSocialLink}>
                            Add Social Link
                        </Button>
                    </PanelBody>

                    <PanelColorSettings
                        title={__('Color Settings', 'author-website-templates')}
                        colorSettings={[
                            {
                                value: footerBgColor,
                                onChange: (value) => setAttributes({ footerBgColor: value }),
                                label: __('Background Color', 'author-website-templates'),
                            },
                            {
                                value: textColor,
                                onChange: (value) => setAttributes({ textColor: value }),
                                label: __('Text Color', 'author-website-templates'),
                            },
                            {
                                value: headingColor,
                                onChange: (value) => setAttributes({ headingColor: value }),
                                label: __('Heading Color', 'author-website-templates'),
                            },
                            {
                                value: accentColor,
                                onChange: (value) => setAttributes({ accentColor: value }),
                                label: __('Accent Color', 'author-website-templates'),
                            },
                            {
                                value: borderColor,
                                onChange: (value) => setAttributes({ borderColor: value }),
                                label: __('Border Color', 'author-website-templates'),
                            },
                        ]}
                    />
                </InspectorControls>

                <ServerSideRender
                    block="awt/author-pro-footer"
                    attributes={attributes}
                />
            </div>
        </div>
    );
}
