import { useState } from 'react';
//@ts-ignore
import { Button, TextControl, Modal, TextareaControl, Notice, } from '@wordpress/components';
//@ts-ignore: Cannot find module '@wordpress/i18n' or its corresponding type declarations.
import { __ } from '@wordpress/i18n';

import { imageGroupUrlListDefaults } from '../defaults'
import type { ImageGroupUrlList } from '../types';
import type { AttributesCanvas2d } from '../../../v2/blocks/canvas2d/types';

function isValidUrl(url: string) {
    try {
        new URL(url);
        return true;
    } catch {
        return false;
    }
}

export default function ModalImagesUrl({ setIsOpen, attributes, setAttributes, setShow }: { setIsOpen: any, attributes: AttributesCanvas2d, setAttributes: any, setShow?: any }) {

    const [prefix, setPrefix] = useState('');
    const [suffix, setSuffix] = useState('');
    const [urls, setUrls] = useState('');
    const [error, setError] = useState<string | null>(null);
    const [showNotice, setShowNotice] = useState(false);

    const isEmpty = !prefix && !suffix && !urls.trim();

    // Get first line and preview
    const lines = urls.split('\n').map(line => line.trim()).filter(Boolean);
    const firstLine = lines[0] || __('[your line]', 'scrollsequence');
    const previewUrl = `${prefix}${firstLine}${suffix}`;

    const handleConfirm = () => {
        setShowNotice(true);
        if (lines.length === 0) return;
        for (const line of lines) {
            const fullUrl = `${prefix}${line}${suffix}`;
            if (!isValidUrl(fullUrl)) {
                setError(fullUrl);
                return;
            }
        }
        setError(null);

        // construct the new media group from the data
        const newMediaGroupChecked : ImageGroupUrlList = {
            ...imageGroupUrlListDefaults,
            prefix,
            suffix,
            images: lines,
        }

        console.log('New media group to add:', newMediaGroupChecked);

        // add a new media group at the end of the array inside mediaGroups
        const newMediaGroups = [...attributes.mediaGroups];
        newMediaGroups.push(newMediaGroupChecked);
        setAttributes({ mediaGroups: newMediaGroups });

        setIsOpen(false);
        // close the adder if we have it
        if (setShow) {
            setShow('canvas');
        }
    };

    // Colors
    const prefixColor = '#2171b1';
    const lineColor = error ? '#d63638' : '#333';
    const suffixColor = '#2ca642';

    return (
        <Modal title={__("Add Images by URL", "scrollsequence")} shouldCloseOnClickOutside={false} onRequestClose={() => setIsOpen(false)}>
            <TextControl
                label={__("URL Prefix (optional)", "scrollsequence")}
                help={__('Prefix added to each line', 'scrollsequence')}
                placeholder="https://example.com/imgs/image"
                value={prefix}
                onChange={setPrefix}
            />
            <TextareaControl
                label={__("URL List", "scrollsequence")}
                help={__('Enter one URL per line', 'scrollsequence')}
                placeholder={`0001\n0002\n0003`}
                value={urls}
                onChange={setUrls}
            />
            <TextControl
                label={__("URL Suffix (optional)", "scrollsequence")}
                help={__('Suffix added to each line', 'scrollsequence')}
                placeholder=".jpg"
                value={suffix}
                onChange={setSuffix}
            />

            {/* Always show preview */}
            <div style={{ margin: '1em 0 1em 0' }}>
                <p>
                    {__('How your URL is constructed:', 'scrollsequence')}
                </p>
                <span style={{ background: '#f8f8f8', padding: '2px 6px', borderRadius: '4px', display: 'inline-block', marginTop: '0.5em' }}>
                    <span style={{ color: prefixColor, fontWeight: 600 }}>{prefix}</span>
                    <span style={{ color: lineColor, fontWeight: 600 }}>{firstLine}</span>
                    <span style={{ color: suffixColor, fontWeight: 600 }}>{suffix}</span>
                </span>
            </div>

            {/* Show notice only after confirm */}
            {showNotice && error && (
                <Notice status="warning" isDismissible={false} style={{ marginBottom: '1em' }}>
                    <strong>{__('Invalid URL:', 'scrollsequence')}</strong>
                    <div style={{ color: '#d63638', fontWeight: 600 }}>{error}</div>
                </Notice>
            )}
            {showNotice && !error && (
                <Notice status="success" isDismissible={false} style={{ marginBottom: '1em' }}>
                    <strong>{__('All URLs are valid!', 'scrollsequence')}</strong>
                </Notice>
            )}

            <Button
                variant="secondary"
                onClick={handleConfirm}
                disabled={isEmpty}
                style={{ marginTop: '1em' }}
            >
                {__('Confirm', 'scrollsequence')}
            </Button>
        </Modal>
    );
}