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

import classes from "./TabSelector.module.css";
import { usePlaySound } from "@/audio";
import tg from "@/tg";

type Tab = {
  key: string;
  title: string;
};

type Props = Omit<HTMLMotionProps<"div">, "className" | "onChange"> & {
  tabs: Tab[];
  value?: string | null;
  onChange?: (key: string) => void;
  className?: ClassValue;
};

export default function TabSelector({ tabs, value, onChange, className, ...props }: Props) {
  const play = usePlaySound();

  const selectedIndex = value != null ? tabs.findIndex((tab) => tab.key === value) : -1;

  return (
    <ContentSurface {...props} className={clsx(classes.container, className)}>
      <div className={classes.tabsContainer}>
        <div className={classes.tabs}>
          {tabs.map((tab) => (
            <motion.button
              type="button"
              key={tab.key}
              whileTap={{ scale: 0.95 }}
              onClick={() => {
                play("click");
                tg.hapticFeedback.click();
                onChange?.(tab.key);
              }}
              className={classes.tab}
            >
              {tab.title}
            </motion.button>
          ))}
        </div>
        {selectedIndex >= 0 && (
          <DarkSurface
            className={classes.thumb}
            initial={{ scale: 0.5 }}
            animate={{
              left: `${(selectedIndex / tabs.length) * 100}%`,
              width: `${100 / tabs.length}%`,
              scale: 1,
            }}
            transition={{ type: "spring", stiffness: 500, damping: 35 }}
          />
        )}
      </div>
    </ContentSurface>
  );
}
