import styled from "styled-components";
import { useEffect, useState, useRef } from "react";
import { DISPATCH_PLAY_SFX } from "./AudioController";
import { respondTo } from "../../utils/responsive";

        // "/audios/counting.mp3",
        // "/audios/timeout.mp3",

function CountdownTimer({ totalSeconds, onFinish, className, shouldStart }) {
    const [leftTime, setLeftTime] = useState(totalSeconds);
    const timerIdRef = useRef(null);

    useEffect(() => {
        if (!shouldStart) {
            if (timerIdRef.current) {
                clearTimeout(timerIdRef.current);
                timerIdRef.current = null;
            }
            return;
        }

        if (leftTime <= 10) {
            DISPATCH_PLAY_SFX("/audios/counting.mp3");
        }


        if (leftTime <= 0) {
            onFinish();
            DISPATCH_PLAY_SFX("/audios/timeout.mp3");
            return;
        }

        const handleTimer = () => {
            setLeftTime(leftTime - 1);

            if (leftTime <= 0) {
                clearTimeout(timerIdRef.current);
                onFinish();
            } else {
                timerIdRef.current = setTimeout(handleTimer, 1000);
            }
        }

        timerIdRef.current = setTimeout(handleTimer, 1000);
        return () => {
            clearTimeout(timerIdRef.current);
            timerIdRef.current = null;
        };
    }, [leftTime, shouldStart, onFinish]);

    const formatTime = (seconds) => {
        const minutes = Math.floor(seconds / 60);
        const remainingSeconds = seconds % 60;
        return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
    };

    return (
        <StyledContainer className={className}>
            <span>倒數</span>
            <b>{formatTime(leftTime)}</b>
        </StyledContainer>
    );
}

const StyledContainer = styled.div`
    background: var(--main-color-e);
    border-radius: 12px 0px 0px 12px;
    padding: 16px 32px;
    color: white;
    height: 80px;

    display: flex;
    align-items: center;
    justify-content: center;
    gap: 16px;

    font: var(--headline-6);

    ${respondTo.sm} {
        height: 56px;
        font: var(--mobile-headline-6);

        padding: 16px 12px;
    }

    b {
        font-family: "Bungee", sans-serif;
        color: #ff6b24;
        font-size: 48px;
        line-height: 1.2;

        width: calc(48px * 3.2);

        ${respondTo.sm} {
            font-size: 32px;
            width: calc(32px * 3.2);
        }
    }
`;

export default CountdownTimer;
