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

interface ToggleBaseProps {
	id: string
	field: HTMLProps<HTMLInputElement>
}

function ToggleBase({ id, field, ...rest }: ToggleBaseProps) {
	return (
		<div className="hds-form-toggle">
			<input
				id={id}
				className="hds-form-toggle__control"
				type="checkbox"
				{...field}
				{...rest}
				role="switch"
			/>
			<div className="hds-form-toggle__facade"></div>
		</div>
	)
}

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

export default function ToggleField({
	isInvalid,
	isLoading,
	isRequired,
	isOptional,
	id,
	label,
	helperText,
	error,
	field,
	className,
	...rest
}: ToggleFieldProps) {
	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}
		>
			<ToggleBase id={inputId} field={field} {...rest} />
		</Field>
	)
}

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

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

function ToggleGroupField(props: ToggleFieldProps) {
	return (
		<ToggleField
			{...props}
			className={classNames('hds-form-group__control-field', props.className)}
		/>
	)
}

export const Group = {
	Root: ToggleGroup,
	Field: ToggleGroupField,
}
