import "./style.pcss";

import { useEffect, useState } from "react";
import type { FC, ReactElement } from "react";
import type { IChecker } from "./config/types";
import { getRequiredState } from "./utils/getRequiredState";
import type { IComponentBaseProps } from "../../types/components/index";
import { getClassString } from "../../utils/getClassString";
import { getSanitizedHTML } from "../../utils/getSanitizedHTML";
import { useCN } from "../../utils/react/useCN";
import { Input } from "../input";

/**
 * Компонент чекбокса или радиобаттона
 * @returns {ReactElement}
 */
const Checker: FC<IChecker & IComponentBaseProps> = ({
  name,
  extraClasses = {},
  extraAttrs = {},
  onChange,
  children,
  label = "",
  type = "checkbox",
  isDisabled = false,
  isRequired = false,
  isChecked = false,
  form,
  value = "",
  tabIndex = 0,
  id,
}): ReactElement => {

  const { getCN } = useCN(type);

  const [ isDisabledState, setIsDisabledState ] = useState(isDisabled);
  const [ isCheckedState, setIsCheckedState ] = useState(isChecked);
  const [ isRequiredState, setIsRequiredState ] = useState(() => getRequiredState(isRequired, type));
  const [ checkerValue, setCheckerValue ] = useState(value);

  useEffect(() => {
    setIsDisabledState(isDisabled);
  }, [ isDisabled ]);

  useEffect(() => {
    setIsCheckedState(isChecked);
  }, [ isChecked ]);

  useEffect(() => {
    setIsRequiredState(getRequiredState(isRequired, type));
  }, [ isRequired, type ]);

  useEffect(() => {
    setCheckerValue(value);
  }, [ value ]);

  const labelClassName = getCN("", {
    isChecked: isCheckedState,
    isRequired: !!isRequiredState,
    ...extraClasses,
  });

  const inputGetCN = (elem = "", mod = {}) => getClassString(`${type}__input`, elem, mod);

  return (
    <label className={labelClassName} {...extraAttrs}>
      {children || (
        <>
          <Input
            value={checkerValue}
            tabIndex={tabIndex}
            getCN={inputGetCN}
            form={form}
            name={name}
            id={id || name}
            type={type}
            onChange={onChange}
            isDisabled={isDisabledState}
            isChecked={isCheckedState}
            isRequired={isRequiredState}
          />
          <span role={"presentation"} className={getCN("emulator")} />
          {!!label && (
            <span
              className={getCN("label")}
              dangerouslySetInnerHTML={{ __html: getSanitizedHTML(label) }}
            />
          )}
        </>
      )}
    </label>
  );
};

export type { IChecker };
export { Checker };
