import clsx, { type ClassValue } from "clsx";
import ContentSurface from "@components/surface/ContentSurface";
import LightSurface from "@components/surface/LightSurface";
import { motion, type HTMLMotionProps } from "motion/react";

import classes from "./SwitchInput.module.css";

type Props = Omit<HTMLMotionProps<"div">, "className" | "onChange"> & {
  value?: boolean | null;
  onChange?: (value: boolean) => void;
  className?: ClassValue;
};

export default function SwitchInput({ value, onChange, className, ...props }: Props) {
  const selectedIndex = value != null ? (value ? 0 : 1) : -1;

  return (
    <ContentSurface
      {...props}
      className={clsx(classes.container, className)}
      whileTap={{ scale: 1.1 }}
    >
      <div className={classes.optionsContainer}>
        <div className={classes.options}>
          <motion.button
            type="button"
            whileTap={{ scale: 0.95 }}
            onClick={() => onChange?.(true)}
            className={clsx(classes.option, value === true && classes.selected)}
          >
            on
          </motion.button>
          <motion.button
            type="button"
            whileTap={{ scale: 0.95 }}
            onClick={() => onChange?.(false)}
            className={clsx(classes.option, value === false && classes.selected)}
          >
            off
          </motion.button>
        </div>
        {selectedIndex >= 0 && (
          <LightSurface
            className={classes.thumb}
            initial={{ scale: 0.5 }}
            animate={{
              left: `${selectedIndex * 50}%`,
              width: "50%",
              scale: 1,
            }}
            transition={{ type: "spring", stiffness: 500, damping: 35 }}
          />
        )}
      </div>
    </ContentSurface>
  );
}
