import { useEffect, useState } from "react"

interface CountdownProps {
  endDate: string | Date
}

const Countdown = ({ endDate }: CountdownProps) => {
  const [timeLeft, setTimeLeft] = useState<string>("")

  useEffect(() => {
    if (!endDate) {
      setTimeLeft("No end date provided")
      return
    }

    const updateCountdown = () => {
      const now = new Date().getTime()
      const end = new Date(endDate).getTime()
      const diff = end - now

      if (isNaN(end)) {
        setTimeLeft("Invalid date")
        return
      }

      if (diff <= 0) {
        setTimeLeft("Plan completed")
        return
      }

      const days = Math.floor(diff / (1000 * 60 * 60 * 24))
      const hours = Math.floor((diff / (1000 * 60 * 60)) % 24)
      const minutes = Math.floor((diff / (1000 * 60)) % 60)
      const seconds = Math.floor((diff / 1000) % 60)

      const parts: string[] = []
      if (days > 0) parts.push(`${days} day${days !== 1 ? "s" : ""}`)
      if (hours > 0) parts.push(`${hours} hr${hours !== 1 ? "s" : ""}`)
      if (minutes > 0) parts.push(`${minutes} min${minutes !== 1 ? "s" : ""}`)
      if (days === 0 && hours === 0 && minutes < 5) parts.push(`${seconds}s`)

      setTimeLeft(parts.join(", "))
    }

    updateCountdown()
    const interval = setInterval(updateCountdown, 1000) // update every second
    return () => clearInterval(interval)
  }, [endDate])

  return (
    <div>
      <span>{timeLeft}</span>
    </div>
  )
}

export default Countdown
