import classNames from 'classnames'
import { HTMLInputTypeAttribute, HTMLProps, ReactNode, useId } from 'react'
import Field from '../field'
import './style.scss'

interface TextInputBaseProps {
	type?: HTMLInputTypeAttribute
	isInvalid?: boolean
	isLoading?: boolean
	required?: boolean
	className?: string
	id: string
	field: HTMLProps<HTMLInputElement>
}

function TextInputBase({
	type,
	isInvalid,
	isLoading,
	className,
	id,
	field,
	...rest
}: TextInputBaseProps) {
	return (
		<input
			id={id}
			type={type}
			className={classNames(
				'hds-form-text-input',
				'hds-typography-body-200',
				'hds-font-weight-regular',
				{
					['hds-form-text-input--is-invalid']: isInvalid,
					['hds-form-text-input--is-loading']: isLoading,
				},
				className
			)}
			{...field}
			{...rest}
		/>
	)
}

interface TextInputFieldProps {
	type?: HTMLInputTypeAttribute
	isInvalid?: boolean
	isLoading?: boolean
	isRequired?: boolean
	isOptional?: boolean
	id?: string
	label?: ReactNode
	helperText?: ReactNode
	error?: ReactNode
	field: HTMLProps<HTMLInputElement>
	className?: string
}

export default function TextInputField({
	type = 'text',
	isInvalid,
	isLoading,
	isRequired,
	isOptional,
	id,
	label,
	helperText,
	error,
	field,
	className,
	...rest
}: TextInputFieldProps) {
	const generatedId = useId()
	const inputId = id ?? generatedId

	return (
		<Field
			label={label}
			helperText={helperText}
			error={error}
			isRequired={isRequired}
			isOptional={isOptional}
			id={inputId}
			layout="vertical"
			className={className}
		>
			<TextInputBase
				id={inputId}
				type={type}
				isInvalid={isInvalid}
				isLoading={isLoading}
				required={isRequired}
				field={field}
				{...rest}
			/>
		</Field>
	)
}
