'use client'

import { useState, useEffect } from 'react'
import { Clock } from 'lucide-react'

interface FlashSaleTimerProps {
  endTime: Date
  onExpire?: () => void
}

export default function FlashSaleTimer({ endTime, onExpire }: FlashSaleTimerProps) {
  const [timeLeft, setTimeLeft] = useState({ hours: 0, minutes: 0, seconds: 0 })

  useEffect(() => {
    const calculateTimeLeft = () => {
      const difference = endTime.getTime() - new Date().getTime()
      
      if (difference <= 0) {
        onExpire?.()
        return { hours: 0, minutes: 0, seconds: 0 }
      }
      
      return {
        hours: Math.floor(difference / (1000 * 60 * 60)),
        minutes: Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60)),
        seconds: Math.floor((difference % (1000 * 60)) / 1000),
      }
    }

    setTimeLeft(calculateTimeLeft())
    
    const timer = setInterval(() => {
      setTimeLeft(calculateTimeLeft())
    }, 1000)
    
    return () => clearInterval(timer)
  }, [endTime, onExpire])

  return (
    <div className="flex items-center gap-4 bg-black/30 backdrop-blur-sm px-5 py-3 rounded-full">
      <Clock className="text-white/70 w-5 h-5" />
      <div className="flex gap-3">
        <div className="text-center">
          <div className="bg-white text-gray-900 rounded-lg px-3 py-1.5 min-w-12.5">
            <span className="text-xl md:text-2xl font-bold tabular-nums">
              {String(timeLeft.hours).padStart(2, '0')}
            </span>
          </div>
          <div className="text-white/70 text-xs mt-0.5">Hours</div>
        </div>
        <div className="text-white text-xl font-bold self-start mt-1">:</div>
        <div className="text-center">
          <div className="bg-white text-gray-900 rounded-lg px-3 py-1.5 min-w-12.5">
            <span className="text-xl md:text-2xl font-bold tabular-nums">
              {String(timeLeft.minutes).padStart(2, '0')}
            </span>
          </div>
          <div className="text-white/70 text-xs mt-0.5">Minutes</div>
        </div>
        <div className="text-white text-xl font-bold self-start mt-1">:</div>
        <div className="text-center">
          <div className="bg-white text-gray-900 rounded-lg px-3 py-1.5 min-w-12.5">
            <span className="text-xl md:text-2xl font-bold tabular-nums">
              {String(timeLeft.seconds).padStart(2, '0')}
            </span>
          </div>
          <div className="text-white/70 text-xs mt-0.5">Seconds</div>
        </div>
      </div>
    </div>
  )
}