import React, { useState } from 'react';
import { useTheme } from '@emotion/react';
import { capitalize } from '../../functions';
import { StyledCheckbox } from './style';
import { BnIcon, Typography } from '../index';
import { ErrorMessage } from '../ErrorMessage';
import { ETypography, ETypographyColor } from '../../types/theme';

export interface Props {
  checked?: boolean;
  setChecked?: (val: boolean) => void;
  icon?: string;
  label?: string;
  width?: number;
  error?: string;
  isDisabled?: boolean;
  sizer?: 'M' | 'S';
}
export const Checkbox = ({
  checked,
  setChecked,
  label = '',
  sizer = 'S',
  icon = '',
  width = 20,
  error,
  isDisabled = false,
  ...props
}: Props) => {
  const colors = useTheme();
  const [visited, setVisited] = useState<boolean>(false);

  return (
    <>
      <StyledCheckbox theme={{ ...colors }} disabled={isDisabled} width={width}>
        {(label || icon) && (
          <div className={`${sizer}`}>
            {icon && <BnIcon icon={icon} />}
            {capitalize(label)}
          </div>
        )}
        <input
          type="checkbox"
          checked={checked}
          disabled={isDisabled}
          onChange={(e) => {
            if (!isDisabled) {
              //@ts-ignore
              if (setChecked) {
                //@ts-ignore
                setChecked(e.target.checked);
              }
            }
          }}
          {...props}
          onBlur={() => setVisited(true)}
        />
        <span className={`checkmark ${visited && error ? 'error' : ''}`}></span>
      </StyledCheckbox>
      {visited && <ErrorMessage error={error || ''} />}
    </>
  );
};
