import { __ } from "@wordpress/i18n";
import { 
    PanelBody, 
    TextControl,
    SelectControl,
    Notice
} from "@wordpress/components";
import { useState } from '@wordpress/element';
import { useSelect } from '@wordpress/data';
import { store as coreDataStore } from '@wordpress/core-data';

const UrlRedirectPanel = ({ redirectUrl, setRedirectUrl }) => {
    const [urlError, setUrlError] = useState(false);
    const [tempUrl, setTempUrl] = useState(redirectUrl);

    const { postGroups } = useSelect((select) => {
        const postTypes = select(coreDataStore).getPostTypes();
        const groups = [];

        if (postTypes) {
            postTypes
                .filter(type => type.viewable && type.slug !== 'attachment')
                .forEach(type => {
                    const items = select(coreDataStore).getEntityRecords('postType', type.slug, {
                        per_page: -1,
                        orderby: 'title',
                        order: 'asc',
                        status: 'publish',
                    });

                    if (items && items.length > 0) {
                        groups.push({
                            label: type.labels.name,
                            options: items.map(item => ({
                                label: item.title.rendered,
                                value: item.link
                            }))
                        });
                    }
                });
        }

        return { postGroups: groups };
    }, []);

    const isValidUrl = (url) => {
        if (!url) return true;
        const urlPattern = /^(https?:\/\/)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*\/?$/;
        return urlPattern.test(url);
    };

    const handleUrlChange = (value) => {
        setTempUrl(value);
        
        if (isValidUrl(value)) {
            setUrlError(false);
            setRedirectUrl(value);
        } else {
            setUrlError(true);
        }
    };

    const handleSelectChange = (value) => {
        if (value) {
            setTempUrl(value);
            setUrlError(false);
            setRedirectUrl(value);
        }
    };

    return (
        <PanelBody title="URL Redirect">
            <TextControl
                label="URL"
                value={tempUrl}
                onChange={handleUrlChange}
            />
            <p>- or find content -</p>
            <SelectControl
                label="Find content"
                value=""
                onChange={handleSelectChange}
            >
                <option value="">Select content</option>
                {postGroups.map((group, index) => (
                    <optgroup key={index} label={group.label}>
                        {group.options.map((option, optIndex) => (
                            <option key={`${index}-${optIndex}`} value={option.value}>
                                {option.label}
                            </option>
                        ))}
                    </optgroup>
                ))}
            </SelectControl>
            {urlError && (
                <Notice status="error" isDismissible={false}>
                    Please enter a valid URL (e.g. https://example.com)
                </Notice>
            )}
        </PanelBody>
    );
};

export default UrlRedirectPanel; 