'use client';

import { useEffect, useRef, useState } from 'react';
import { useTranslations } from 'next-intl';
import { useRouter, useParams } from 'next/navigation';
import { Clock } from 'lucide-react';
import { useBookingDraft } from '@/lib/store/booking-draft';
import { cn } from '@/lib/utils';

interface HoldCountdownProps {
  expiresAt?: string | null;
  /** Unix ms from the server response Date header — used to correct client clock drift. */
  serverNowMs?: number;
  onExpired?: () => void;
}

export function HoldCountdown({ expiresAt, serverNowMs, onExpired }: HoldCountdownProps = {}) {
  const t = useTranslations('checkout');
  const router = useRouter();
  const params = useParams<{ locale: string }>();
  const locale = params?.locale ?? 'en';
  const holdExpiresAtFromStore = useBookingDraft((s) => s.holdExpiresAt);
  const holdExpiresAt = expiresAt !== undefined ? expiresAt : holdExpiresAtFromStore;
  const clear = useBookingDraft((s) => s.clear);
  const [remaining, setRemaining] = useState<number | null>(null);
  const firedRef = useRef(false);
  const driftMs = serverNowMs != null ? serverNowMs - Date.now() : 0;

  useEffect(() => {
    firedRef.current = false;
    if (!holdExpiresAt) {
      setRemaining(null);
      return;
    }
    const target = new Date(holdExpiresAt).getTime();
    const tick = () => {
      const diff = Math.max(0, Math.floor((target - (Date.now() + driftMs)) / 1000));
      setRemaining(diff);
      if (diff === 0 && !firedRef.current) {
        firedRef.current = true;
        onExpired?.();
        if (!onExpired) {
          clear();
          router.push(`/${locale}/cart?expired=1`);
        }
      }
    };
    tick();
    const id = window.setInterval(tick, 1000);
    return () => window.clearInterval(id);
  }, [holdExpiresAt, driftMs, clear, locale, router, onExpired]);

  if (remaining === null) return null;

  const minutes = Math.floor(remaining / 60);
  const seconds = remaining % 60;
  const warning = remaining <= 120;

  const expiryTime = holdExpiresAt
    ? new Intl.DateTimeFormat(locale === 'ar' ? 'ar-EG' : 'en-EG', {
        hour: '2-digit',
        minute: '2-digit',
      }).format(new Date(holdExpiresAt))
    : null;

  return (
    <div
      className={cn(
        'mb-4 flex items-center gap-2 rounded-md border px-3 py-2 text-sm',
        warning
          ? 'border-warning/40 bg-warning/10 text-warning'
          : 'border-neutral-200 bg-neutral-50 text-neutral-700',
      )}
      role="status"
      aria-live="polite"
    >
      <Clock className="h-4 w-4" />
      <span>
        {t('hold_countdown.label')}{' '}
        <strong className="font-mono">
          {String(minutes).padStart(2, '0')}:{String(seconds).padStart(2, '0')}
        </strong>
        {expiryTime && (
          <span className="ms-2 text-xs opacity-70">
            {t('hold_countdown.expires_at', { time: expiryTime })}
          </span>
        )}
      </span>
    </div>
  );
}
