"use client";

import { useEffect, useState, useRef, useCallback } from "react";


export default function CountDown({
    endTime,
    boxClassName,
    timerClassName,
    onCountDownEnd
}: {
    endTime: number;
    boxClassName?: string;
    timerClassName?: string;
    onCountDownEnd: () => void;
}) { 
    const defaultBoxClassName = boxClassName || "flex items-center gap-2 flex-none text-ly-14 text-white";
    const defaultTimerClassName = timerClassName || "flex items-center justify-center w-6 h-6 bg-white rounded-xs text-ly-12 font-medium text-black";
    
    const timerRef = useRef<number | null>(null);
    const [seconds, setSeconds] = useState(() => {
        return Math.max(0, Math.floor((endTime - Date.now()) / 1000));
    }); // 倒计时的总秒数

    const clearTimer = () => {
        if (timerRef.current !== null) {
            clearInterval(timerRef.current);
            timerRef.current = null;
        }
    };

    const start = useCallback(() => {
        if (timerRef.current) return;

        timerRef.current = window.setInterval(() => {
            setSeconds((prev) => {
                if (prev <= 1) {
                clearTimer();
                onCountDownEnd();
                return 0;
                }
                return prev - 1;
            });
        }, 1000);
    }, [onCountDownEnd]);

    const format = (n: number) => {
        const h = Math.floor(n / 3600);
        const m = Math.floor((n % 3600) / 60);
        const s = n % 60;
        return {
            hour: String(h).padStart(2, "0"),
            minute: String(m).padStart(2, "0"),
            second: String(s).padStart(2, "0"),
        }
    };

    useEffect(() => {
        start();
        return () => clearTimer();
    }, [start]);

    const { hour, minute, second } = format(seconds);

    return (
        <div className={defaultBoxClassName}>
            <span className={defaultTimerClassName}>{hour}</span>
            :
            <span className={defaultTimerClassName}>{minute}</span>
            :
            <span className={defaultTimerClassName}>{second}</span>
        </div>
    );
}
