import './style.css';
import {
    InspectorControls,
    useBlockProps
} from '@wordpress/block-editor';
import {
    PanelBody,
    TextControl,
    RangeControl,
    ToggleControl,
    SelectControl,
    Button,
    Spinner,
    ColorPicker,
    __experimentalText as Text
} from '@wordpress/components';
import { useState } from '@wordpress/element';
import { ezhp_t, ezhp_getHouseSystemName, EZHP_HOUSE_SYSTEMS } from './i18n';

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

    const {
        language = 'en',
        houseSystem = 'placidus',
        includeTransits = true,
        transitDateTime = '',
        backgroundColor,
        transparentBackground,
        circleColor,
        pointsColor,
        signsColor,
        cuspsColor,
        lineColor,
        axisFontColor,
        legendFontColor,
        legendBorderColor,
        colorAries,
        colorTaurus,
        colorGemini,
        colorCancer,
        colorLeo,
        colorVirgo,
        colorLibra,
        colorScorpio,
        colorSagittarius,
        colorCapricorn,
        colorAquarius,
        colorPisces,
        aspectColorConjunction,
        aspectColorOpposition,
        aspectColorTrine,
        aspectColorSquare,
        aspectColorSextile,
        aspectColorQuincunx,
        aspectOrbitConjunction,
        aspectOrbitOpposition,
        aspectOrbitTrine,
        aspectOrbitSquare,
        aspectOrbitSextile,
        aspectOrbitQuincunx,
        symbolScale,
        pointsTextSize,
        pointsStroke,
        signsStroke,
        circleStroke,
        cuspsStroke,
        axisStroke,
        margin,
        padding,
        collisionRadius,
        indoorCircleRadiusRatio,
        innerCircleRadiusRatio,
        rulerRadius,
        shiftInDegrees,
        strokeOnly,
        addClickArea,
        showDignitiesText,
        debug
    } = attributes;

    // Editor-only states
    const [loading, setLoading] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [editorLocation, setEditorLocation] = useState('');
    const [editorDateTime, setEditorDateTime] = useState('');
    const [errorMessage, setErrorMessage] = useState('');
    const [editorTransitDateTime, setEditorTransitDateTime] = useState(() => {
        const now = new Date();
        return new Date(now.getTime() - now.getTimezoneOffset() * 60000).toISOString().slice(0, 16);
    });

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

    // Build style settings object from attributes
    function buildStyleSettings() {
        return {
            houseSystem,
            backgroundColor: transparentBackground ? 'transparent' : backgroundColor,
            transparentBackground,
            circleColor,
            pointsColor,
            signsColor,
            cuspsColor,
            lineColor,
            axisFontColor,
            legendFontColor,
            legendBorderColor,
            colorAries,
            colorTaurus,
            colorGemini,
            colorCancer,
            colorLeo,
            colorVirgo,
            colorLibra,
            colorScorpio,
            colorSagittarius,
            colorCapricorn,
            colorAquarius,
            colorPisces,
            aspectColors: {
                Conjunction: aspectColorConjunction,
                Opposition: aspectColorOpposition,
                Trine: aspectColorTrine,
                Square: aspectColorSquare,
                Sextile: aspectColorSextile,
                Quincunx: aspectColorQuincunx
            },
            aspectConfigs: {
                Conjunction: { color: aspectColorConjunction, orbit: aspectOrbitConjunction },
                Opposition: { color: aspectColorOpposition, orbit: aspectOrbitOpposition },
                Trine: { color: aspectColorTrine, orbit: aspectOrbitTrine },
                Square: { color: aspectColorSquare, orbit: aspectOrbitSquare },
                Sextile: { color: aspectColorSextile, orbit: aspectOrbitSextile },
                Quincunx: { color: aspectColorQuincunx, orbit: aspectOrbitQuincunx }
            },
            symbolScale,
            pointsTextSize,
            pointsStroke,
            signsStroke,
            circleStrong: circleStroke,
            cuspsStroke,
            axisStroke,
            margin,
            padding,
            collisionRadius,
            indoorCircleRadiusRatio,
            innerCircleRadiusRatio,
            rulerRadius,
            shiftInDegrees,
            strokeOnly,
            addClickArea,
            showDignitiesText,
            debug
        };
    }

    // Fetch preview chart
    async function fetchChart() {
        if (!editorLocation || !editorDateTime) {
            setErrorMessage(ezhp_t(language, 'pleaseEnterDetails'));
            return;
        }

        setLoading(true);
        setErrorMessage('');

        try {
            const payload = {
                location: editorLocation,
                birthDateTimeLocal: editorDateTime,
                language: language,
                includeTransits: includeTransits,
                styleSettings: buildStyleSettings()
            };
            
            // Only include transitDateTime if provided
            if (editorTransitDateTime) {
                payload.transitDateTime = editorTransitDateTime;
            }

            const response = await wp.apiFetch({
                path: 'ezhp/v1/birth-chart',
                method: 'POST',
                data: payload
            });

            if (response?.image) {
                setPreviewImage(response.image);
            } else if (response?.error) {
                setErrorMessage(response.error);
                setPreviewImage('');
            } else {
                setErrorMessage(ezhp_t(language, 'errorLoading'));
                setPreviewImage('');
            }
        } catch (e) {
            setErrorMessage(ezhp_t(language, 'errorLoading'));
            setPreviewImage('');
        }

        setLoading(false);
    }

    // Color control helper component
    const ColorControl = ({ label, value, onChange }) => (
        <div style={{ marginBottom: '16px' }}>
            <Text style={{ display: 'block', marginBottom: '4px', fontWeight: 500 }}>{label}</Text>
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                <input
                    type="color"
                    value={value}
                    onChange={(e) => onChange(e.target.value)}
                    style={{ width: '40px', height: '30px', border: '1px solid #ccc', borderRadius: '4px', cursor: 'pointer' }}
                />
                <TextControl
                    value={value}
                    onChange={onChange}
                    style={{ flex: 1 }}
                    __nextHasNoMarginBottom
                />
            </div>
        </div>
    );

    return (
        <>
            <InspectorControls>
                {/* Basic Settings */}
                <PanelBody title="Basic Settings" initialOpen={true}>
                    <TextControl
                        label="Language"
                        value={language}
                        onChange={(value) => setAttributes({ language: value })}
                    />
                    <SelectControl
                        label={ezhp_t(language, 'selectHouseSystem')}
                        value={houseSystem}
                        options={Object.keys(EZHP_HOUSE_SYSTEMS.en).map((key) => ({
                            label: ezhp_getHouseSystemName(language, key),
                            value: key
                        }))}
                        onChange={(value) => setAttributes({ houseSystem: value })}
                    />
                </PanelBody>

                {/* Chart Colors */}
                <PanelBody title="Chart Colors" initialOpen={false}>
                    <ToggleControl
                        label="Transparent Background"
                        help={transparentBackground ? 'Background will be transparent (for overlays)' : 'Background will use the color below'}
                        checked={transparentBackground}
                        onChange={(value) => setAttributes({ transparentBackground: value })}
                    />
                    {!transparentBackground && (
                        <ColorControl
                            label="Background Color"
                            value={backgroundColor}
                            onChange={(value) => setAttributes({ backgroundColor: value })}
                        />
                    )}
                    <ColorControl
                        label="Circle Color"
                        value={circleColor}
                        onChange={(value) => setAttributes({ circleColor: value })}
                    />
                    <ColorControl
                        label="Points Color"
                        value={pointsColor}
                        onChange={(value) => setAttributes({ pointsColor: value })}
                    />
                    <ColorControl
                        label="Signs Color"
                        value={signsColor}
                        onChange={(value) => setAttributes({ signsColor: value })}
                    />
                    <ColorControl
                        label="Cusps Color"
                        value={cuspsColor}
                        onChange={(value) => setAttributes({ cuspsColor: value })}
                    />
                    <ColorControl
                        label="Line Color"
                        value={lineColor}
                        onChange={(value) => setAttributes({ lineColor: value })}
                    />
                    {/* Axis Font Color - hidden from editor but still functional
                    <ColorControl
                        label="Axis Font Color"
                        value={axisFontColor}
                        onChange={(value) => setAttributes({ axisFontColor: value })}
                    />
                    */}
                    <ColorControl
                        label="Legend Font Color"
                        value={legendFontColor}
                        onChange={(value) => setAttributes({ legendFontColor: value })}
                    />
                    <ColorControl
                        label="Legend Border Color"
                        value={legendBorderColor}
                        onChange={(value) => setAttributes({ legendBorderColor: value })}
                    />
                </PanelBody>

                {/* Zodiac Sign Colors */}
                <PanelBody title="Zodiac Sign Colors" initialOpen={false}>
                    <ColorControl
                        label="Aries"
                        value={colorAries}
                        onChange={(value) => setAttributes({ colorAries: value })}
                    />
                    <ColorControl
                        label="Taurus"
                        value={colorTaurus}
                        onChange={(value) => setAttributes({ colorTaurus: value })}
                    />
                    <ColorControl
                        label="Gemini"
                        value={colorGemini}
                        onChange={(value) => setAttributes({ colorGemini: value })}
                    />
                    <ColorControl
                        label="Cancer"
                        value={colorCancer}
                        onChange={(value) => setAttributes({ colorCancer: value })}
                    />
                    <ColorControl
                        label="Leo"
                        value={colorLeo}
                        onChange={(value) => setAttributes({ colorLeo: value })}
                    />
                    <ColorControl
                        label="Virgo"
                        value={colorVirgo}
                        onChange={(value) => setAttributes({ colorVirgo: value })}
                    />
                    <ColorControl
                        label="Libra"
                        value={colorLibra}
                        onChange={(value) => setAttributes({ colorLibra: value })}
                    />
                    <ColorControl
                        label="Scorpio"
                        value={colorScorpio}
                        onChange={(value) => setAttributes({ colorScorpio: value })}
                    />
                    <ColorControl
                        label="Sagittarius"
                        value={colorSagittarius}
                        onChange={(value) => setAttributes({ colorSagittarius: value })}
                    />
                    <ColorControl
                        label="Capricorn"
                        value={colorCapricorn}
                        onChange={(value) => setAttributes({ colorCapricorn: value })}
                    />
                    <ColorControl
                        label="Aquarius"
                        value={colorAquarius}
                        onChange={(value) => setAttributes({ colorAquarius: value })}
                    />
                    <ColorControl
                        label="Pisces"
                        value={colorPisces}
                        onChange={(value) => setAttributes({ colorPisces: value })}
                    />
                </PanelBody>

                {/* Aspect Colors */}
                <PanelBody title="Aspect Colors" initialOpen={false}>
                    <ColorControl
                        label="Conjunction"
                        value={aspectColorConjunction}
                        onChange={(value) => setAttributes({ aspectColorConjunction: value })}
                    />
                    <ColorControl
                        label="Opposition"
                        value={aspectColorOpposition}
                        onChange={(value) => setAttributes({ aspectColorOpposition: value })}
                    />
                    <ColorControl
                        label="Trine"
                        value={aspectColorTrine}
                        onChange={(value) => setAttributes({ aspectColorTrine: value })}
                    />
                    <ColorControl
                        label="Square"
                        value={aspectColorSquare}
                        onChange={(value) => setAttributes({ aspectColorSquare: value })}
                    />
                    <ColorControl
                        label="Sextile"
                        value={aspectColorSextile}
                        onChange={(value) => setAttributes({ aspectColorSextile: value })}
                    />
                    <ColorControl
                        label="Quincunx"
                        value={aspectColorQuincunx}
                        onChange={(value) => setAttributes({ aspectColorQuincunx: value })}
                    />
                </PanelBody>

                {/* Aspect Orbits - hidden from editor but still functional
                <PanelBody title="Aspect Orbits" initialOpen={false}>
                    <RangeControl
                        label="Conjunction Orbit"
                        value={aspectOrbitConjunction}
                        onChange={(value) => setAttributes({ aspectOrbitConjunction: value })}
                        min={1}
                        max={15}
                        step={0.5}
                    />
                    <RangeControl
                        label="Opposition Orbit"
                        value={aspectOrbitOpposition}
                        onChange={(value) => setAttributes({ aspectOrbitOpposition: value })}
                        min={1}
                        max={15}
                        step={0.5}
                    />
                    <RangeControl
                        label="Trine Orbit"
                        value={aspectOrbitTrine}
                        onChange={(value) => setAttributes({ aspectOrbitTrine: value })}
                        min={1}
                        max={15}
                        step={0.5}
                    />
                    <RangeControl
                        label="Square Orbit"
                        value={aspectOrbitSquare}
                        onChange={(value) => setAttributes({ aspectOrbitSquare: value })}
                        min={1}
                        max={15}
                        step={0.5}
                    />
                    <RangeControl
                        label="Sextile Orbit"
                        value={aspectOrbitSextile}
                        onChange={(value) => setAttributes({ aspectOrbitSextile: value })}
                        min={1}
                        max={15}
                        step={0.5}
                    />
                    <RangeControl
                        label="Quincunx Orbit"
                        value={aspectOrbitQuincunx}
                        onChange={(value) => setAttributes({ aspectOrbitQuincunx: value })}
                        min={1}
                        max={15}
                        step={0.5}
                    />
                </PanelBody>
                */}

                {/* Sizing & Strokes */}
                <PanelBody title="Sizing & Strokes" initialOpen={false}>
                    <RangeControl
                        label="Symbol Scale"
                        value={symbolScale}
                        onChange={(value) => setAttributes({ symbolScale: value })}
                        min={0.5}
                        max={3}
                        step={0.1}
                    />
                    <RangeControl
                        label="Points Text Size"
                        value={pointsTextSize}
                        onChange={(value) => setAttributes({ pointsTextSize: value })}
                        min={4}
                        max={20}
                        step={1}
                    />
                    <RangeControl
                        label="Points Stroke"
                        value={pointsStroke}
                        onChange={(value) => setAttributes({ pointsStroke: value })}
                        min={0.5}
                        max={5}
                        step={0.1}
                    />
                    <RangeControl
                        label="Signs Stroke"
                        value={signsStroke}
                        onChange={(value) => setAttributes({ signsStroke: value })}
                        min={0.5}
                        max={5}
                        step={0.1}
                    />
                    <RangeControl
                        label="Circle Stroke"
                        value={circleStroke}
                        onChange={(value) => setAttributes({ circleStroke: value })}
                        min={0.5}
                        max={5}
                        step={0.1}
                    />
                    <RangeControl
                        label="Cusps Stroke"
                        value={cuspsStroke}
                        onChange={(value) => setAttributes({ cuspsStroke: value })}
                        min={0.5}
                        max={5}
                        step={0.1}
                    />
                    <RangeControl
                        label="Axis Stroke"
                        value={axisStroke}
                        onChange={(value) => setAttributes({ axisStroke: value })}
                        min={0.5}
                        max={5}
                        step={0.1}
                    />
                </PanelBody>

                {/* Layout */}
                <PanelBody title="Layout" initialOpen={false}>
                    <RangeControl
                        label="Margin"
                        value={margin}
                        onChange={(value) => setAttributes({ margin: value })}
                        min={0}
                        max={100}
                        step={5}
                    />
                    <RangeControl
                        label="Padding"
                        value={padding}
                        onChange={(value) => setAttributes({ padding: value })}
                        min={0}
                        max={50}
                        step={2}
                    />
                    <RangeControl
                        label="Collision Radius"
                        value={collisionRadius}
                        onChange={(value) => setAttributes({ collisionRadius: value })}
                        min={5}
                        max={30}
                        step={1}
                    />
                    <RangeControl
                        label="Indoor Circle Radius Ratio"
                        value={indoorCircleRadiusRatio}
                        onChange={(value) => setAttributes({ indoorCircleRadiusRatio: value })}
                        min={1}
                        max={10}
                        step={0.5}
                    />
                    <RangeControl
                        label="Inner Circle Radius Ratio"
                        value={innerCircleRadiusRatio}
                        onChange={(value) => setAttributes({ innerCircleRadiusRatio: value })}
                        min={1}
                        max={15}
                        step={0.5}
                    />
                    <RangeControl
                        label="Ruler Radius"
                        value={rulerRadius}
                        onChange={(value) => setAttributes({ rulerRadius: value })}
                        min={1}
                        max={10}
                        step={0.5}
                    />
                    <RangeControl
                        label="Shift In Degrees"
                        value={shiftInDegrees}
                        onChange={(value) => setAttributes({ shiftInDegrees: value })}
                        min={0}
                        max={360}
                        step={15}
                    />
                </PanelBody>

                {/* Toggle Options */}
                <PanelBody title="Display Options" initialOpen={false}>
                    <ToggleControl
                        label="Stroke Only"
                        checked={strokeOnly}
                        onChange={(value) => setAttributes({ strokeOnly: value })}
                    />
                    <ToggleControl
                        label="Add Click Area"
                        checked={addClickArea}
                        onChange={(value) => setAttributes({ addClickArea: value })}
                    />
                    <ToggleControl
                        label="Show Dignities Text"
                        checked={showDignitiesText}
                        onChange={(value) => setAttributes({ showDignitiesText: value })}
                    />
                    <ToggleControl
                        label="Debug Mode"
                        checked={debug}
                        onChange={(value) => setAttributes({ debug: value })}
                    />
                </PanelBody>
            </InspectorControls>

            {/* Editor UI */}
            <div {...blockProps}>
                <div className="birth-chart-editor-ui" style={{ marginBottom: '15px' }}>
                    <div style={{ marginBottom: '10px' }}>
                        <label style={{ fontWeight: '600', display: 'block', marginBottom: '5px' }}>
                            {ezhp_t(language, 'enterLocation')}
                        </label>
                        <input
                            type="text"
                            value={editorLocation}
                            onChange={(e) => setEditorLocation(e.target.value)}
                            placeholder="e.g., New York, NY"
                            style={{
                                width: '100%',
                                padding: '8px',
                                borderRadius: '4px',
                                border: '1px solid #ccc'
                            }}
                        />
                    </div>

                    <div style={{ marginBottom: '10px' }}>
                        <label style={{ fontWeight: '600', display: 'block', marginBottom: '5px' }}>
                            {ezhp_t(language, 'enterBirthDateTime')}
                        </label>
                        <input
                            type="datetime-local"
                            value={editorDateTime}
                            onChange={(e) => setEditorDateTime(e.target.value)}
                            style={{
                                width: '100%',
                                padding: '8px',
                                borderRadius: '4px',
                                border: '1px solid #ccc'
                            }}
                        />
                    </div>

                    <div style={{ marginBottom: '10px' }}>
                        <label style={{ fontWeight: '600', display: 'block', marginBottom: '5px' }}>
                            {ezhp_t(language, 'selectHouseSystem')}
                        </label>
                        <select
                            value={houseSystem}
                            onChange={(e) => setAttributes({ houseSystem: e.target.value })}
                            style={{
                                width: '100%',
                                padding: '8px',
                                borderRadius: '4px',
                                border: '1px solid #ccc'
                            }}
                        >
                            {Object.keys(EZHP_HOUSE_SYSTEMS.en).map((key) => (
                                <option key={key} value={key}>
                                    {ezhp_getHouseSystemName(language, key)}
                                </option>
                            ))}
                        </select>
                    </div>

                    <div style={{ marginBottom: '10px' }}>
                        <label style={{ fontWeight: '600', display: 'flex', alignItems: 'center', gap: '8px' }}>
                            <input
                                type="checkbox"
                                checked={includeTransits}
                                onChange={(e) => setAttributes({ includeTransits: e.target.checked })}
                            />
                            {ezhp_t(language, 'showTransits')}
                        </label>
                    </div>

                    {includeTransits && (
                        <div style={{ marginBottom: '10px' }}>
                            <label style={{ fontWeight: '600', display: 'block', marginBottom: '5px' }}>
                                {ezhp_t(language, 'transitDateTime')}
                            </label>
                            <input
                                type="datetime-local"
                                value={editorTransitDateTime}
                                onChange={(e) => setEditorTransitDateTime(e.target.value)}
                                style={{
                                    width: '100%',
                                    padding: '8px',
                                    borderRadius: '4px',
                                    border: '1px solid #ccc'
                                }}
                            />
                        </div>
                    )}

                    <Button
                        variant="primary"
                        onClick={fetchChart}
                        disabled={!editorLocation || !editorDateTime}
                    >
                        {ezhp_t(language, 'generateChart')}
                    </Button>
                </div>

                {/* Preview Area */}
                <div className="birth-chart-preview" style={{ padding: '10px', textAlign: 'center' }}>
                    {loading && <Spinner />}
                    {errorMessage && !loading && (
                        <div style={{ color: '#d63638', padding: '10px' }}>{errorMessage}</div>
                    )}
                    {!loading && previewImage && (
                        <img
                            src={previewImage}
                            alt="Birth Chart Preview"
                            style={{ maxWidth: '100%', height: 'auto', borderRadius: '8px' }}
                        />
                    )}
                    {!loading && !previewImage && !errorMessage && (
                        <div style={{ color: '#757575', padding: '20px' }}>
                            {ezhp_t(language, 'previewPlaceholder')}
                        </div>
                    )}
                </div>
            </div>
        </>
    );
}