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

// Simple calendar icon SVG
const CalendarIcon = () => (
    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
        <rect x="3" y="4" width="18" height="18" rx="2" ry="2"/>
        <line x1="16" y1="2" x2="16" y2="6"/>
        <line x1="8" y1="2" x2="8" y2="6"/>
        <line x1="3" y1="10" x2="21" y2="10"/>
    </svg>
);

export default function Edit({ attributes, setAttributes }) {
    const {
        sign = 'aries',
        language = 'en',
        horoscopeDate = '',
        heroImageUrl = '',
        heroImageAlt = '',
        heroImageDisplayMode = 'inline',
        heroImageAlignment = 'center',
        heroImageTextWrap = 'none',
        heroImageOverlayOpacity = 0,
        heroImageOverlayColor = 'black',
        heroImageMaxWidth = '40%',
        suppressHeading = false,
        // Section visibility
        showThemeSection = true,
        showKeyDatesSection = true,
        showFocusAreasSection = true,
        showPracticesSection = true,
        showMantraSection = true,
        // CTA 1
        cta1Enabled = false,
        cta1Position = 'after-theme',
        cta1HeaderText = '',
        cta1HeaderLevel = 'h3',
        cta1Text = '',
        cta1ImageUrl = '',
        cta1ImageAlt = '',
        cta1ImageMaxWidth = '100%',
        cta1Url = '',
        cta1LinkType = 'button',
        cta1LinkText = '',
        cta1ImageClickable = false,
        cta1ElementId = '',
        cta1Alignment = 'center',
        // CTA 2
        cta2Enabled = false,
        cta2Position = 'after-key-dates',
        cta2HeaderText = '',
        cta2HeaderLevel = 'h3',
        cta2Text = '',
        cta2ImageUrl = '',
        cta2ImageAlt = '',
        cta2ImageMaxWidth = '100%',
        cta2Url = '',
        cta2LinkType = 'button',
        cta2LinkText = '',
        cta2ImageClickable = false,
        cta2ElementId = '',
        cta2Alignment = 'center',
        // CTA 3
        cta3Enabled = false,
        cta3Position = 'after-focus-areas',
        cta3HeaderText = '',
        cta3HeaderLevel = 'h3',
        cta3Text = '',
        cta3ImageUrl = '',
        cta3ImageAlt = '',
        cta3ImageMaxWidth = '100%',
        cta3Url = '',
        cta3LinkType = 'button',
        cta3LinkText = '',
        cta3ImageClickable = false,
        cta3ElementId = '',
        cta3Alignment = 'center',
    } = attributes;

    const [isDatePickerOpen, setIsDatePickerOpen] = useState(false);

    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 positionOptions = [
        { label: 'Before Theme', value: 'before-theme' },
        { label: 'After Theme', value: 'after-theme' },
        { label: 'Before Key Dates', value: 'before-key-dates' },
        { label: 'After Key Dates', value: 'after-key-dates' },
        { label: 'Before Focus Areas', value: 'before-focus-areas' },
        { label: 'After Focus Areas', value: 'after-focus-areas' },
        { label: 'Before Practices', value: 'before-practices' },
        { label: 'After Practices', value: 'after-practices' },
        { label: 'Before Mantra', value: 'before-mantra' },
        { label: 'After Mantra', value: 'after-mantra' },
    ];

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

    const headerLevelOptions = [
        { label: 'H2', value: 'h2' },
        { label: 'H3', value: 'h3' },
        { label: 'H4', value: 'h4' },
    ];

    const alignmentOptions = [
        { label: 'Left', value: 'left' },
        { label: 'Center', value: 'center' },
        { label: 'Right', value: 'right' },
    ];

    const displayModeOptions = [
        { label: 'Inline Image', value: 'inline' },
        { label: 'Background Image', value: 'background' },
    ];

    const textWrapOptions = [
        { label: 'None (Centered)', value: 'none' },
        { label: 'Float Left', value: 'left' },
        { label: 'Float Right', value: 'right' },
    ];

    const overlayColorOptions = [
        { label: 'Black', value: 'black' },
        { label: 'White', value: 'white' },
    ];

    const blockProps = useBlockProps({
        className: 'ez-horoscope-block ez-monthly-horoscope-block',
        style: { border: '1px solid #ddd', padding: '10px', borderRadius: '6px' },
    });

    const sectionDividerStyle = {
        borderTop: '1px solid #ddd',
        marginTop: '16px',
        paddingTop: '16px',
    };

    const sectionLabelStyle = {
        fontSize: '11px',
        fontWeight: '600',
        textTransform: 'uppercase',
        color: '#757575',
        marginBottom: '12px',
    };

    // Format date for display
    const formatDateForDisplay = (dateString) => {
        if (!dateString) return '';
        const date = new Date(dateString);
        return date.toLocaleDateString('en-US', { year: 'numeric', month: 'long' });
    };

    // Handle date change from DatePicker
    const handleDateChange = (newDate) => {
        if (newDate) {
            // Format as YYYY-MM-DD for API
            const date = new Date(newDate);
            const formatted = date.toISOString().split('T')[0];
            setAttributes({ horoscopeDate: formatted });
        }
        setIsDatePickerOpen(false);
    };

    // Render CTA controls
    const renderCTAControls = (ctaNum, enabled, setEnabled, position, headerText, headerLevel, text, imageUrl, imageAlt, imageMaxWidth, url, linkType, linkText, imageClickable, elementId, alignment) => {
        const prefix = `cta${ctaNum}`;
        
        return (
            <PanelBody title={`CTA ${ctaNum}`} initialOpen={false}>
                <ToggleControl
                    label="Enable CTA"
                    checked={enabled}
                    onChange={(value) => setAttributes({ [`${prefix}Enabled`]: value })}
                />

                {enabled && (
                    <>
                        <SelectControl
                            label="Position"
                            value={position}
                            options={positionOptions}
                            onChange={(value) => setAttributes({ [`${prefix}Position`]: value })}
                            help="Choose where to display this CTA in the horoscope."
                        />

                        <div style={sectionDividerStyle}>
                            <p style={sectionLabelStyle}>Content</p>
                        </div>

                        <TextControl
                            label="CTA Header"
                            value={headerText}
                            onChange={(value) => setAttributes({ [`${prefix}HeaderText`]: value })}
                            placeholder="Your Special Offer"
                        />

                        <SelectControl
                            label="Header Level"
                            value={headerLevel}
                            options={headerLevelOptions}
                            onChange={(value) => setAttributes({ [`${prefix}HeaderLevel`]: value })}
                        />

                        <TextareaControl
                            label="CTA Text"
                            value={text}
                            onChange={(value) => setAttributes({ [`${prefix}Text`]: value })}
                            help="Introductory text for your offer."
                            placeholder="Discover your deeper cosmic insights today!"
                        />

                        <div style={{ marginBottom: '16px' }}>
                            <p style={{ marginBottom: '5px', fontWeight: '500' }}>CTA Image (optional)</p>
                            <MediaUploadCheck>
                                <MediaUpload
                                    onSelect={(media) => setAttributes({
                                        [`${prefix}ImageUrl`]: media.url,
                                        [`${prefix}ImageAlt`]: media.alt || ''
                                    })}
                                    allowedTypes={['image']}
                                    render={({ open }) => (
                                        <div>
                                            {imageUrl ? (
                                                <>
                                                    <img
                                                        src={imageUrl}
                                                        alt={imageAlt}
                                                        style={{
                                                            maxWidth: '100%',
                                                            borderRadius: '4px',
                                                            marginBottom: '8px',
                                                            display: 'block',
                                                        }}
                                                    />
                                                    <Button
                                                        isDestructive
                                                        variant="secondary"
                                                        isSmall
                                                        onClick={() => setAttributes({
                                                            [`${prefix}ImageUrl`]: '',
                                                            [`${prefix}ImageAlt`]: ''
                                                        })}
                                                    >
                                                        Remove Image
                                                    </Button>
                                                </>
                                            ) : (
                                                <Button variant="secondary" onClick={open}>
                                                    Select CTA Image
                                                </Button>
                                            )}
                                        </div>
                                    )}
                                />
                            </MediaUploadCheck>
                        </div>

                        {imageUrl && (
                            <TextControl
                                label="Image Alt Text"
                                value={imageAlt}
                                onChange={(value) => setAttributes({ [`${prefix}ImageAlt`]: value })}
                            />
                        )}

                        {imageUrl && (
                            <TextControl
                                label="Image Max Width"
                                value={imageMaxWidth}
                                onChange={(value) => setAttributes({ [`${prefix}ImageMaxWidth`]: value })}
                                placeholder="100%"
                                help="CSS value (e.g., 50%, 300px, 20rem)"
                            />
                        )}

                        <div style={sectionDividerStyle}>
                            <p style={sectionLabelStyle}>Link Settings</p>
                        </div>

                        <TextControl
                            label="CTA URL"
                            value={url}
                            onChange={(value) => setAttributes({ [`${prefix}Url`]: value })}
                            placeholder="https://example.com/affiliate-link"
                            type="url"
                        />

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

                        {(linkType === 'button' || linkType === 'text') && (
                            <TextControl
                                label={linkType === 'button' ? 'Button Text' : 'Link Text'}
                                value={linkText}
                                onChange={(value) => setAttributes({ [`${prefix}LinkText`]: value })}
                                placeholder={linkType === 'button' ? 'Get Your Reading Now!' : 'Click here to learn more'}
                            />
                        )}

                        {imageUrl && linkType !== 'image' && (
                            <ToggleControl
                                label="Make Image Clickable"
                                checked={imageClickable}
                                onChange={(value) => setAttributes({ [`${prefix}ImageClickable`]: value })}
                                help="Also wrap the image in a link."
                            />
                        )}

                        <div style={sectionDividerStyle}>
                            <p style={sectionLabelStyle}>Styling</p>
                        </div>

                        <SelectControl
                            label="Alignment"
                            value={alignment}
                            options={alignmentOptions}
                            onChange={(value) => setAttributes({ [`${prefix}Alignment`]: value })}
                        />

                        <TextControl
                            label="Element ID (for CSS)"
                            value={elementId}
                            onChange={(value) => setAttributes({ [`${prefix}ElementId`]: value })}
                            placeholder={`cta-${ctaNum}-custom`}
                            help="Custom ID for styling with CSS."
                        />
                    </>
                )}
            </PanelBody>
        );
    };

    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 Code"
                        value={language}
                        onChange={(value) => setAttributes({ language: value })}
                        help="Enter language code (e.g., en, es, fr, de)"
                        placeholder="en"
                    />

                    <div style={{ marginBottom: '16px' }}>
                        <p style={{ marginBottom: '5px', fontWeight: '500' }}>Month</p>
                        <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                            <TextControl
                                value={horoscopeDate ? formatDateForDisplay(horoscopeDate) : ''}
                                placeholder="Current month"
                                readOnly
                                style={{ flex: 1 }}
                            />
                            <Button
                                icon={CalendarIcon}
                                onClick={() => setIsDatePickerOpen(!isDatePickerOpen)}
                                label="Select date"
                            />
                            {horoscopeDate && (
                                <Button
                                    isDestructive
                                    isSmall
                                    onClick={() => setAttributes({ horoscopeDate: '' })}
                                >
                                    Clear
                                </Button>
                            )}
                        </div>
                        {isDatePickerOpen && (
                            <Popover
                                position="bottom center"
                                onClose={() => setIsDatePickerOpen(false)}
                            >
                                <div style={{ padding: '16px' }}>
                                    <DatePicker
                                        currentDate={horoscopeDate || new Date().toISOString()}
                                        onChange={handleDateChange}
                                    />
                                </div>
                            </Popover>
                        )}
                        <p style={{ fontSize: '12px', color: '#757575', marginTop: '4px' }}>
                            Leave empty to display current month's horoscope.
                        </p>
                    </div>

                    <ToggleControl
                        label="Suppress Main Heading"
                        checked={suppressHeading}
                        onChange={(value) => setAttributes({ suppressHeading: value })}
                        help="Hide the main title heading."
                    />
                </PanelBody>

                {/* Hero Image Settings */}
                <PanelBody title="Hero Image" initialOpen={false}>
                    <div style={{ marginBottom: '16px' }}>
                        <p style={{ marginBottom: '5px', fontWeight: '500' }}>Hero Image</p>
                        <MediaUploadCheck>
                            <MediaUpload
                                onSelect={(media) => setAttributes({
                                    heroImageUrl: media.url,
                                    heroImageAlt: media.alt || ''
                                })}
                                allowedTypes={['image']}
                                render={({ open }) => (
                                    <div>
                                        {heroImageUrl ? (
                                            <>
                                                <img
                                                    src={heroImageUrl}
                                                    alt={heroImageAlt}
                                                    style={{
                                                        maxWidth: '100%',
                                                        borderRadius: '4px',
                                                        marginBottom: '8px',
                                                        display: 'block',
                                                    }}
                                                />
                                                <div style={{ display: 'flex', gap: '8px' }}>
                                                    <Button variant="secondary" onClick={open}>
                                                        Replace Image
                                                    </Button>
                                                    <Button
                                                        isDestructive
                                                        variant="secondary"
                                                        onClick={() => setAttributes({
                                                            heroImageUrl: '',
                                                            heroImageAlt: ''
                                                        })}
                                                    >
                                                        Remove
                                                    </Button>
                                                </div>
                                            </>
                                        ) : (
                                            <Button variant="secondary" onClick={open}>
                                                Select Hero Image
                                            </Button>
                                        )}
                                    </div>
                                )}
                            />
                        </MediaUploadCheck>
                    </div>

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

                            <SelectControl
                                label="Display Mode"
                                value={heroImageDisplayMode}
                                options={displayModeOptions}
                                onChange={(value) => setAttributes({ heroImageDisplayMode: value })}
                            />

                            {heroImageDisplayMode === 'inline' && (
                                <>
                                    <SelectControl
                                        label="Text Wrap / Float"
                                        value={heroImageTextWrap}
                                        options={textWrapOptions}
                                        onChange={(value) => setAttributes({ heroImageTextWrap: value })}
                                        help="How text should flow around the image."
                                    />

                                    <TextControl
                                        label="Max Width"
                                        value={heroImageMaxWidth}
                                        onChange={(value) => setAttributes({ heroImageMaxWidth: value })}
                                        placeholder="40%"
                                        help="CSS value (e.g., 40%, 300px)"
                                    />
                                </>
                            )}

                            {heroImageDisplayMode === 'background' && (
                                <SelectControl
                                    label="Background Position"
                                    value={heroImageAlignment}
                                    options={alignmentOptions}
                                    onChange={(value) => setAttributes({ heroImageAlignment: value })}
                                />
                            )}

                            <div style={sectionDividerStyle}>
                                <p style={sectionLabelStyle}>Overlay</p>
                            </div>

                            <RangeControl
                                label="Overlay Opacity"
                                value={heroImageOverlayOpacity}
                                onChange={(value) => setAttributes({ heroImageOverlayOpacity: value })}
                                min={0}
                                max={100}
                                help="0 = no overlay, 100 = full overlay"
                            />

                            <SelectControl
                                label="Overlay Color"
                                value={heroImageOverlayColor}
                                options={overlayColorOptions}
                                onChange={(value) => setAttributes({ heroImageOverlayColor: value })}
                            />
                        </>
                    )}
                </PanelBody>

                {/* Section Visibility */}
                <PanelBody title="Section Visibility" initialOpen={false}>
                    <ToggleControl
                        label="Show Theme Section"
                        checked={showThemeSection}
                        onChange={(value) => setAttributes({ showThemeSection: value })}
                    />
                    <ToggleControl
                        label="Show Key Dates Section"
                        checked={showKeyDatesSection}
                        onChange={(value) => setAttributes({ showKeyDatesSection: value })}
                    />
                    <ToggleControl
                        label="Show Focus Areas Section"
                        checked={showFocusAreasSection}
                        onChange={(value) => setAttributes({ showFocusAreasSection: value })}
                    />
                    <ToggleControl
                        label="Show Practices Section"
                        checked={showPracticesSection}
                        onChange={(value) => setAttributes({ showPracticesSection: value })}
                    />
                    <ToggleControl
                        label="Show Mantra Section"
                        checked={showMantraSection}
                        onChange={(value) => setAttributes({ showMantraSection: value })}
                    />
                </PanelBody>

                {/* CTA 1 */}
                {renderCTAControls(
                    1, cta1Enabled, (v) => setAttributes({ cta1Enabled: v }),
                    cta1Position, cta1HeaderText, cta1HeaderLevel, cta1Text,
                    cta1ImageUrl, cta1ImageAlt, cta1ImageMaxWidth, cta1Url, cta1LinkType, cta1LinkText,
                    cta1ImageClickable, cta1ElementId, cta1Alignment
                )}

                {/* CTA 2 */}
                {renderCTAControls(
                    2, cta2Enabled, (v) => setAttributes({ cta2Enabled: v }),
                    cta2Position, cta2HeaderText, cta2HeaderLevel, cta2Text,
                    cta2ImageUrl, cta2ImageAlt, cta2ImageMaxWidth, cta2Url, cta2LinkType, cta2LinkText,
                    cta2ImageClickable, cta2ElementId, cta2Alignment
                )}

                {/* CTA 3 */}
                {renderCTAControls(
                    3, cta3Enabled, (v) => setAttributes({ cta3Enabled: v }),
                    cta3Position, cta3HeaderText, cta3HeaderLevel, cta3Text,
                    cta3ImageUrl, cta3ImageAlt, cta3ImageMaxWidth, cta3Url, cta3LinkType, cta3LinkText,
                    cta3ImageClickable, cta3ElementId, cta3Alignment
                )}
            </InspectorControls>

            <div {...blockProps}>
                <ServerSideRender
                    block="ezhoroscope/monthly-horoscope"
                    attributes={attributes}
                    key={[
                        attributes.sign,
                        attributes.language,
                        attributes.horoscopeDate,
                        attributes.heroImageUrl,
                        attributes.heroImageDisplayMode,
                        attributes.heroImageAlignment,
                        attributes.heroImageTextWrap,
                        attributes.heroImageOverlayOpacity,
                        attributes.heroImageOverlayColor,
                        attributes.heroImageMaxWidth,
                        attributes.suppressHeading,
                        attributes.showThemeSection,
                        attributes.showKeyDatesSection,
                        attributes.showFocusAreasSection,
                        attributes.showPracticesSection,
                        attributes.showMantraSection,
                        attributes.cta1Enabled,
                        attributes.cta1Position,
                        attributes.cta2Enabled,
                        attributes.cta2Position,
                        attributes.cta3Enabled,
                        attributes.cta3Position,
                    ].join('-')}
                />
            </div>
        </>
    );
}