import './style.css';
import {
    InspectorControls,
    MediaUpload,
    MediaUploadCheck,
    useBlockProps
} from '@wordpress/block-editor';
import {
    PanelBody,
    SelectControl,
    TextControl,
    TextareaControl,
    RangeControl,
    Button,
    ToggleControl,
    ColorPicker
} from '@wordpress/components';
import ServerSideRender from '@wordpress/server-side-render';

// RTL language codes
const RTL_LANGUAGES = [
    'ar', 'he', 'fa', 'ur', 'ps', 'sd', 'yi', 'ku', 'dv', 'ug',
    'arc', 'azb', 'ckb', 'mzn', 'pnb', 'ks', 'glk', 'bal', 'bqi',
    'luz', 'gbz', 'khw', 'lrc', 'prd', 'sdh', 'skr'
];

// Check if language code is RTL
const isRtlLanguage = (lang) => {
    if (!lang) return false;
    const baseLang = lang.toLowerCase().split('-')[0];
    return RTL_LANGUAGES.includes(baseLang);
};

// Get zodiac images URL from localized script data
const getZodiacImagesUrl = () => {
    if (typeof ezWeeklyHoroscopeProfessionalData !== 'undefined' && ezWeeklyHoroscopeProfessionalData.zodiacImagesUrl) {
        return ezWeeklyHoroscopeProfessionalData.zodiacImagesUrl;
    }
    return '';
};

// Get the default hero image URL for a zodiac sign
const getDefaultHeroImageUrl = (sign) => {
    const baseUrl = getZodiacImagesUrl();
    if (baseUrl && sign) {
        return baseUrl + 'ez-' + sign + '.jpg';
    }
    return '';
};

