import classNames from "classnames";
import { useState } from "react";
import { HiInformationCircle } from "react-icons/hi";
import { useUpdateEffect } from "react-use";

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

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

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

  return (
    <div className="w-full flex items-center justify-start gap-2.5 relative">
      <div className="flex items-center justify-start gap-2">
        {tooltip && (
          <div className="group cursor-pointer">
            <HiInformationCircle className="text-slate-400 dark:text-slate-500 group-hover:text-slate-600 dark:group-hover:text-slate-300 text-xl" />
            <div className="bg-black dark:bg-slate-950/90 z-10 min-w-[200px] rounded-xl p-3 text-white absolute text-xs left-0 bottom-0 translate-y-[calc(100%+8px)] opacity-0 transition-all duration-200 group-hover:opacity-100 pointer-events-none group-hover:pointer-events-auto">
              {tooltip}
            </div>
          </div>
        )}
        <label className="text-slate-500 dark:text-slate-400 text-sm dark:font-medium capitalize">
          {label}:
        </label>
      </div>
      <div
        className={classNames(
          "w-[32px] h-[20px] rounded-full px-[4px] relative cursor-pointer",
          {
            "bg-red-700": !checkedState,
            "bg-green-500": checkedState,
          }
        )}
        onClick={() => setCheckedState(!checkedState)}
      >
        <div
          className={classNames(
            "rounded-full h-[12px] w-[12px] bg-slate-50 shadow-xl absolute top-[4px] transition-all duration-200",
            {
              "translate-x-0": !checkedState,
              "translate-x-full": checkedState,
            }
          )}
        />
      </div>
    </div>
  );
};
