import './style.css';
import {
    InspectorControls,
    MediaUpload,
    MediaUploadCheck,
    useBlockProps,
    __experimentalLinkControl as LinkControl
} from '@wordpress/block-editor';

import {
    PanelBody,
    TextControl,
    RangeControl,
    SelectControl,
    Button,
    Spinner,
    Placeholder,
    BaseControl,
    ToggleControl
} from '@wordpress/components';

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

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

    const {
        language = 'en',
        showHeader = true,

        // 12 image attributes
        imageAries = '',
        imageTaurus = '',
        imageGemini = '',
        imageCancer = '',
        imageLeo = '',
        imageVirgo = '',
        imageLibra = '',
        imageScorpio = '',
        imageSagittarius = '',
        imageCapricorn = '',
        imageAquarius = '',
        imagePisces = '',

        // 12 link attributes
        linkAries = '',
        linkTaurus = '',
        linkGemini = '',
        linkCancer = '',
        linkLeo = '',
        linkVirgo = '',
        linkLibra = '',
        linkScorpio = '',
        linkSagittarius = '',
        linkCapricorn = '',
        linkAquarius = '',
        linkPisces = '',

        // Hero display settings (global)
        heroImageDisplayMode = 'inline',
        heroImageTextWrap = 'none',
        heroImageAlignment = 'center',
        heroImageOverlayOpacity = 50,
        heroImageOverlayColor = 'black',
        heroImageMaxWidth = '40%',
    } = attributes;

    // RTL language detection
    const rtlLanguages = ['ar', 'he', 'fa', 'ur'];
    const isRTL = rtlLanguages.includes(language);

    const blockProps = useBlockProps({
        className: 'ez-horoscope-block',
        style: { border: '1px solid #ddd', padding: '10px', borderRadius: '6px' },
        dir: isRTL ? 'rtl' : undefined,
        lang: isRTL ? language : undefined,
    });

    // Track which link control is currently open
    const [activeLinkControl, setActiveLinkControl] = useState(null);

    // Debounced render key to prevent too many API calls
    const [renderKey, setRenderKey] = useState(0);
    
    useEffect(() => {
        const timer = setTimeout(() => {
            setRenderKey(prev => prev + 1);
        }, 500);
        return () => clearTimeout(timer);
    }, [
        language,
        showHeader,
        imageAries, imageTaurus, imageGemini, imageCancer,
        imageLeo, imageVirgo, imageLibra, imageScorpio,
        imageSagittarius, imageCapricorn, imageAquarius, imagePisces,
        linkAries, linkTaurus, linkGemini, linkCancer,
        linkLeo, linkVirgo, linkLibra, linkScorpio,
        linkSagittarius, linkCapricorn, linkAquarius, linkPisces,
        heroImageDisplayMode, heroImageTextWrap, heroImageAlignment,
        heroImageOverlayOpacity, heroImageOverlayColor, heroImageMaxWidth
    ]);

    // Zodiac sign symbols for visual appeal
    const zodiacSymbols = {
        Aries: '♈',
        Taurus: '♉',
        Gemini: '♊',
        Cancer: '♋',
        Leo: '♌',
        Virgo: '♍',
        Libra: '♎',
        Scorpio: '♏',
        Sagittarius: '♐',
        Capricorn: '♑',
        Aquarius: '♒',
        Pisces: '♓'
    };

    // Card style for each zodiac sign
    const cardStyle = {
        border: '1px solid #e0e0e0',
        borderRadius: '8px',
        padding: '12px',
        marginBottom: '12px',
        backgroundColor: '#fafafa'
    };

    const cardHeaderStyle = {
        display: 'flex',
        alignItems: 'center',
        gap: '8px',
        marginBottom: '10px',
        paddingBottom: '8px',
        borderBottom: '1px solid #e0e0e0'
    };

    const symbolStyle = {
        fontSize: '20px',
        width: '28px',
        height: '28px',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#0073aa',
        color: '#fff',
        borderRadius: '50%'
    };

    const labelStyle = {
        fontWeight: '600',
        fontSize: '13px',
        margin: 0
    };

    // Helper for generating image upload controls for each sign
    function renderImageControl(label, attrName, attrValue) {
        const symbol = zodiacSymbols[label] || '★';
        
        return (
            <div style={cardStyle}>
                <div style={cardHeaderStyle}>
                    <span style={symbolStyle}>{symbol}</span>
                    <span style={labelStyle}>{label}</span>
                </div>
                <MediaUploadCheck>
                    <MediaUpload
                        onSelect={(media) => setAttributes({ [attrName]: media.url })}
                        allowedTypes={['image']}
                        render={({ open }) => (
                            <div>
                                {attrValue ? (
                                    <div>
                                        <img
                                            src={attrValue}
                                            alt={label}
                                            style={{ 
                                                width: '100%',
                                                height: '80px',
                                                objectFit: 'cover',
                                                borderRadius: '4px',
                                                marginBottom: '8px'
                                            }}
                                        />
                                        <div style={{ display: 'flex', gap: '8px' }}>
                                            <Button
                                                variant="secondary"
                                                size="small"
                                                onClick={open}
                                                style={{ flex: 1 }}
                                            >
                                                Replace
                                            </Button>
                                            <Button
                                                isDestructive
                                                variant="secondary"
                                                size="small"
                                                onClick={() => setAttributes({ [attrName]: '' })}
                                                style={{ flex: 1 }}
                                            >
                                                Remove
                                            </Button>
                                        </div>
                                    </div>
                                ) : (
                                    <Button 
                                        variant="secondary" 
                                        onClick={open}
                                        style={{ width: '100%' }}
                                    >
                                        Select Image
                                    </Button>
                                )}
                            </div>
                        )}
                    />
                </MediaUploadCheck>
            </div>
        );
    }

    // Helper for generating link controls with page picker
    function renderLinkControl(label, attrName, attrValue) {
        const isOpen = activeLinkControl === attrName;
        const symbol = zodiacSymbols[label.replace(' Link', '')] || '★';
        
        return (
            <div style={cardStyle}>
                <div style={cardHeaderStyle}>
                    <span style={symbolStyle}>{symbol}</span>
                    <span style={labelStyle}>{label}</span>
                </div>
                <div>
                    {attrValue && !isOpen ? (
                        <div>
                            <div style={{ 
                                padding: '8px',
                                background: '#fff',
                                border: '1px solid #ddd',
                                borderRadius: '4px',
                                marginBottom: '8px',
                                fontSize: '11px',
                                overflow: 'hidden',
                                textOverflow: 'ellipsis',
                                whiteSpace: 'nowrap'
                            }}>
                                {attrValue}
                            </div>
                            <div style={{ display: 'flex', gap: '8px' }}>
                                <Button
                                    variant="secondary"
                                    size="small"
                                    onClick={() => setActiveLinkControl(attrName)}
                                    style={{ flex: 1 }}
                                >
                                    Edit
                                </Button>
                                <Button
                                    isDestructive
                                    variant="secondary"
                                    size="small"
                                    onClick={() => setAttributes({ [attrName]: '' })}
                                    style={{ flex: 1 }}
                                >
                                    Remove
                                </Button>
                            </div>
                        </div>
                    ) : (
                        <div>
                            {!isOpen ? (
                                <Button
                                    variant="secondary"
                                    onClick={() => setActiveLinkControl(attrName)}
                                    style={{ width: '100%' }}
                                >
                                    Select Page
                                </Button>
                            ) : (
                                <div style={{ 
                                    border: '1px solid #ddd', 
                                    borderRadius: '4px',
                                    background: '#fff'
                                }}>
                                    <LinkControl
                                        value={{ url: attrValue }}
                                        onChange={(newLink) => {
                                            setAttributes({ [attrName]: newLink?.url || '' });
                                        }}
                                        onRemove={() => {
                                            setAttributes({ [attrName]: '' });
                                            setActiveLinkControl(null);
                                        }}
                                        settings={[]}
                                        showSuggestions={true}
                                        suggestionsQuery={{
                                            type: 'post',
                                            subtype: 'page,post'
                                        }}
                                    />
                                    <div style={{ padding: '8px', borderTop: '1px solid #ddd' }}>
                                        <Button
                                            variant="secondary"
                                            size="small"
                                            onClick={() => setActiveLinkControl(null)}
                                        >
                                            Done
                                        </Button>
                                    </div>
                                </div>
                            )}
                        </div>
                    )}
                </div>
            </div>
        );
    }

    return (
        <>
            <InspectorControls>

                {/* === GENERAL SETTINGS === */}
                <PanelBody title="Horoscope Summary Settings" initialOpen={true}>
                    <TextControl
                        label="Language"
                        value={language}
                        onChange={(value) => setAttributes({ language: value })}
                    />
                    <ToggleControl
                        label="Show Date Header"
                        help={showHeader ? 'Displaying "Daily Horoscopes for [date]" header.' : 'Header is hidden.'}
                        checked={showHeader}
                        onChange={(value) => setAttributes({ showHeader: value })}
                    />
                </PanelBody>

                {/* === IMAGE UPLOADS === */}
                <PanelBody title="Zodiac Sign Images" initialOpen={false}>
                    <p style={{ fontSize: '12px', color: '#666', marginBottom: '15px' }}>
                        Add images for each zodiac sign. Images will display based on your Hero Image settings.
                    </p>
                    {renderImageControl('Aries', 'imageAries', imageAries)}
                    {renderImageControl('Taurus', 'imageTaurus', imageTaurus)}
                    {renderImageControl('Gemini', 'imageGemini', imageGemini)}
                    {renderImageControl('Cancer', 'imageCancer', imageCancer)}
                    {renderImageControl('Leo', 'imageLeo', imageLeo)}
                    {renderImageControl('Virgo', 'imageVirgo', imageVirgo)}
                    {renderImageControl('Libra', 'imageLibra', imageLibra)}
                    {renderImageControl('Scorpio', 'imageScorpio', imageScorpio)}
                    {renderImageControl('Sagittarius', 'imageSagittarius', imageSagittarius)}
                    {renderImageControl('Capricorn', 'imageCapricorn', imageCapricorn)}
                    {renderImageControl('Aquarius', 'imageAquarius', imageAquarius)}
                    {renderImageControl('Pisces', 'imagePisces', imagePisces)}
                </PanelBody>

                {/* === LINK URLS === */}
                <PanelBody title="Zodiac Sign Links" initialOpen={false}>
                    <p style={{ fontSize: '12px', color: '#666', marginBottom: '15px' }}>
                        Search for pages or enter a custom URL. A "More..." link will appear after each summary.
                    </p>
                    {renderLinkControl('Aries Link', 'linkAries', linkAries)}
                    {renderLinkControl('Taurus Link', 'linkTaurus', linkTaurus)}
                    {renderLinkControl('Gemini Link', 'linkGemini', linkGemini)}
                    {renderLinkControl('Cancer Link', 'linkCancer', linkCancer)}
                    {renderLinkControl('Leo Link', 'linkLeo', linkLeo)}
                    {renderLinkControl('Virgo Link', 'linkVirgo', linkVirgo)}
                    {renderLinkControl('Libra Link', 'linkLibra', linkLibra)}
                    {renderLinkControl('Scorpio Link', 'linkScorpio', linkScorpio)}
                    {renderLinkControl('Sagittarius Link', 'linkSagittarius', linkSagittarius)}
                    {renderLinkControl('Capricorn Link', 'linkCapricorn', linkCapricorn)}
                    {renderLinkControl('Aquarius Link', 'linkAquarius', linkAquarius)}
                    {renderLinkControl('Pisces Link', 'linkPisces', linkPisces)}
                </PanelBody>

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

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

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

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

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

                    <SelectControl
                        label="Overlay Color"
                        value={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(heroImageMaxWidth.replace('%', ''))}
                        onChange={(value) => setAttributes({ heroImageMaxWidth: value + '%' })}
                        min={10}
                        max={100}
                        step={5}
                    />

                </PanelBody>
            </InspectorControls>

            {/* === BLOCK PREVIEW === */}
            <div {...blockProps}>
                <ServerSideRender
                    block="ezhoroscope/horoscope-summaries"
                    attributes={attributes}
                    httpMethod="POST"
                    key={renderKey}
                    LoadingResponsePlaceholder={() => (
                        <Placeholder>
                            <Spinner />
                            <p>Loading horoscope summaries...</p>
                        </Placeholder>
                    )}
                    ErrorResponsePlaceholder={({ response }) => (
                        <Placeholder>
                            <p style={{ color: 'red' }}>
                                Error loading block preview.
                            </p>
                            {response && (
                                <pre style={{ fontSize: '11px', overflow: 'auto', maxHeight: '200px' }}>
                                    {typeof response === 'string' ? response : JSON.stringify(response, null, 2)}
                                </pre>
                            )}
                        </Placeholder>
                    )}
                />
            </div>
        </>
    );
}