"use client"

import { useState } from "react"
import { useInterval } from "usehooks-ts"

import { dt } from "@/lib/dt"

import Title from "@/components/TempDesignSystem/Text/Title"

import type { CountdownProps } from "@/types/components/countdown"

export default function Countdown({
  minutes = 30,
  seconds = 0,
  onChange = () => undefined,
}: CountdownProps) {
  const [time, setTime] = useState(dt.duration({ minutes, seconds }))
  const timeSeconds = time.asSeconds()

  useInterval(
    () => {
      setTime((currentTime) => {
        const newTime = currentTime.asMilliseconds() - 1000
        onChange(newTime)
        return dt.duration(newTime)
      })
    },
    timeSeconds > 0 ? 1000 : null
  )

  return (
    <Title as="h1">
      <time dateTime={time.toISOString()}>{time.format("m:ss")}</time>
    </Title>
  )
}
