---
/**
 * DEFAULT INPUT COMPONENT
 */
import type { InputType } from '@astro-reactive/common';
import type { FormControl } from '../../core/form-control';

export interface Props {
	control: FormControl;
	readOnly?: boolean;
}

const { control, readOnly } = Astro.props;

const { validators = [] } = control;

const hasError: boolean = control.errors?.some((error) => error.category === 'error');
const hasWarn: boolean = control.errors?.some((error) => error.category === 'warn');
const hasInfo: boolean = control.errors?.some((error) => error.category === 'info');

// @ts-ignore
const validatorAttributes: Record<string, string> = validators.reduce((prev, val) => {
	const validator = typeof val === 'string' ? val : val.validator;
	const split: string[] = validator.split(':');
	const label: string = `data-${split[0]}` || 'invalid';
	const value: string | null = split.length > 1 ? split[1] ?? null : 'true';
	const category = typeof val === 'string' ? 'error' : val.category || 'error';
	const categoryLabel: string = `data-${split[0]}-category`;

	return {
		...prev,
		[label]: value,
		[categoryLabel]: category,
	};
}, {});
---

<input
	name={control.name}
	id={control.id}
	type={control.type as InputType}
	value={control.value?.toString()}
	checked={control.value === 'checked'}
	placeholder={control.placeholder}
	data-label={control.label}
	data-validator-error={hasError ? hasError.toString() : null}
	data-validator-warn={hasWarn ? hasWarn.toString() : null}
	data-validator-info={hasInfo ? hasInfo.toString() : null}
	data-validation-on={control.triggerValidationOn ? control.triggerValidationOn  : null}
	readonly={readOnly || null}
	disabled={(readOnly || null) && control.type === 'checkbox'}
	{...validatorAttributes}
/>
