import React from "react";

import "../init";
import PropTypes from "prop-types";
import styling from "@devcake/styling";
import { FormElement } from "../formElement";

styling.setDefault("component.form.checkbox", "border-gray-300");
styling.setDefault("component.form.checkbox.label.left", "mr-2");
styling.setDefault("component.form.checkbox.label.right", "ml-2");

export type CheckboxProps = FormElement<boolean> & {
  color:
    | "amber"
    | "blue"
    | "cyan"
    | "emerald"
    | "fuchsia"
    | "gray"
    | "green"
    | "indigo"
    | "lightBlue"
    | "lime"
    | "orange"
    | "pink"
    | "purple"
    | "red"
    | "rose"
    | "teal"
    | "violet"
    | "yellow";
  labelPosition?: "left" | "right";
  labelClassName?: string;
};

export const Checkbox = ({
                           className,
                           color,
                           disabled,
                           label,
                           labelPosition,
                           labelClassName,
                           onChange,
                           value
                         }: CheckboxProps) => {
  const [checkboxValue, setCheckboxValue] = React.useState<boolean>(value);

  React.useEffect(() => {
    setCheckboxValue(value);
  }, [value]);

  return (
    <div className="flex flex-row items-center">
      {label && labelPosition === "left" && (
        <label
          className={`${labelClassName ? labelClassName : ""} ${styling.get(
            "component.form.checkbox.label.left"
          )}`}
        >
          {label}
        </label>
      )}
      <input
        type="checkbox"
        className={`
        ${styling.get(
          "component.form.checkbox"
        )} focus:ring-${color}-500 text-${color}-600 hover:bg-${color}-300 ${
          className ? className : ""
        }`}
        onChange={(evt) => {
          const { checked } = evt.target;
          setCheckboxValue(checked);

          if (onChange) onChange(checked);
        }}
        disabled={disabled}
        checked={checkboxValue}
      />
      {label && labelPosition === "right" && (
        <label
          className={`${labelClassName} ${styling.get(
            "component.form.checkbox.label.right"
          )}`}
        >
          {label}
        </label>
      )}
    </div>
  );
};

Checkbox.defaultProps = {
  color: "red",
  labelPosition: "right",
  disabled: false,
};

Checkbox.propTypes = {
  color: PropTypes.oneOf([
    "amber",
    "blue",
    "cyan",
    "emerald",
    "fuchsia",
    "gray",
    "green",
    "indigo",
    "lightBlue",
    "lime",
    "orange",
    "pink",
    "purple",
    "red",
    "rose",
    "teal",
    "violet",
    "yellow",
  ]),
  className: PropTypes.string,
  label: PropTypes.string,
  labelPosition: PropTypes.oneOf(["left", "right"]),
  labelClassName: PropTypes.string,
  onChange: PropTypes.func,
  disabled: PropTypes.bool,
};
Checkbox.defaultProps = {
  onChange: () => null
};
