import { useBlockProps, RichText, MediaUpload, MediaUploadCheck, InspectorControls, PanelColorSettings } from '@wordpress/block-editor';
import { PanelBody, Button, TextControl, RangeControl, ToggleControl, TextareaControl, SelectControl } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { useEffect } from '@wordpress/element';

export default function Edit({ attributes, setAttributes, clientId }) {
    const {
        title,
        heroStyle,
        description,
        heroImageId,
        heroImageUrl,
        authorImageId,
        authorImageUrl,
        titleColor,
        descColor,
        sectionPadding,
        sectionBgColor,
        hideCurve,
        curveColor,
        btn1Text,
        btn1Url,
        btn1BgColor,
        btn1TextColor,
        btn1HoverBgColor,
        btn1HoverTextColor,
        btn2Text,
        btn2Url,
        btn2BgColor,
        btn2TextColor,
        btn2HoverBgColor,
        btn2HoverTextColor,
        blockId,
    } = attributes;

    // Set blockId if empty
    useEffect(() => {
        if (!blockId) {
            setAttributes({ blockId: clientId });
        }
    }, [blockId, clientId, setAttributes]);

    // Conditional class rendering to avoid !important conflicts
    const isFun = heroStyle === 'fun';
    const isElegant = heroStyle === 'elegant';

    let containerClass = (sectionBgColor || sectionPadding !== null)
        ? 'relative overflow-hidden'
        : 'relative overflow-hidden bg-blue-sky bg-opacity-10 pt-24 pb-32';

    if (isElegant) {
        containerClass = (sectionBgColor || sectionPadding !== null)
            ? 'relative overflow-hidden'
            : 'relative overflow-hidden bg-slate-50 pt-24 pb-32';
    }

    let titleClass = titleColor
        ? 'text-5xl lg:text-7xl font-black mb-6 leading-tight'
        : 'text-5xl lg:text-7xl font-black text-navy mb-6 leading-tight';

    if (isElegant) {
        titleClass = titleColor
            ? 'text-5xl md:text-7xl font-serif font-bold mb-6 leading-tight'
            : 'text-5xl md:text-7xl font-serif font-bold text-slate-800 mb-6 leading-tight';
    }

    let descClass = descColor
        ? 'text-xl mb-10 max-w-lg mx-auto md:mx-0'
        : 'text-xl text-navy/80 mb-10 max-w-lg mx-auto md:mx-0';

    if (isElegant) {
        descClass = descColor
            ? 'text-xl mb-10 max-w-lg mx-auto md:mx-0 font-light leading-relaxed'
            : 'text-xl text-slate-500 mb-10 max-w-lg mx-auto md:mx-0 font-light leading-relaxed';
    }

    let btn1Class = btn1BgColor
        ? 'btn-fun btn-1'
        : 'btn-fun btn-yellow btn-1';

    if (isElegant) {
        btn1Class = btn1BgColor
            ? 'px-8 py-3 rounded font-medium transition-all duration-300 ease-in-out border border-transparent shadow-sm hover:shadow-md btn-1'
            : 'px-8 py-3 rounded font-medium transition-all duration-300 ease-in-out border border-transparent bg-slate-900 text-white shadow-sm hover:shadow-md btn-1';
    }

    let btn2Class = btn2BgColor
        ? 'btn-fun btn-2'
        : 'btn-fun btn-white btn-2';

    if (isElegant) {
        btn2Class = btn2BgColor
            ? 'px-8 py-3 rounded font-medium transition-all duration-300 ease-in-out border border-transparent btn-2'
            : 'px-8 py-3 rounded font-medium transition-all duration-300 ease-in-out border border-current hover:bg-slate-50 btn-2';
    }

    // Dynamic hover styles
    const hoverStyles = `
		.block-${blockId} .btn-1:hover {
			${btn1HoverBgColor ? `background-color: ${btn1HoverBgColor} !important;` : ''}
			${btn1HoverTextColor ? `color: ${btn1HoverTextColor} !important;` : ''}
		}
		.block-${blockId} .btn-2:hover {
			${btn2HoverBgColor ? `background-color: ${btn2HoverBgColor} !important;` : ''}
			${btn2HoverTextColor ? `color: ${btn2HoverTextColor} !important;` : ''}
		}
	`;

    const blockProps = useBlockProps({
        className: `${containerClass} block-${blockId}`,
        style: {
            backgroundColor: sectionBgColor || (isElegant ? '#f8fafc' : undefined),
            paddingTop: sectionPadding !== null ? `${sectionPadding}px` : undefined,
            paddingBottom: sectionPadding !== null ? `${sectionPadding}px` : undefined,
        }
    });

    const onSelectHeroImage = (media) => {
        setAttributes({
            heroImageId: media.id,
            heroImageUrl: media.url,
        });
    };

    const onSelectAuthorImage = (media) => {
        setAttributes({
            authorImageId: media.id,
            authorImageUrl: media.url,
        });
    };

    return (
        <>
            <InspectorControls>
                <PanelBody title={__('Content Settings', 'author-website-templates')} initialOpen={true}>
                    <SelectControl
                        label={__('Hero Style', 'author-website-templates')}
                        value={heroStyle}
                        options={[
                            { label: __('Fun (Child)', 'author-website-templates'), value: 'fun' },
                            { label: __('Elegant (Author)', 'author-website-templates'), value: 'elegant' },
                        ]}
                        onChange={(value) => setAttributes({ heroStyle: value })}
                        help={__('Switch between the playful child theme and the elegant author portfolio style.', 'author-website-templates')}
                    />
                    <hr style={{ margin: '16px 0' }} />

                    {/* Hero Image Upload */}
                    <div className="sidebar-image-control" style={{ marginBottom: '16px' }}>
                        <p style={{ marginBottom: '8px', fontWeight: 'bold' }}>{__('Hero Image', 'author-website-templates')}</p>
                        <MediaUploadCheck>
                            <MediaUpload
                                onSelect={onSelectHeroImage}
                                allowedTypes={['image']}
                                value={heroImageId}
                                render={({ open }) => (
                                    <>
                                        {heroImageUrl ? (
                                            <>
                                                <img src={heroImageUrl} alt="Hero Preview" style={{ width: '100%', height: 'auto', marginBottom: '10px', borderRadius: '8px' }} />
                                                <Button variant="secondary" onClick={open} style={{ width: '100%', marginBottom: '8px' }}>
                                                    {__('Replace Image', 'author-website-templates')}
                                                </Button>
                                                <Button variant="link" isDestructive onClick={() => setAttributes({ heroImageId: 0, heroImageUrl: '' })}>
                                                    {__('Remove', 'author-website-templates')}
                                                </Button>
                                            </>
                                        ) : (
                                            <Button variant="primary" onClick={open} style={{ width: '100%' }}>
                                                {__('Upload Image', 'author-website-templates')}
                                            </Button>
                                        )}
                                    </>
                                )}
                            />
                        </MediaUploadCheck>
                    </div>

                    {/* Author Image Upload */}
                    <div className="sidebar-image-control" style={{ marginBottom: '16px' }}>
                        <p style={{ marginBottom: '8px', fontWeight: 'bold' }}>{__('Author Image', 'author-website-templates')}</p>
                        <MediaUploadCheck>
                            <MediaUpload
                                onSelect={onSelectAuthorImage}
                                allowedTypes={['image']}
                                value={authorImageId}
                                render={({ open }) => (
                                    <>
                                        {authorImageUrl ? (
                                            <>
                                                <img src={authorImageUrl} alt="Author Preview" style={{ width: '100%', height: 'auto', marginBottom: '10px', borderRadius: '8px' }} />
                                                <Button variant="secondary" onClick={open} style={{ width: '100%', marginBottom: '8px' }}>
                                                    {__('Replace Image', 'author-website-templates')}
                                                </Button>
                                                <Button variant="link" isDestructive onClick={() => setAttributes({ authorImageId: 0, authorImageUrl: '' })}>
                                                    {__('Remove', 'author-website-templates')}
                                                </Button>
                                            </>
                                        ) : (
                                            <Button variant="primary" onClick={open} style={{ width: '100%' }}>
                                                {__('Upload Image', 'author-website-templates')}
                                            </Button>
                                        )}
                                    </>
                                )}
                            />
                        </MediaUploadCheck>
                    </div>

                    {/* Text Content Controls */}
                    <TextareaControl
                        label={__('Title', 'author-website-templates')}
                        value={title}
                        onChange={(value) => setAttributes({ title: value })}
                        rows={3}
                        help={__('You can also edit directly on the canvas', 'author-website-templates')}
                    />

                    <TextareaControl
                        label={__('Description', 'author-website-templates')}
                        value={description}
                        onChange={(value) => setAttributes({ description: value })}
                        rows={4}
                        help={__('You can also edit directly on the canvas', 'author-website-templates')}
                    />

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

                    <h4 style={{ marginBottom: '12px', fontWeight: 'bold' }}>{__('Button 1', 'author-website-templates')}</h4>
                    <TextControl
                        label={__('Button 1 Text', 'author-website-templates')}
                        value={btn1Text}
                        onChange={(value) => setAttributes({ btn1Text: value })}
                    />
                    <TextControl
                        label={__('Button 1 URL', 'author-website-templates')}
                        value={btn1Url}
                        onChange={(value) => setAttributes({ btn1Url: value })}
                        placeholder="#featured-book"
                    />

                    <h4 style={{ marginTop: '16px', marginBottom: '12px', fontWeight: 'bold' }}>{__('Button 2', 'author-website-templates')}</h4>
                    <TextControl
                        label={__('Button 2 Text', 'author-website-templates')}
                        value={btn2Text}
                        onChange={(value) => setAttributes({ btn2Text: value })}
                    />
                    <TextControl
                        label={__('Button 2 URL', 'author-website-templates')}
                        value={btn2Url}
                        onChange={(value) => setAttributes({ btn2Url: value })}
                        placeholder="#activities"
                    />
                </PanelBody>

                <PanelBody title={__('Color Settings', 'author-website-templates')} initialOpen={false}>
                    <PanelColorSettings
                        title={__('Section Colors', 'author-website-templates')}
                        colorSettings={[
                            {
                                value: sectionBgColor,
                                onChange: (color) => setAttributes({ sectionBgColor: color }),
                                label: __('Section Background', 'author-website-templates'),
                            },
                            {
                                value: titleColor,
                                onChange: (color) => setAttributes({ titleColor: color }),
                                label: __('Title Color', 'author-website-templates'),
                            },
                            {
                                value: descColor,
                                onChange: (color) => setAttributes({ descColor: color }),
                                label: __('Description Color', 'author-website-templates'),
                            },
                            {
                                value: curveColor,
                                onChange: (color) => setAttributes({ curveColor: color }),
                                label: __('Curve Color', 'author-website-templates'),
                            },
                        ]}
                    />
                </PanelBody>

                <PanelBody title={__('Spacing & Layout', 'author-website-templates')} initialOpen={false}>
                    <RangeControl
                        label={__('Section Padding (px)', 'author-website-templates')}
                        value={sectionPadding !== null ? sectionPadding : 96}
                        onChange={(value) => setAttributes({ sectionPadding: value })}
                        min={0}
                        max={200}
                        step={8}
                        help={__('Default: 96px (pt-24 pb-32)', 'author-website-templates')}
                    />

                    <ToggleControl
                        label={__('Hide Curve Divider', 'author-website-templates')}
                        checked={hideCurve}
                        onChange={(value) => setAttributes({ hideCurve: value })}
                    />
                </PanelBody>

                <PanelBody title={__('Button 1 Settings', 'author-website-templates')} initialOpen={false}>
                    <TextControl
                        label={__('Button URL', 'author-website-templates')}
                        value={btn1Url}
                        onChange={(value) => setAttributes({ btn1Url: value })}
                        placeholder="#featured-book"
                    />
                    <PanelColorSettings
                        title={__('Button 1 Colors', 'author-website-templates')}
                        colorSettings={[
                            {
                                value: btn1BgColor,
                                onChange: (color) => setAttributes({ btn1BgColor: color }),
                                label: __('Background', 'author-website-templates'),
                            },
                            {
                                value: btn1TextColor,
                                onChange: (color) => setAttributes({ btn1TextColor: color }),
                                label: __('Text Color', 'author-website-templates'),
                            },
                            {
                                value: btn1HoverBgColor,
                                onChange: (color) => setAttributes({ btn1HoverBgColor: color }),
                                label: __('Hover Background', 'author-website-templates'),
                            },
                            {
                                value: btn1HoverTextColor,
                                onChange: (color) => setAttributes({ btn1HoverTextColor: color }),
                                label: __('Hover Text', 'author-website-templates'),
                            },
                        ]}
                    />
                </PanelBody>

                <PanelBody title={__('Button 2 Settings', 'author-website-templates')} initialOpen={false}>
                    <TextControl
                        label={__('Button URL', 'author-website-templates')}
                        value={btn2Url}
                        onChange={(value) => setAttributes({ btn2Url: value })}
                        placeholder="#activities"
                    />
                    <PanelColorSettings
                        title={__('Button 2 Colors', 'author-website-templates')}
                        colorSettings={[
                            {
                                value: btn2BgColor,
                                onChange: (color) => setAttributes({ btn2BgColor: color }),
                                label: __('Background', 'author-website-templates'),
                            },
                            {
                                value: btn2TextColor,
                                onChange: (color) => setAttributes({ btn2TextColor: color }),
                                label: __('Text Color', 'author-website-templates'),
                            },
                            {
                                value: btn2HoverBgColor,
                                onChange: (color) => setAttributes({ btn2HoverBgColor: color }),
                                label: __('Hover Background', 'author-website-templates'),
                            },
                            {
                                value: btn2HoverTextColor,
                                onChange: (color) => setAttributes({ btn2HoverTextColor: color }),
                                label: __('Hover Text', 'author-website-templates'),
                            },
                        ]}
                    />
                </PanelBody>
            </InspectorControls>

            <section {...blockProps}>
                {/* Dynamic Hover Styles */}
                <style>{hoverStyles}</style>

                {/* SVG Wave Divider - Conditional (Fun Mode Only) */}
                {(!hideCurve && isFun) && (
                    <div className="absolute bottom-0 left-0 w-full pointer-events-none">
                        <svg viewBox="0 0 1440 100" fill="none" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none" className="w-full h-auto">
                            <path d="M0 100H1440V0C1192.5 49.497 919.5 74.497 720 74.497C520.5 74.497 247.5 49.497 0 0V100Z" fill={curveColor} />
                        </svg>
                    </div>
                )}

                <div className="awt-container mx-auto px-6 grid md:grid-cols-2 gap-8 md:items-left relative z-10">
                    {/* Left Column - Text Content */}
                    <div className="text-center md:text-left">
                        <RichText
                            tagName="h1"
                            className={titleClass}
                            value={title}
                            onChange={(value) => setAttributes({ title: value })}
                            placeholder={__('Enter hero title...', 'author-website-templates')}
                            style={{ color: titleColor || (isElegant ? '#1e293b' : undefined) }}
                        />

                        <RichText
                            tagName="p"
                            className={descClass}
                            value={description}
                            onChange={(value) => setAttributes({ description: value })}
                            placeholder={__('Enter hero description...', 'author-website-templates')}
                            style={{ color: descColor || (isElegant ? '#64748b' : undefined) }}
                        />

                        <div className="flex flex-col sm:flex-row md:space-y-3 lg:space-y-0 flex-wrap md:items-left md:flex-col lg:flex-row gap-4 justify-center md:justify-start">
                            <div className="btn-wrapper md:mb-4 lg:mb-0">
                                <RichText
                                    tagName="span"
                                    value={btn1Text}
                                    onChange={(value) => setAttributes({ btn1Text: value })}
                                    placeholder={__('Button 1 text...', 'author-website-templates')}
                                    className={btn1Class}
                                    style={{
                                        backgroundColor: btn1BgColor || (isElegant ? '#0f172a' : undefined),
                                        color: btn1TextColor || (isElegant ? '#ffffff' : undefined),
                                    }}
                                />
                            </div>
                            <div className="btn-wrapper">
                                <RichText
                                    tagName="span"
                                    value={btn2Text}
                                    onChange={(value) => setAttributes({ btn2Text: value })}
                                    placeholder={__('Button 2 text...', 'author-website-templates')}
                                    className={btn2Class}
                                    style={{
                                        backgroundColor: btn2BgColor || undefined,
                                        color: btn2TextColor || (isElegant ? '#0f172a' : undefined),
                                        borderColor: (!btn2BgColor && isElegant) ? '#0f172a' : undefined
                                    }}
                                />
                            </div>
                        </div>
                    </div>

                    {/* Right Column - Images */}
                    <div className="flex items-center justify-center">
                        <div className="relative">
                            {/* Main Hero Image */}
                            <MediaUpload
                                onSelect={onSelectHeroImage}
                                allowedTypes={['image']}
                                value={heroImageId}
                                render={({ open }) => {
                                    if (isElegant) {
                                        return (
                                            <div className="relative w-full max-w-md" onClick={open} style={{ cursor: 'pointer' }}>
                                                <div className="absolute inset-0 transform translate-x-4 translate-y-4 z-0 rounded-lg" style={{ backgroundColor: 'rgba(15, 23, 42, 0.1)' }}></div>
                                                <figure className="relative z-10 w-full aspect-[4/5] bg-gray-200 rounded-lg overflow-hidden shadow-xl">
                                                    {heroImageUrl ? (
                                                        <img src={heroImageUrl} alt="Hero" className="w-full h-full object-cover" />
                                                    ) : (
                                                        <div className="w-full h-full flex items-center justify-center text-gray-400">
                                                            <span>{__('Select Image', 'author-website-templates')}</span>
                                                        </div>
                                                    )}
                                                </figure>
                                            </div>
                                        );
                                    }
                                    return (
                                        <figure className="rounded-lg shadow-xl w-full max-w-lg transform rotate-2 cursor-pointer" onClick={open}>
                                            {heroImageUrl ? (
                                                <img src={heroImageUrl} alt="Hero character illustration" />
                                            ) : (
                                                <div className="bg-gray-200 aspect-[3/2] flex items-center justify-center">
                                                    <Button variant="primary" onClick={open}>
                                                        {__('Upload Hero Image', 'author-website-templates')}
                                                    </Button>
                                                </div>
                                            )}
                                        </figure>
                                    );
                                }}
                            />

                            {/* Author Circle Image (Fun Mode Only) */}
                            {isFun && (
                                <MediaUpload
                                    onSelect={onSelectAuthorImage}
                                    allowedTypes={['image']}
                                    value={authorImageId}
                                    render={({ open }) => (
                                        <figure className="absolute -bottom-12 -right-12 w-32 h-32 md:w-40 md:h-40 rounded-full border-8 border-white shadow-2xl transform -rotate-6 cursor-pointer overflow-hidden" onClick={open}>
                                            {authorImageUrl ? (
                                                <img src={authorImageUrl} alt="Author photo" className="w-full h-full object-cover" />
                                            ) : (
                                                <div className="bg-gray-300 w-full h-full flex items-center justify-center">
                                                    <Button variant="primary" onClick={open} className="text-xs">
                                                        {__('Author', 'author-website-templates')}
                                                    </Button>
                                                </div>
                                            )}
                                        </figure>
                                    )}
                                />
                            )}
                        </div>
                    </div>
                </div>
            </section>
        </>
    );
}
