import React from 'react'
import { Button } from './ui/button'

export interface CountdownRedirectProps {
  seconds?: number
  onComplete: () => void
  destination?: string
}

export function CountdownRedirect({ seconds = 5, onComplete, destination = 'dashboard' }: CountdownRedirectProps) {
  const [remaining, setRemaining] = React.useState<number>(seconds)
  const timerRef = React.useRef<number | null>(null)
  const cancelledRef = React.useRef<boolean>(false)

  React.useEffect(() => {
    timerRef.current = window.setInterval(() => {
      setRemaining((prev) => {
        if (prev <= 1) {
          if (!cancelledRef.current) {
            onComplete()
          }
          if (timerRef.current) {
            clearInterval(timerRef.current)
            timerRef.current = null
          }
          return 0
        }
        return prev - 1
      })
    }, 1000)

    return () => {
      if (timerRef.current) {
        clearInterval(timerRef.current)
        timerRef.current = null
      }
    }
  }, [onComplete])

  function handleManual() {
    cancelledRef.current = true
    if (timerRef.current) {
      clearInterval(timerRef.current)
      timerRef.current = null
    }
    onComplete()
  }

  return (
    <div className="mt-4 flex flex-col items-center text-center">
      <div className="text-base">
        Anda akan diarahkan ke {destination} dalam {remaining} detik...
      </div>
      <Button size="lg" className="mt-3" onClick={handleManual}>
        Kembali Sekarang
      </Button>
    </div>
  )
}