import {
	useId,
	type ComponentProps,
	type HTMLProps,
	type ReactNode,
} from 'react'
import Field from '../field'
import './style.scss'
import Fieldset from '../fieldset'
import classNames from 'classnames'

interface CheckboxBaseProps {
	id: string
	required?: boolean
	field: HTMLProps<HTMLInputElement>
}

export function CheckboxBase({ id, required, field }: CheckboxBaseProps) {
	return (
		<input
			id={id}
			type="checkbox"
			className="hds-form-checkbox"
			required={required}
			{...field}
		/>
	)
}

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

export default function CheckboxField({
	isInvalid,
	isLoading,
	isRequired,
	isOptional,
	id,
	label,
	helperText,
	error,
	field,
	className,
	...rest
}: CheckboxFieldProps) {
	const generatedId = useId()
	const inputId = id ?? generatedId

	return (
		<Field
			label={label}
			helperText={helperText}
			error={error}
			isRequired={isRequired}
			isOptional={isOptional}
			id={inputId}
			layout="flag"
			className={className}
		>
			<CheckboxBase
				id={inputId}
				required={isRequired}
				field={field}
				{...rest}
			/>
		</Field>
	)
}

interface CheckboxGroupProps extends ComponentProps<typeof Fieldset> {
	children: ReactNode
}

function CheckboxGroup({
	layout = 'vertical',
	legend,
	isOptional,
	isRequired,
	children,
}: CheckboxGroupProps) {
	return (
		<Fieldset
			layout={layout}
			legend={legend}
			isOptional={isOptional}
			isRequired={isRequired}
		>
			{children}
		</Fieldset>
	)
}

function CheckboxGroupField(props: CheckboxFieldProps) {
	return (
		<CheckboxField
			{...props}
			className={classNames('hds-form-group__control-field', props.className)}
		/>
	)
}

export const Group = {
	Root: CheckboxGroup,
	Field: CheckboxGroupField,
}
