import { useInView, useMotionValue, useSpring } from "framer-motion";
import { useEffect, useRef, useState } from "react";
import { ProgressBar } from "react-bootstrap";

type AnimatedProgressBarProps = {
    value: number;
    className?: string;
    once?: boolean;
};

const AnimatedProgressBar = ({ value, className, once = true }: AnimatedProgressBarProps) => {
    const ref = useRef<HTMLDivElement>(null);
    const isInView = useInView(ref, { once, amount: 0.5 });
    const motionValue = useMotionValue(0);
    const spring = useSpring(motionValue, { stiffness: 60, damping: 20 });
    const [display, setDisplay] = useState(0);

    useEffect(() => {
        if (isInView) {
            motionValue.set(value);
        } else if (!once) {
            motionValue.set(0);
        }
    }, [isInView, value, motionValue, once]);

    useEffect(() => {
        const unsubscribe = spring.on("change", (v) => {
            setDisplay(Math.round(v));
        });
        return unsubscribe;
    }, [spring]);

    return (
        <div ref={ref}>
            <ProgressBar
                className={className}
                now={display}
                label={`${display}%`}
            />
        </div>
    );
};

export default AnimatedProgressBar;
