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

// RTL language codes
const RTL_LANGUAGES = ['ar', 'he', 'ur', 'fa'];

export default function Edit({ attributes, setAttributes }) {
    const {
        language = 'en',
        imageSize = 100,
        newMoonImage = '',
        waxingCrescentImage = '',
        firstQuarterImage = '',
        waxingGibbousImage = '',
        fullMoonImage = '',
        waningGibbousImage = '',
        lastQuarterImage = '',
        waningCrescentImage = '',
        ctaEnabled = false,
        ctaText = '',
        ctaImageUrl = '',
        ctaImageAlt = '',
        ctaUrl = '',
        ctaLinkType = 'button',
        ctaLinkText = '',
        ctaImageClickable = false,
        ctaElementId = '',
    } = attributes;

    // Check if current language is RTL
    const isRtl = RTL_LANGUAGES.includes(language);

    const languages = [
        { label: 'English', value: 'en' },
        { label: 'French', value: 'fr' },
        { label: 'Italian', value: 'it' },
        { label: 'German', value: 'de' },
        { label: 'Spanish', value: 'es' },
        { label: 'Arabic', value: 'ar' },
        { label: 'Bengali', value: 'bn' },
        { label: 'Czech', value: 'cs' },
        { label: 'Danish', value: 'da' },
        { label: 'Greek', value: 'el' },
        { label: 'Estonian', value: 'et' },
        { label: 'Basque', value: 'eu' },
        { label: 'Persian', value: 'fa' },
        { label: 'Finnish', value: 'fi' },
        { label: 'Hebrew', value: 'he' },
        { label: 'Hindi', value: 'hi' },
        { label: 'Hungarian', value: 'hu' },
        { label: 'Indonesian', value: 'id' },
        { label: 'Japanese', value: 'ja' },
        { label: 'Korean', value: 'ko' },
        { label: 'Lithuanian', value: 'lt' },
        { label: 'Latvian', value: 'lv' },
        { label: 'Malay', value: 'ms' },
        { label: 'Norwegian', value: 'nb' },
        { label: 'Dutch', value: 'nl' },
        { label: 'Polish', value: 'pl' },
        { label: 'Portuguese', value: 'pt' },
        { label: 'Romanian', value: 'ro' },
        { label: 'Russian', value: 'ru' },
        { label: 'Albanian', value: 'sq' },
        { label: 'Swedish', value: 'sv' },
        { label: 'Thai', value: 'th' },
        { label: 'Tagalog', value: 'tl' },
        { label: 'Turkish', value: 'tr' },
        { label: 'Ukrainian', value: 'uk' },
        { label: 'Urdu', value: 'ur' },
        { label: 'Esperanto', value: 'eo' },
        { label: 'Irish', value: 'ga' },
        { label: 'Galician', value: 'gl' },
        { label: 'Azerbaijani', value: 'az' },
        { label: 'Bulgarian', value: 'bg' },
        { label: 'Catalan', value: 'ca' },
        { label: 'Slovak', value: 'sk' },
        { label: 'Slovenian', value: 'sl' },
        { label: 'Chinese', value: 'zh' },
    ];

    const moonPhaseImages = [
        { key: 'newMoonImage', label: 'New Moon', value: newMoonImage },
        { key: 'waxingCrescentImage', label: 'Waxing Crescent', value: waxingCrescentImage },
        { key: 'firstQuarterImage', label: 'First Quarter', value: firstQuarterImage },
        { key: 'waxingGibbousImage', label: 'Waxing Gibbous', value: waxingGibbousImage },
        { key: 'fullMoonImage', label: 'Full Moon', value: fullMoonImage },
        { key: 'waningGibbousImage', label: 'Waning Gibbous', value: waningGibbousImage },
        { key: 'lastQuarterImage', label: 'Last Quarter', value: lastQuarterImage },
        { key: 'waningCrescentImage', label: 'Waning Crescent', value: waningCrescentImage },
    ];

    const linkTypeOptions = [
        { label: 'Button', value: 'button' },
        { label: 'Text Link', value: 'text' },
        { label: 'Image Only', value: 'image' },
    ];

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

    const renderImageUpload = (imageKey, label, currentValue) => (
        <div style={{ marginBottom: '15px' }}>
            <p style={{ marginBottom: '5px', fontWeight: '500' }}>{label}</p>
            <MediaUploadCheck>
                <MediaUpload
                    onSelect={(media) => setAttributes({ [imageKey]: media.url })}
                    allowedTypes={['image']}
                    render={({ open }) => (
                        <div>
                            {currentValue ? (
                                <>
                                    <img
                                        src={currentValue}
                                        alt={label}
                                        style={{
                                            maxWidth: '60px',
                                            borderRadius: '4px',
                                            marginBottom: '5px',
                                            display: 'block',
                                        }}
                                    />
                                    <Button
                                        isDestructive
                                        variant="secondary"
                                        isSmall
                                        onClick={() => setAttributes({ [imageKey]: '' })}
                                    >
                                        Remove
                                    </Button>
                                </>
                            ) : (
                                <Button variant="secondary" isSmall onClick={open}>
                                    Select Image
                                </Button>
                            )}
                        </div>
                    )}
                />
            </MediaUploadCheck>
        </div>
    );

    return (
        <>
            <InspectorControls>
                <PanelBody title="Moon Phase Settings" initialOpen={true}>
                    <SelectControl
                        label="Language"
                        value={language}
                        options={languages}
                        onChange={(value) => setAttributes({ language: value })}
                    />
                    <RangeControl
                        label="Moon Image Size (px)"
                        value={imageSize}
                        onChange={(value) => setAttributes({ imageSize: value })}
                        min={40}
                        max={200}
                        step={10}
                    />
                </PanelBody>

                <PanelBody title="Moon Phase Images" initialOpen={false}>
                    <p style={{ marginBottom: '15px', color: '#666', fontSize: '12px' }}>
                        Upload custom images for each moon phase. If not set, default images will be used.
                    </p>
                    {moonPhaseImages.map(({ key, label, value }) =>
                        renderImageUpload(key, label, value)
                    )}
                </PanelBody>

                <PanelBody title="Call to Action (Premium)" initialOpen={false}>
                    <ToggleControl
                        label="Enable CTA"
                        checked={ctaEnabled}
                        onChange={(value) => setAttributes({ ctaEnabled: value })}
                        help="Replace the default moon reading prompt with your custom call to action."
                    />

                    {ctaEnabled && (
                        <>
                            <TextareaControl
                                label="CTA Text"
                                value={ctaText}
                                onChange={(value) => setAttributes({ ctaText: value })}
                                help="Introductory text for your offer (not clickable)."
                                placeholder="Today's moon phase is perfect for you to get your moon reading"
                            />

                            <div style={{ marginBottom: '16px' }}>
                                <p style={{ marginBottom: '5px', fontWeight: '500' }}>CTA Image (optional)</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%',
                                                                borderRadius: '4px',
                                                                marginBottom: '8px',
                                                                display: 'block',
                                                            }}
                                                        />
                                                        <Button
                                                            isDestructive
                                                            variant="secondary"
                                                            isSmall
                                                            onClick={() => setAttributes({ 
                                                                ctaImageUrl: '',
                                                                ctaImageAlt: ''
                                                            })}
                                                        >
                                                            Remove Image
                                                        </Button>
                                                    </>
                                                ) : (
                                                    <Button variant="secondary" onClick={open}>
                                                        Select CTA Image
                                                    </Button>
                                                )}
                                            </div>
                                        )}
                                    />
                                </MediaUploadCheck>
                            </div>

                            {ctaImageUrl && (
                                <TextControl
                                    label="Image Alt Text"
                                    value={ctaImageAlt}
                                    onChange={(value) => setAttributes({ ctaImageAlt: value })}
                                />
                            )}

                            <TextControl
                                label="CTA URL"
                                value={ctaUrl}
                                onChange={(value) => setAttributes({ ctaUrl: value })}
                                placeholder="https://example.com/affiliate-link"
                                type="url"
                            />

                            <SelectControl
                                label="Link Type"
                                value={ctaLinkType}
                                options={linkTypeOptions}
                                onChange={(value) => setAttributes({ ctaLinkType: value })}
                                help={
                                    ctaLinkType === 'button' ? 'Displays a styled button.' :
                                    ctaLinkType === 'text' ? 'Displays a text link.' :
                                    'Makes the image itself clickable (no button/text link).'
                                }
                            />

                            {(ctaLinkType === 'button' || ctaLinkType === 'text') && (
                                <TextControl
                                    label={ctaLinkType === 'button' ? 'Button Text' : 'Link Text'}
                                    value={ctaLinkText}
                                    onChange={(value) => setAttributes({ ctaLinkText: value })}
                                    placeholder={ctaLinkType === 'button' ? 'Get Your Reading Now!' : 'Click here to learn more'}
                                />
                            )}

                            {ctaImageUrl && ctaLinkType !== 'image' && (
                                <ToggleControl
                                    label="Make Image Clickable"
                                    checked={ctaImageClickable}
                                    onChange={(value) => setAttributes({ ctaImageClickable: value })}
                                    help="Also wrap the image in a link."
                                />
                            )}

                            <TextControl
                                label="Element ID (for CSS)"
                                value={ctaElementId}
                                onChange={(value) => setAttributes({ ctaElementId: value })}
                                placeholder="my-moon-cta"
                                help="Custom ID for styling with CSS."
                            />
                        </>
                    )}
                </PanelBody>
            </InspectorControls>

            <div {...blockProps}>
                <ServerSideRender
                    block="ezhoroscope/moon-phase"
                    attributes={attributes}
                    key={[
                        language,
                        imageSize,
                        newMoonImage,
                        waxingCrescentImage,
                        firstQuarterImage,
                        waxingGibbousImage,
                        fullMoonImage,
                        waningGibbousImage,
                        lastQuarterImage,
                        waningCrescentImage,
                    ].join('-')}
                />
            </div>
        </>
    );
}