import {__} from "@wordpress/i18n";

/**
 * UrlInput Component
 * Validates URL format
 *
 * @param {Object} props Component props
 * @param {React.Ref} props.textareaRef Textarea ref
 * @param {string} props.text Current text value
 * @param {Function} props.onTextChange Text change handler
 * @param {Function} props.onKeyDown Key down handler
 * @param {boolean} props.isValid Is input valid
 * @param {string} props.placeholder Custom placeholder
 */
export default function UrlInput({
                                     textareaRef,
                                     text,
                                     onTextChange,
                                     onKeyDown,
                                     isValid,
                                     placeholder
                                 }) {
    const hasError = !isValid && text.trim().length > 0;
    const placeholderText = placeholder || __('Enter a URL...', 'limb-chatbot');

    return (
        <input
            ref={textareaRef}
            type="url"
            className={`lbaic-textarea${hasError ? ' lbaic-textarea-invalid' : ''}`}
            placeholder={placeholderText}
            value={text}
            onChange={onTextChange}
            onKeyDown={onKeyDown}
            autoComplete="off"
        />
    );
}

/**
 * Validate URL input
 *
 * @param {string} value Input value
 * @returns {boolean} Is valid URL
 */
export const validateUrlInput = (value) => {
    if (value.trim().length === 0) {
        return true; // Empty input is "valid" (just can't send)
    }

    const trimmedValue = value.trim();

    // URL shouldn't contain spaces
    if (trimmedValue.includes(' ')) {
        return false;
    }

    // URL must start with http:// or https://
    if (!trimmedValue.startsWith('http://') && !trimmedValue.startsWith('https://')) {
        return false;
    }

    // Try to parse as URL with protocol
    try {
        const url = new URL(trimmedValue);
        return isValidHttpUrl(url);
    } catch {
        return false;
    }
};

/**
 * Check if URL object is a valid HTTP(S) URL
 *
 * @param {URL} url URL object to validate
 * @returns {boolean} Is valid HTTP(S) URL
 */
function isValidHttpUrl(url) {
    // Must be http or https
    if (url.protocol !== 'http:' && url.protocol !== 'https:') {
        return false;
    }

    // Must have a hostname
    if (!url.hostname) {
        return false;
    }

    // Check for IPv4 address
    const ipv4Regex = /^(\d{1,3}\.){3}\d{1,3}$/;
    if (ipv4Regex.test(url.hostname)) {
        // Validate IPv4 octets are in range 0-255
        const octets = url.hostname.split('.');
        return octets.every(octet => {
            const num = parseInt(octet, 10);
            return num >= 0 && num <= 255;
        });
    }

    // Check for IPv6 address (enclosed in brackets in URL)
    if (url.hostname.startsWith('[') && url.hostname.endsWith(']')) {
        return true; // URL constructor already validated it
    }

    // For domain names, validate labels
    const labels = url.hostname.replace(/\.$/, '').split('.');

    // Must have at least 2 labels (domain.tld)
    if (labels.length < 2) {
        return false;
    }

    // Check for invalid patterns: consecutive dots, leading dot
    if (/\.\./.test(url.hostname) || url.hostname.startsWith('.')) {
        return false;
    }

    // Validate each label in the domain
    for (const label of labels) {
        // Label must not be empty
        if (!label) {
            return false;
        }

        // Label must not start or end with hyphen
        if (label.startsWith('-') || label.endsWith('-')) {
            return false;
        }

        // Label must be alphanumeric with hyphens only
        if (!/^[a-zA-Z0-9-]+$/.test(label)) {
            return false;
        }

        // Label length must be 63 characters or less (DNS limit)
        if (label.length > 63) {
            return false;
        }
    }

    // Check TLD (last label) has at least 2 characters and is not all numeric
    const tld = labels[labels.length - 1];
    if (tld.length < 2 || /^\d+$/.test(tld)) {
        return false;
    }

    return true;
}
