'use client';

import { useState, useEffect } from 'react';

interface Props {
  endTime: string;
  productId: string;
  compact?: boolean;
}

function getTimeLeft(endTime: string) {
  const diff = new Date(endTime).getTime() - Date.now();
  if (diff <= 0) return { days: 0, hours: 0, minutes: 0, seconds: 0, ended: true };
  return {
    days: Math.floor(diff / (1000 * 60 * 60 * 24)),
    hours: Math.floor((diff / (1000 * 60 * 60)) % 24),
    minutes: Math.floor((diff / (1000 * 60)) % 60),
    seconds: Math.floor((diff / 1000) % 60),
    ended: false,
  };
}

export default function AuctionCountdown({ endTime, compact }: Props) {
  const [time, setTime] = useState(getTimeLeft(endTime));

  useEffect(() => {
    const interval = setInterval(() => setTime(getTimeLeft(endTime)), 1000);
    return () => clearInterval(interval);
  }, [endTime]);

  if (time.ended) {
    return (
      <div className={`${compact ? 'px-3 py-1.5' : 'px-4 py-3'} bg-gray-800 text-white text-center rounded-lg`}>
        <span className="text-xs font-bold text-red-400">AUCTION ENDED</span>
      </div>
    );
  }

  if (compact) {
    return (
      <div className="auction-timer px-3 py-1.5 flex items-center justify-center gap-2 text-white">
        <span className="text-xs font-bold text-red-400 animate-pulse">🔥 LIVE</span>
        <div className="flex items-center gap-1 text-xs font-mono font-bold">
          {time.days > 0 && <span>{time.days}d</span>}
          <span>{String(time.hours).padStart(2, '0')}</span>:
          <span>{String(time.minutes).padStart(2, '0')}</span>:
          <span>{String(time.seconds).padStart(2, '0')}</span>
        </div>
      </div>
    );
  }

  return (
    <div className="bg-gray-900 rounded-xl p-4 text-white">
      <div className="flex items-center justify-between mb-3">
        <span className="auction-badge text-xs font-bold text-white px-3 py-1 rounded-full">🔥 LIVE AUCTION</span>
        <span className="text-xs text-gray-400">Ends {new Date(endTime).toLocaleDateString()}</span>
      </div>
      <div className="flex items-center justify-center gap-3">
        {[
          { label: 'Days', value: time.days },
          { label: 'Hours', value: time.hours },
          { label: 'Minutes', value: time.minutes },
          { label: 'Seconds', value: time.seconds },
        ].map((t, i) => (
          <div key={i} className="text-center">
            <div className="timer-box bg-gray-800 text-white text-xl font-mono font-bold px-3 py-2 rounded-lg min-w-[3rem]">
              {String(t.value).padStart(2, '0')}
            </div>
            <span className="text-xs text-gray-400 mt-1 block">{t.label}</span>
          </div>
        ))}
      </div>
    </div>
  );
}
