import classNames from "classnames";
import { useState } from "react";
import { useUpdateEffect } from "react-use";

interface Props {
  label: string;
  checked: boolean;
  onChange: (checked: boolean) => void;
}

export const Toggle: React.FC<Props> = ({ label, onChange, checked }) => {
  const [checkedState, setCheckedState] = useState(checked);

  useUpdateEffect(() => onChange(checkedState), [checkedState]);

  return (
    <div className="w-full flex items-center justify-start gap-2.5">
      <label className="text-slate-400 text-sm font-medium capitalize">
        {label}:
      </label>
      <div
        className={classNames(
          "w-[52px] h-[24px] rounded-full p-[4px] relative cursor-pointer",
          {
            "bg-red-700": !checkedState,
            "bg-blue-600": checkedState,
          }
        )}
        onClick={() => setCheckedState(!checkedState)}
      >
        <div
          className={classNames(
            "rounded-full h-[16px] w-[16px] bg-slate-50 shadow-xl absolute top-[4px] transition-all duration-200",
            {
              "left-[4px]": checkedState,
              "left-[31px]": !checkedState,
            }
          )}
        />
        <p
          className={classNames(
            "text-white text-xs uppercase font-bold transition-all duration-200",
            {
              "text-right": checkedState,
            }
          )}
        >
          {checkedState ? "on" : "off"}
        </p>
      </div>
    </div>
  );
};
