"use client";
import React, { useEffect, useState, type ReactElement, type ChangeEvent } from 'react'
import { makeClassName } from '@/utils'
import { type ICheckboxInputProps } from '@/Types'
import Label from '@/Components/Inputs/Label'
import Description from '@/Components/Inputs/Description'

export default function Checkbox({
  id,
  testId = 'checkbox',
  value,
  error,
  disabled = false,
  onChange,
  defaultClassName,
  className = '',
  defaultWrapperClassName = 'block align-middle',
  wrapperClassName,
  size,
  label,
  description,
  after,
  before,
  align = 'left'
}: ICheckboxInputProps): ReactElement {
  const alignClasses = {
    left: 'mr-2',
    right: 'ml-2',
    none: ''
  }
  const [v, setV] = useState<boolean>(value)
  const labelOutput = <Label
    className='inline'
    label={label}
    disabled={disabled}
  />
  const updateValue = (newValue: boolean): void => {
    setV(newValue)
    value = newValue
  }
  useEffect(() => {
    updateValue(value)
  }, [value])
  const onInputChange = (e: ChangeEvent<HTMLInputElement>): void => {
    const newV = !!e.target.checked
    updateValue(newV)
    if (typeof onChange === 'function') {
      onChange(newV)
    }
  }

  const CheckboxInput = (): ReactElement => {
    return (
      <input
        data-testid={testId}
        type="checkbox"
        className={makeClassName({
          defaultClassName,
          className,
          error,
          extras: [
            'p-0', alignClasses[align],
            disabled ? 'cursor-not-allowed' : '']
        })}
        onChange={onInputChange}
        checked={!!v}
        disabled={disabled}
      />
    )
  }

  const CheckboxContent = (): ReactElement => {
    return (
      <>
        {before !== undefined ? before : ''}
        {align !== 'right' ? <CheckboxInput /> : ''}
        {label !== undefined ? labelOutput : ''}
        {align === 'right' ? <CheckboxInput /> : ''}
        {after !== undefined ? after : ''}
      </>
    )
  }

  return (
    <>
      {
        label !== undefined || after !== undefined || before !== undefined
          ? <label className={makeClassName({
            defaultClassName: defaultWrapperClassName,
            className: wrapperClassName
          })}>
            <CheckboxContent />
            {
              description !== undefined
                ? typeof description === 'string'
                  ? <Description description={description} disabled={disabled} />
                  : description !== undefined ? description : ''
                : ''

            }
          </label>
          : <CheckboxContent />
      }
    </>

  )
}
