import clsx, { type ClassValue } from "clsx";
import { useTranslation } from "react-i18next";
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";
import tg from "@/tg";

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 { t } = useTranslation();
  const selectedIndex = value != null ? (value ? 0 : 1) : -1;

  return (
    <ContentSurface
      {...props}
      className={clsx(classes.container, className)}
      whileTap={{ scale: 1.1 }}
      onClick={() => {
        tg.hapticFeedback.click();
        onChange?.(!value);
      }}
    >
      <div className={classes.optionsContainer}>
        <div className={classes.options}>
          <motion.button
            type="button"
            className={clsx(classes.option, value === true && classes.selected)}
          >
            {t("common.on")}
          </motion.button>
          <motion.button
            type="button"
            className={clsx(classes.option, value === false && classes.selected)}
          >
            {t("common.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>
  );
}
