import { forwardRef } from 'react';
import TextAreaInput from '@/components/Inputs/TextAreaInput';
import ButtonInput from '@/components/Inputs/ButtonInput';
import {
	buildControllerFieldProps,
	renderWrappedField
} from '@/components/Fields/fieldHelpers';
import { __ } from '@wordpress/i18n';

const parseIPList = ( value ) => {
	const normalized = ( value || '' )
		.replace( /\r\n/g, '\n' )
		.replace( /\r/g, '\n' );
	const list = normalized
		.split( '\n' )
		.map( ( line ) => line.trim() )
		.filter( ( line ) => '' !== line );
	return { normalized, list };
};

/**
 * IpBlockField component
 */
const IpBlockField = forwardRef(
	({ field, fieldState, label, help, context, className, ...props }, ref ) => {
		const { inputId, error, wrapperProps } = buildControllerFieldProps({
			field,
			fieldState,
			props,
			label,
			help,
			context,
			className
		});
		const ip = burst_settings.current_ip;

		// Ensure value is always a string
		const value = field.value || '';

		const handleChange = ( e ) => {

			// Don't prevent or modify the input - allow line breaks
			const newValue = e.target.value;
			field.onChange( newValue );
		};

		const handleAddIP = () => {
			if ( ! ip ) {
				return;
			}

			const { normalized: normalizedValue, list: ipList } = parseIPList( value );

			// Add IP to the list
			let updatedIPList;

			if ( 0 === ipList.length ) {

				// If list is empty, just add the IP
				updatedIPList = ip;
			} else {

				// Properly append the new IP with a newline
				if ( '' === normalizedValue.trim() ) {

					// If empty or just whitespace
					updatedIPList = ip;
				} else if ( normalizedValue.endsWith( '\n' ) ) {

					// If already ends with newline
					updatedIPList = normalizedValue + ip;
				} else {

					// Add a newline then the IP
					updatedIPList = normalizedValue + '\n' + ip;
				}
			}

			field.onChange( updatedIPList );
		};

		// Check if the "Add current IP" button should be disabled
		// Compare with normalized IPs to avoid false negatives due to whitespace
		const ipExists = () => {
			if ( ! ip ) {
				return true;
			}

			const { list: ipList } = parseIPList( value );
			return ipList.includes( ip );
		};

		return renderWrappedField({
			wrapperProps,
			InputComponent: () => (
				<div className="w-full flex flex-col gap-2">
					<TextAreaInput
						ref={ref}
						id={inputId}
						placeholder={'127.0.0.1\n192.168.0.1'}
						aria-invalid={!! error}
						onChange={handleChange}
						value={value}
						rows={4}
						{...props}
					/>
					<ButtonInput
						onClick={handleAddIP}
						disabled={! ip || ipExists()}
						btnVariant="tertiary"
						size="md"
					>
						{__( 'Add current IP address', 'burst-statistics' )}
					</ButtonInput>
				</div>
			),
			inputProps: {}
		});
	}
);

IpBlockField.displayName = 'IpBlockField';
export default IpBlockField;
