"use client";

import React from "react";
import { IconButton, Box, Typography } from "@mui/material";
import PlayArrowIcon from "@mui/icons-material/PlayArrow";
import PauseIcon from "@mui/icons-material/Pause";
import useWaveSurferPlayer from "@/lib/hooks/useWaveSurferPlayer";

function formatTime(seconds) {
    if (!seconds || isNaN(seconds)) return "0:00";
    const minutes = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);
    return `${minutes}:${secs.toString().padStart(2, "0")}`;
}

const Player = ({ audioUrl }) => {
    const { containerRef, isPlaying, playPause, currentTime, duration } =
        useWaveSurferPlayer(audioUrl);

    return (
        <Box
            sx={{
                display: "flex",
                alignItems: "center",
                gap: 1,
                justifyContent: "center",
            }}
        >
            <div ref={containerRef} style={{ width: 180 }} />

            <IconButton aria-label="play-pause" onClick={playPause}>
                {isPlaying ? (
                    <PauseIcon sx={{ color: "#d32f2f" }} />
                ) : (
                    <PlayArrowIcon sx={{ color: "#1b4332" }} />
                )}
            </IconButton>
            <Typography variant="body2" sx={{ minWidth: 60, textAlign: "right" }}>
                {formatTime(currentTime)} / {formatTime(duration)}
            </Typography>
        </Box>
    );
};

export default Player;
