import React, { ButtonHTMLAttributes } from "react";
import { motion, HTMLMotionProps } from "framer-motion";

type PropsWeControl =
  | "onDrag"
  | "onDragStart"
  | "onDragEnd"
  | "onAnimationStart";

type ToggleButtonProps = Omit<
  ButtonHTMLAttributes<HTMLButtonElement>,
  PropsWeControl | "ref"
> & {
  isActive?: boolean;
  title?: string;
  size?: "small" | "medium" | "large";
} & Pick<HTMLMotionProps<"button">, PropsWeControl>;

const ToggleButton = React.forwardRef<HTMLButtonElement, ToggleButtonProps>(
  (
    { isActive = false, title, className = "", size = "medium", ...props },
    ref
  ) => {
    return (
      <div className="flex items-center gap-2">
        {title && (
          <span className="text-sm whitespace-nowrap text-gray-700 dark:text-dark-100">
            {title}
          </span>
        )}

        <motion.button
          ref={ref}
          className={`
            relative flex items-center justify-between ${
              size === "small"
                ? "w-8 h-4"
                : size === "medium"
                ? "w-12 h-5"
                : "w-14 h-5"
            } rounded-full
            transition-colors duration-300 focus:outline-none
            ${isActive ? "bg-primary-500" : "bg-black-200 dark:bg-gray-600"}
            ${className}
          `}
          aria-pressed={isActive}
          whileTap={{ scale: 0.97 }}
          dir="rtl"
          {...props}
        >
          <motion.span
            className={`${
              size === "small"
                ? "w-3 h-3"
                : size === "medium"
                ? "w-4 h-4"
                : "w-4 h-4"
            } rounded-full shadow-md ${
              isActive ? "bg-white" : "bg-white dark:bg-gray-200"
            }`}
            layout
            transition={{
              type: "spring",
              stiffness: 700,
              damping: 30,
            }}
            initial={{
              left: isActive
                ? `${
                    size === "small"
                      ? "1rem"
                      : size === "medium"
                      ? "1.75rem"
                      : "2.3rem"
                  }`
                : "0.25rem",
            }}
            animate={{
              left: isActive
                ? `${
                    size === "small"
                      ? "1rem"
                      : size === "medium"
                      ? "1.75rem"
                      : "2.3rem"
                  }`
                : "0.25rem",
            }}
            style={{
              position: "absolute",
              top: "0.125rem",
              left: isActive ? "1.75rem" : "0.25rem",
            }}
          />
        </motion.button>
      </div>
    );
  }
);

ToggleButton.displayName = "ToggleButton";

export default ToggleButton;
