"use client";

import { useEffect, useState } from "react";

type PaymentCountdownProps = {
  /** ISO date string from API (e.g. expiration_estimate_date) */
  expiresAtIso: string | null | undefined;
  label: string;
  onExpire?: () => void;
  className?: string;
  /** `inline` = compact pill for header row; `block` = full-width bar (default) */
  variant?: "block" | "inline";
};

export default function PaymentCountdown({
  expiresAtIso,
  label,
  onExpire,
  className = "",
  variant = "block",
}: PaymentCountdownProps) {
  const [secondsLeft, setSecondsLeft] = useState<number | null>(null);

  useEffect(() => {
    if (!expiresAtIso) {
      setSecondsLeft(null);
      return;
    }
    const end = new Date(expiresAtIso).getTime();
    if (!Number.isFinite(end)) {
      setSecondsLeft(null);
      return;
    }

    let expiredNotified = false;
    const tick = () => {
      const s = Math.max(0, Math.floor((end - Date.now()) / 1000));
      setSecondsLeft(s);
      if (s <= 0 && !expiredNotified) {
        expiredNotified = true;
        onExpire?.();
      }
    };

    tick();
    const id = setInterval(tick, 1000);
    return () => clearInterval(id);
  }, [expiresAtIso, onExpire]);

  if (secondsLeft == null) return null;

  const mm = Math.floor(secondsLeft / 60);
  const ss = secondsLeft % 60;
  const display = `${String(mm).padStart(2, "0")}:${String(ss).padStart(2, "0")}`;

  if (variant === "inline") {
    return (
      <div
        className={`inline-flex shrink-0 items-center gap-3 rounded-full border border-amber-200/80 bg-amber-50 px-4 py-2 text-xs font-medium text-amber-950 ${className}`}
      >
        <span className="text-slate-600">{label}</span>
        <span className="min-w-[3.25rem] font-semibold tabular-nums text-slate-900">
          {display}
        </span>
      </div>
    );
  }

  return (
    <div
      className={`rounded-xl border border-slate-200 bg-slate-50/90 px-4 py-3 ${className}`}
    >
      <div className="flex flex-wrap items-center gap-x-3 gap-y-1">
        <span className="text-sm font-medium leading-5 text-slate-600">
          {label}
        </span>
        <span className="text-sm font-semibold tabular-nums text-slate-900">
          {display}
        </span>
      </div>
    </div>
  );
}