export default function Edit({ attributes, setAttributes }) {
    const {
        sign = 'aries',
        language = 'en',
        heroImageUrl = '',
        heroImageAlt = '',
        heroImageDisplayMode = 'inline',
        heroImageAlignment = 'center',
        heroImageTextWrap = 'none',
        heroImageOverlayOpacity = 50,
        heroImageOverlayColor = 'black',
        heroImageMaxWidth = '40%',
        // CTA settings
        ctaPlacement = 'none',
        ctaHeadline = '',
        ctaHeadingLevel = 'h3',
        ctaText = '',
        ctaButtonText = '',
        ctaButtonUrl = '',
        ctaImageUrl = '',
        ctaImageAlt = '',
        ctaImageClickable = true,
        ctaImageMaxWidth = '100%',
        ctaBackgroundColor = '',
        ctaBackgroundTransparent = false,
        ctaButtonColor = '',
    } = attributes;

    const isRtl = isRtlLanguage(language);

    // Check if EyeDropper API is supported
    const hasEyeDropper = typeof window !== 'undefined' && 'EyeDropper' in window;

    const signs = [
        { label: 'Aries', value: 'aries' },
        { label: 'Taurus', value: 'taurus' },
        { label: 'Gemini', value: 'gemini' },
        { label: 'Cancer', value: 'cancer' },
        { label: 'Leo', value: 'leo' },
        { label: 'Virgo', value: 'virgo' },
        { label: 'Libra', value: 'libra' },
        { label: 'Scorpio', value: 'scorpio' },
        { label: 'Sagittarius', value: 'sagittarius' },
        { label: 'Capricorn', value: 'capricorn' },
        { label: 'Aquarius', value: 'aquarius' },
        { label: 'Pisces', value: 'pisces' },
    ];

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

    return (
        <>
            <InspectorControls>
                {/* Horoscope Settings */}
                <PanelBody title="Horoscope Settings" initialOpen={true}>
                    <SelectControl
                        label="Zodiac Sign"
                        value={sign}
                        options={signs}
                        onChange={(value) => setAttributes({ sign: value })}
                    />
                    <TextControl
                        label="Language"
                        value={language}
                        onChange={(value) => setAttributes({ language: value })}
                        help={`Enter language code (e.g., en, es, fr, de, ar, he)${isRtl ? ' — RTL detected' : ''}`}
                    />
                    <p style={{ 
                        fontSize: '12px', 
                        color: '#5D6B8A', 
                        backgroundColor: 'rgba(93, 107, 138, 0.08)',
                        padding: '10px',
                        borderRadius: '4px',
                        marginTop: '10px'
                    }}>
                        <strong>Professional Style:</strong> This block uses the two-tier methodology with trigger/background analysis, favorable/sensitive periods, and activated life sectors.
                    </p>
                </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 }) => {
                                const defaultHeroUrl = getDefaultHeroImageUrl(sign);
                                const isUsingDefault = !heroImageUrl && defaultHeroUrl;
                                const displayUrl = heroImageUrl || defaultHeroUrl;

                                return (
                                    <div style={{ marginBottom: '15px' }}>
                                        {displayUrl ? (
                                            <>
                                                <p style={{ fontWeight: '600', marginBottom: '8px' }}>
                                                    Hero Image
                                                    {isUsingDefault && (
                                                        <span style={{ 
                                                            fontWeight: '400', 
                                                            fontSize: '11px', 
                                                            color: '#757575',
                                                            marginLeft: '8px',
                                                            backgroundColor: '#f0f0f0',
                                                            padding: '2px 6px',
                                                            borderRadius: '3px'
                                                        }}>
                                                            Default
                                                        </span>
                                                    )}
                                                </p>
                                                <img
                                                    src={displayUrl}
                                                    alt={heroImageAlt}
                                                    style={{
                                                        maxWidth: '100%',
                                                        maxHeight: '150px',
                                                        objectFit: 'cover',
                                                        borderRadius: '4px',
                                                        marginBottom: '10px',
                                                        display: 'block',
                                                        opacity: isUsingDefault ? 0.8 : 1,
                                                        border: isUsingDefault ? '2px dashed #ccc' : 'none',
                                                    }}
                                                />
                                                <div style={{ display: 'flex', gap: '8px' }}>
                                                    <Button variant="secondary" onClick={open}>
                                                        {isUsingDefault ? 'Replace Default' : 'Replace Image'}
                                                    </Button>
                                                    {!isUsingDefault && (
                                                        <Button
                                                            isDestructive
                                                            variant="secondary"
                                                            onClick={() => setAttributes({ 
                                                                heroImageUrl: '',
                                                                heroImageAlt: ''
                                                            })}
                                                        >
                                                            Use Default
                                                        </Button>
                                                    )}
                                                </div>
                                            </>
                                        ) : (
                                            <Button variant="secondary" onClick={open}>
                                                Select Hero Image
                                            </Button>
                                        )}
                                    </div>
                                );
                            }}
                        />
                    </MediaUploadCheck>

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

                    {heroImageDisplayMode === 'background' && (
                        <SelectControl
                            label="Image Position"
                            value={heroImageAlignment}
                            options={[
                                { label: 'Center', value: 'center' },
                                { label: 'Top', value: 'top' },
                                { label: 'Bottom', value: 'bottom' },
                                { label: 'Left', value: 'left' },
                                { label: 'Right', value: 'right' },
                            ]}
                            onChange={(value) => setAttributes({ heroImageAlignment: value })}
                        />
                    )}

                    {heroImageDisplayMode === 'inline' && (
                        <>
                            <SelectControl
                                label="Text Wrapping"
                                value={heroImageTextWrap}
                                options={[
                                    { label: 'None (Centered)', value: 'none' },
                                    { label: 'Wrap Left', value: 'left' },
                                    { label: 'Wrap Right', value: 'right' },
                                ]}
                                onChange={(value) => setAttributes({ heroImageTextWrap: value })}
                                help={isRtl ? 'Note: Left/Right will be mirrored for RTL languages' : ''}
                            />

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

                    <RangeControl
                        label="Overlay Opacity (%)"
                        value={heroImageOverlayOpacity ?? 50}
                        onChange={(value) => setAttributes({ heroImageOverlayOpacity: value })}
                        min={0}
                        max={100}
                        step={5}
                        help="Adjust overlay transparency (0% transparent — 100% opaque)."
                    />

                    <SelectControl
                        label="Overlay Color"
                        value={heroImageOverlayColor}
                        options={[
                            { label: 'Black (dark)', value: 'black' },
                            { label: 'White (light)', value: 'white' },
                        ]}
                        onChange={(value) => setAttributes({ heroImageOverlayColor: value })}
                        help="Choose dark or light tint depending on your image brightness."
                    />
                </PanelBody>

                {/* Call to Action */}
                <PanelBody 
                    title={`Call to Action${ctaPlacement !== 'none' ? ' ✓' : ''}`}
                    initialOpen={false}
                >
                    <SelectControl
                        label="Placement"
                        value={ctaPlacement}
                        options={[
                            { label: 'Disabled', value: 'none' },
                            { label: 'After Trigger Section', value: 'after-trigger' },
                            { label: 'After Life Sectors', value: 'after-life-sectors' },
                            { label: 'After Limitations', value: 'after-limitations' },
                        ]}
                        onChange={(value) => setAttributes({ ctaPlacement: value })}
                        help="Choose where the CTA appears in the professional weekly horoscope."
                    />

                    {ctaPlacement !== 'none' && (
                        <>
                            {/* Headline */}
                            <div style={{ marginTop: '15px', paddingTop: '15px', borderTop: '1px solid #e0e0e0' }}>
                                <TextControl
                                    label="Headline"
                                    value={ctaHeadline}
                                    onChange={(value) => setAttributes({ ctaHeadline: value })}
                                    placeholder="e.g., Unlock Your Full Reading"
                                />
                                <SelectControl
                                    label="Heading Level"
                                    value={ctaHeadingLevel}
                                    options={[
                                        { label: 'H2', value: 'h2' },
                                        { label: 'H3', value: 'h3' },
                                        { label: 'H4', value: 'h4' },
                                    ]}
                                    onChange={(value) => setAttributes({ ctaHeadingLevel: value })}
                                />
                            </div>

                            {/* Description Text */}
                            <div style={{ marginTop: '15px', paddingTop: '15px', borderTop: '1px solid #e0e0e0' }}>
                                <TextareaControl
                                    label="Description"
                                    value={ctaText}
                                    onChange={(value) => setAttributes({ ctaText: value })}
                                    placeholder="e.g., Get personalized insights and detailed predictions..."
                                    rows={3}
                                />
                            </div>

                            {/* Button */}
                            <div style={{ marginTop: '15px', paddingTop: '15px', borderTop: '1px solid #e0e0e0' }}>
                                <p style={{ fontWeight: '600', marginBottom: '8px' }}>Button</p>
                                <TextControl
                                    label="Button Text"
                                    value={ctaButtonText}
                                    onChange={(value) => setAttributes({ ctaButtonText: value })}
                                    placeholder="e.g., Get Premium"
                                />
                                <TextControl
                                    label="Button URL"
                                    value={ctaButtonUrl}
                                    onChange={(value) => setAttributes({ ctaButtonUrl: value })}
                                    placeholder="e.g., https://example.com/premium"
                                    type="url"
                                />
                            </div>

                            {/* Image */}
                            <div style={{ marginTop: '15px', paddingTop: '15px', borderTop: '1px solid #e0e0e0' }}>
                                <p style={{ fontWeight: '600', marginBottom: '8px' }}>Image</p>
                                <MediaUploadCheck>
                                    <MediaUpload
                                        onSelect={(media) => setAttributes({ 
                                            ctaImageUrl: media.url,
                                            ctaImageAlt: media.alt || ''
                                        })}
                                        allowedTypes={['image']}
                                        render={({ open }) => (
                                            <div>
                                                {ctaImageUrl ? (
                                                    <>
                                                        <img
                                                            src={ctaImageUrl}
                                                            alt={ctaImageAlt}
                                                            style={{
                                                                maxWidth: '100%',
                                                                maxHeight: '120px',
                                                                objectFit: 'cover',
                                                                borderRadius: '4px',
                                                                marginBottom: '8px',
                                                                display: 'block',
                                                            }}
                                                        />
                                                        <div style={{ display: 'flex', gap: '5px', marginBottom: '10px' }}>
                                                            <Button variant="secondary" onClick={open} size="small">
                                                                Replace
                                                            </Button>
                                                            <Button 
                                                                isDestructive 
                                                                variant="secondary" 
                                                                onClick={() => setAttributes({ ctaImageUrl: '', ctaImageAlt: '' })} 
                                                                size="small"
                                                            >
                                                                Remove
                                                            </Button>
                                                        </div>
                                                    </>
                                                ) : (
                                                    <Button variant="secondary" onClick={open} style={{ marginBottom: '10px' }}>
                                                        Select Image
                                                    </Button>
                                                )}
                                            </div>
                                        )}
                                    />
                                </MediaUploadCheck>

                                {ctaImageUrl && (
                                    <>
                                        <TextControl
                                            label="Image Alt Text"
                                            value={ctaImageAlt}
                                            onChange={(value) => setAttributes({ ctaImageAlt: value })}
                                            placeholder="Describe the image"
                                        />
                                        <RangeControl
                                            label="Image Max Width (%)"
                                            value={parseInt(ctaImageMaxWidth.replace('%', '')) || 100}
                                            onChange={(value) => setAttributes({ ctaImageMaxWidth: value + '%' })}
                                            min={10}
                                            max={100}
                                            step={5}
                                        />
                                        <ToggleControl
                                            label="Make image clickable"
                                            checked={ctaImageClickable}
                                            onChange={(value) => setAttributes({ ctaImageClickable: value })}
                                            help={ctaImageClickable ? 'Image will link to the Button URL.' : 'Image will not be clickable.'}
                                        />
                                    </>
                                )}
                            </div>

                            {/* Background Color */}
                            <div style={{ marginTop: '15px', paddingTop: '15px', borderTop: '1px solid #e0e0e0' }}>
                                <p style={{ fontWeight: '600', marginBottom: '8px' }}>Background</p>
                                
                                <ToggleControl
                                    label="Transparent background"
                                    checked={ctaBackgroundTransparent}
                                    onChange={(value) => setAttributes({ ctaBackgroundTransparent: value })}
                                />

                                {!ctaBackgroundTransparent && (
                                    <>
                                        <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '10px' }}>
                                            <div 
                                                style={{
                                                    width: '36px',
                                                    height: '36px',
                                                    borderRadius: '4px',
                                                    border: '1px solid #ccc',
                                                    background: ctaBackgroundColor || 'linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f3460 100%)',
                                                }}
                                            />
                                            <span style={{ fontSize: '12px', color: '#757575' }}>
                                                {ctaBackgroundColor || 'Default gradient'}
                                            </span>
                                            {ctaBackgroundColor && (
                                                <Button
                                                    variant="secondary"
                                                    size="small"
                                                    onClick={() => setAttributes({ ctaBackgroundColor: '' })}
                                                >
                                                    Reset
                                                </Button>
                                            )}
                                        </div>

                                        {hasEyeDropper && (
                                            <Button
                                                variant="secondary"
                                                onClick={async () => {
                                                    try {
                                                        const eyeDropper = new window.EyeDropper();
                                                        const result = await eyeDropper.open();
                                                        setAttributes({ ctaBackgroundColor: result.sRGBHex });
                                                    } catch (e) {
                                                        // User cancelled or error
                                                    }
                                                }}
                                                style={{ marginBottom: '10px', display: 'flex', alignItems: 'center', gap: '5px' }}
                                            >
                                                <span style={{ fontSize: '16px' }}>💧</span> Pick Color from Screen
                                            </Button>
                                        )}

                                        <ColorPicker
                                            color={ctaBackgroundColor || '#1a1a2e'}
                                            onChange={(color) => setAttributes({ ctaBackgroundColor: color })}
                                            enableAlpha={false}
                                        />
                                    </>
                                )}
                            </div>

                            {/* Button Color */}
                            <div style={{ marginTop: '15px', paddingTop: '15px', borderTop: '1px solid #e0e0e0' }}>
                                <p style={{ fontWeight: '600', marginBottom: '8px' }}>Button Color</p>
                                
                                <div style={{ display: 'flex', alignItems: 'center', gap: '10px', marginBottom: '10px' }}>
                                    <div 
                                        style={{
                                            width: '36px',
                                            height: '36px',
                                            borderRadius: '4px',
                                            border: '1px solid #ccc',
                                            background: ctaButtonColor || 'linear-gradient(135deg, #e94560 0%, #c23a51 100%)',
                                        }}
                                    />
                                    <span style={{ fontSize: '12px', color: '#757575' }}>
                                        {ctaButtonColor || 'Default gradient'}
                                    </span>
                                    {ctaButtonColor && (
                                        <Button
                                            variant="secondary"
                                            size="small"
                                            onClick={() => setAttributes({ ctaButtonColor: '' })}
                                        >
                                            Reset
                                        </Button>
                                    )}
                                </div>

                                {hasEyeDropper && (
                                    <Button
                                        variant="secondary"
                                        onClick={async () => {
                                            try {
                                                const eyeDropper = new window.EyeDropper();
                                                const result = await eyeDropper.open();
                                                setAttributes({ ctaButtonColor: result.sRGBHex });
                                            } catch (e) {
                                                // User cancelled or error
                                            }
                                        }}
                                        style={{ marginBottom: '10px', display: 'flex', alignItems: 'center', gap: '5px' }}
                                    >
                                        <span style={{ fontSize: '16px' }}>💧</span> Pick Color from Screen
                                    </Button>
                                )}

                                <ColorPicker
                                    color={ctaButtonColor || '#e94560'}
                                    onChange={(color) => setAttributes({ ctaButtonColor: color })}
                                    enableAlpha={false}
                                />
                            </div>
                        </>
                    )}
                </PanelBody>
            </InspectorControls>

            {/* Live preview area */}
            <div {...blockProps}>
                <ServerSideRender
                    block="ezhoroscope/weekly-horoscope-professional"
                    attributes={attributes}
                    LoadingResponsePlaceholder={() => (
                        <p style={{ textAlign: isRtl ? 'right' : 'center', opacity: 0.7 }}>
                            Loading preview…
                        </p>
                    )}
                />
            </div>
        </>
    );
}
