import './style.css';
import {
    InspectorControls,
    MediaUpload,
    MediaUploadCheck,
    useBlockProps
} from '@wordpress/block-editor';
import {
    PanelBody,
    TextControl,
    RangeControl,
    SelectControl,
    Button,
    Spinner,
    ToggleControl
} from '@wordpress/components';
import { useState, useEffect } from '@wordpress/element';
import { EZHP_NUMEROLOGY_I18N, isRtlLanguage } from './i18n';

export default function Edit({ attributes, setAttributes }) {

    const {
        language = 'en',
        heroImageUrl = '',
        heroImageAlt = '',
        heroImageDisplayMode = 'inline',
        heroImageOverlayOpacity = 50,
        heroImageOverlayColor = 'black',
    } = attributes;

    // Translation object
    const t = EZHP_NUMEROLOGY_I18N[language] || EZHP_NUMEROLOGY_I18N.en;

    // RTL detection
    const isRtl = isRtlLanguage(language);

    // EDITOR-ONLY STATES
    const [loading, setLoading] = useState(false);
    const [previewHtml, setPreviewHtml] = useState('');
    const [editorFullName, setEditorFullName] = useState('');
    const [editorBirthDate, setEditorBirthDate] = useState('');
    const [rawHtml, setRawHtml] = useState('');

    // Build hero when raw HTML or hero attributes change
    useEffect(() => {
        if (!rawHtml) return;
        const finalHtml = buildHero(
            rawHtml,
            attributes,
            editorFullName,
            editorBirthDate,
            isRtl
        );
        setPreviewHtml(finalHtml);
    }, [
        rawHtml,
        editorFullName,
        editorBirthDate,
        attributes.heroImageUrl,
        attributes.heroImageAlt,
        attributes.heroImageDisplayMode,
        attributes.heroImageTextWrap,
        attributes.heroImageAlignment,
        attributes.heroImageOverlayOpacity,
        attributes.heroImageOverlayColor,
        attributes.heroImageMaxWidth,
        isRtl
    ]);

    const blockProps = useBlockProps({
        className: `ez-horoscope-block${isRtl ? ' is-rtl' : ''}`,
        style: { border: '1px solid #ddd', padding: '10px', borderRadius: '6px' },
        dir: isRtl ? 'rtl' : 'ltr',
    });

    // Build Hero Section
    function buildHero(raw, attributes, fullName, birthDate, isRtl = false) {
        if (!raw) return '';

        // Parse HTML
        const parser = new DOMParser();
        const doc = parser.parseFromString(raw, 'text/html');

        let section =
            doc.querySelector('section.numerology-report') ||
            doc.querySelector('.numerology-report') ||
            doc.querySelector('section');

        if (!section) {
            section = document.createElement('section');
            section.className = 'numerology-report';
            section.innerHTML = raw;
        }

        const bodyHtml = section.innerHTML;

        // Hero title
        const heroTitle = `
            <h2 class="numerology-title">
    ${t.report_for} ${fullName} (${birthDate})
</h2>
        `;

        const heroPieces = [];
        if (!attributes.hideHeading) heroPieces.push(heroTitle);

        // Base hero wrapper
        let heroHTML = `
            <section class="ez-hero">
                <div class="ez-hero-content">
                    <div class="ez-hero-text">
                        ${heroPieces.join("")}
                    </div>
                </div>
            </section>
        `;

        const mode = attributes.heroImageDisplayMode;
        const heroUrl = attributes.heroImageUrl;
        const heroAlt = attributes.heroImageAlt;

        // INLINE MODE
        if (mode === 'inline' && heroUrl) {
            const wrap = attributes.heroImageTextWrap || 'none';
            const maxWidth = attributes.heroImageMaxWidth || '40%';

            // Flip float directions for RTL
            let floatCSS;
            if (wrap === 'left') {
                floatCSS = isRtl
                    ? 'float:right;margin:0 0 1rem 1rem;'
                    : 'float:left;margin:0 1rem 1rem 0;';
            } else if (wrap === 'right') {
                floatCSS = isRtl
                    ? 'float:left;margin:0 1rem 1rem 0;'
                    : 'float:right;margin:0 0 1rem 1rem;';
            } else {
                floatCSS = 'display:block;margin:0 auto 1rem auto;';
            }

            const inlineImg = `
                <div class="ez-daily-inline-image" style="max-width:${maxWidth};position:relative;">
                    <img src="${heroUrl}" alt="${heroAlt}" style="${floatCSS}border-radius:8px;max-width:100%;">
                </div>
            `;

            heroHTML = heroHTML.replace(
                '<div class="ez-hero-text">',
                `<div class="ez-hero-text">${inlineImg}`
            );
        }

        // BACKGROUND MODE
        if (mode === 'background' && heroUrl) {

            const align = attributes.heroImageAlignment || 'center';

            heroHTML = heroHTML.replace(
                '<section class="ez-hero">',
                `<section class="ez-hero" style="background-image:url('${heroUrl}');background-size:cover;background-repeat:no-repeat;background-position:${align};min-height:300px;position:relative;display:flex;flex-direction:column;">`
            );

            const opacity = parseFloat(attributes.heroImageOverlayOpacity || 50) / 100;
            const color = (attributes.heroImageOverlayColor === 'white') ? '255,255,255' : '0,0,0';

            const overlay = `
                <div class="ez-hero-overlay" style="position:absolute;inset:0;background-color:rgba(${color},${opacity});pointer-events:none;border-radius:0;"></div>
            `;

            heroHTML = heroHTML.replace(
                '<div class="ez-hero-content">',
                overlay + '<div class="ez-hero-content">'
            );
        }

        return `
            <section class="numerology-report">
                ${heroHTML}
                ${bodyHtml}
            </section>
        `;
    }

    // Fetch numerology preview (Editor only)
    async function fetchNumerology() {
        if (!editorFullName || !editorBirthDate) return;

        setLoading(true);

        try {
            const response = await wp.apiFetch({
                path: `ezhp/v1/numerology?fullName=${encodeURIComponent(editorFullName)}&birthDate=${encodeURIComponent(editorBirthDate)}&language=${encodeURIComponent(language)}`
            });

            const html = response?.html || '<div>Unable to load numerology report.</div>';

            setRawHtml(html);

        } catch (e) {
            const loader = document.querySelector('.ezhp-progress-container');
            if (loader) loader.remove();

            setRawHtml('<div>Error loading numerology report.</div>');
        }

        const loader = document.querySelector('.ezhp-progress-container');
        if (loader) loader.remove();

        setLoading(false);
    }

    return (
        <>
            {/* Sidebar Controls */}
            <InspectorControls>
                <PanelBody title="Numerology Settings" initialOpen={true}>

                    <TextControl
                        label={t.full_name}
                        value={editorFullName}
                        onChange={(value) => setEditorFullName(value)}
                    />

                    <label style={{ marginBottom: '6px', display: 'block', fontWeight: 600 }}>
                        {t.birthdate}
                    </label>

                    <input
                        type="date"
                        value={editorBirthDate}
                        onChange={(e) => setEditorBirthDate(e.target.value)}
                        style={{
                            width: '100%',
                            padding: '6px',
                            borderRadius: '4px',
                            border: '1px solid #ccc'
                        }}
                    />

                    <TextControl
                        label="Language"
                        value={language}
                        onChange={(value) => setAttributes({ language: value })}
                        style={{ marginTop: '12px' }}
                    />

                    <ToggleControl
                        label="Hide Heading"
                        checked={attributes.hideHeading}
                        onChange={(value) => setAttributes({ hideHeading: value })}
                    />

                </PanelBody>

                {/* Hero Image Settings */}
                <PanelBody title="Hero Image" initialOpen={false}>

                    <MediaUploadCheck>
                        <MediaUpload
                            onSelect={(media) =>
                                setAttributes({
                                    heroImageUrl: media.url,
                                    heroImageAlt: media.alt || '',
                                })
                            }
                            allowedTypes={['image']}
                            render={({ open }) => (
                                heroImageUrl ? (
                                    <>
                                        <img
                                            src={heroImageUrl}
                                            alt={heroImageAlt}
                                            style={{ maxWidth: '100%', marginBottom: '5px' }}
                                        />
                                        <Button
                                            isDestructive
                                            variant="secondary"
                                            onClick={() =>
                                                setAttributes({ heroImageUrl: '', heroImageAlt: '' })
                                            }
                                        >
                                            Remove Image
                                        </Button>
                                    </>
                                ) : (
                                    <Button variant="primary" onClick={open}>
                                        Select Image
                                    </Button>
                                )
                            )}
                        />
                    </MediaUploadCheck>

                    <SelectControl
                        label="Display Mode"
                        value={attributes.heroImageDisplayMode}
                        options={[
                            { label: 'Inline', value: 'inline' },
                        ]}
                        onChange={(value) => setAttributes({ heroImageDisplayMode: value })}
                    />

                    {attributes.heroImageDisplayMode === 'inline' && (
                        <SelectControl
                            label="Text Wrap"
                            value={attributes.heroImageTextWrap}
                            options={[
                                { label: 'None', value: 'none' },
                                { label: 'Wrap Left', value: 'left' },
                            ]}
                            onChange={(value) =>
                                setAttributes({ heroImageTextWrap: value })
                            }
                        />
                    )}

                    <SelectControl
                        label="Alignment (background mode)"
                        value={attributes.heroImageAlignment}
                        options={[
                            { label: 'Center', value: 'center' },
                            { label: 'Left', value: 'left' },
                            { label: 'Right', value: 'right' },
                        ]}
                        onChange={(value) =>
                            setAttributes({ heroImageAlignment: value })
                        }
                    />

                    <RangeControl
                        label="Overlay Opacity (%)"
                        value={attributes.heroImageOverlayOpacity}
                        onChange={(value) =>
                            setAttributes({ heroImageOverlayOpacity: value })
                        }
                        min={0}
                        max={100}
                        step={5}
                    />

                    <SelectControl
                        label="Overlay Color"
                        value={attributes.heroImageOverlayColor}
                        options={[
                            { label: 'Black (dark)', value: 'black' },
                            { label: 'White (light)', value: 'white' },
                        ]}
                        onChange={(value) =>
                            setAttributes({ heroImageOverlayColor: value })
                        }
                    />

                    <RangeControl
                        label="Max Inline Image Width (%)"
                        value={parseInt((attributes.heroImageMaxWidth || '40%').replace('%', ''))}
                        onChange={(value) =>
                            setAttributes({ heroImageMaxWidth: value + '%' })
                        }
                        min={10}
                        max={100}
                        step={5}
                    />

                </PanelBody>

            </InspectorControls>

            {/* Editor UI */}
            <div {...blockProps}>

                <div className="numerology-editor-ui" style={{ marginBottom: '15px' }}>

                    <label style={{ fontWeight: '600' }}>
                        {t.enter_name_birthdate}
                    </label>

                    <input
                        type="text"
                        placeholder={t.full_name}
                        value={editorFullName}
                        onChange={(e) => setEditorFullName(e.target.value)}
                        style={{
                            width: '200px',
                            marginInlineEnd: '10px',
                            padding: '6px',
                            borderRadius: '4px',
                            border: '1px solid #ccc'
                        }}
                    />

                    <input
                        type="date"
                        value={editorBirthDate}
                        onChange={(e) => setEditorBirthDate(e.target.value)}
                        style={{
                            width: '150px',
                            marginInlineEnd: '10px',
                            padding: '6px',
                            borderRadius: '4px',
                            border: '1px solid #ccc'
                        }}
                    />

                    <Button
                        variant="primary"
                        onClick={fetchNumerology}
                        disabled={!editorFullName || !editorBirthDate}
                    >
                        {t.get_report}
                    </Button>
                </div>

                {/* Live Preview */}
                <div className="numerology-result-editor" style={{ padding: '10px' }}>
                    {loading && (
                        <div>
                            <div className="ezhp-progress-container">
                                <div className="ezhp-progress-bar"></div>
                            </div>
                            <p>{t.loading}</p>
                        </div>
                    )}
                    {!loading && previewHtml && (
                        <div dangerouslySetInnerHTML={{ __html: previewHtml }}></div>
                    )}
                </div>

            </div>
        </>
    );
}