"use client";

import { useEffect, useState } from "react";
import type { Payment } from "@/types/order";
import { formatCurrency } from "@/lib/format";

const BANK_LABEL: Record<string, string> = {
  bca: "BCA",
  bni: "BNI",
  bri: "BRI",
  permata: "Permata",
};

function useCountdown(expiryTime: string | null) {
  const [label, setLabel] = useState<string | null>(null);

  useEffect(() => {
    if (!expiryTime) return; // label already starts null — nothing to sync

    const expiryMs = new Date(expiryTime).getTime();

    function tick() {
      const diff = expiryMs - Date.now();
      if (diff <= 0) {
        setLabel("Expired");
        return;
      }
      const h = Math.floor(diff / 3_600_000);
      const m = Math.floor((diff % 3_600_000) / 60_000);
      const s = Math.floor((diff % 60_000) / 1_000);
      setLabel(`${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`);
    }

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

  return label;
}

/** Renders the QR image or VA number + copy button for an already-charged Payment. */
export function PaymentInstructions({ payment }: { payment: Payment }) {
  const countdown = useCountdown(payment.expiry_time);
  const [copied, setCopied] = useState(false);

  async function handleCopy() {
    if (!payment.va_number) return;
    await navigator.clipboard.writeText(payment.va_number);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  }

  return (
    <div className="rounded-xl border border-neutral-200 bg-white p-4">
      <div className="flex items-center justify-between">
        <p className="font-medium">{formatCurrency(payment.gross_amount)}</p>
        {countdown && (
          <span className="text-sm text-neutral-500">
            {countdown === "Expired" ? countdown : `Pay within ${countdown}`}
          </span>
        )}
      </div>

      {payment.qr_url ? (
        <div className="mt-4 flex flex-col items-center gap-2">
          {/* eslint-disable-next-line @next/next/no-img-element -- external Midtrans-hosted QR image, not a local asset */}
          <img src={payment.qr_url} alt="QRIS" className="h-56 w-56 rounded-lg border border-neutral-100" />
          <p className="text-center text-sm text-neutral-500">
            Open GoPay, OVO, Dana, or any m-banking app that supports QRIS, then scan the code above.
          </p>
        </div>
      ) : payment.va_number ? (
        <div className="mt-4 flex flex-col gap-2">
          <p className="text-sm text-neutral-500">
            Transfer to {BANK_LABEL[payment.bank ?? ""] ?? payment.bank} Virtual Account
          </p>
          <div className="flex items-center justify-between rounded-lg bg-neutral-100 px-4 py-3">
            <span className="font-mono text-lg font-semibold tracking-wide">{payment.va_number}</span>
            <button
              type="button"
              onClick={handleCopy}
              className="rounded-full border border-neutral-300 px-3 py-1 text-sm font-medium transition-colors hover:bg-neutral-200"
            >
              {copied ? "Copied!" : "Copy"}
            </button>
          </div>
          <p className="text-sm text-neutral-500">
            Transfer via {BANK_LABEL[payment.bank ?? ""] ?? payment.bank} ATM, m-banking, or internet banking for the amount above.
          </p>
        </div>
      ) : (
        <p className="mt-4 text-sm text-neutral-500">Waiting for payment instructions...</p>
      )}
    </div>
  );
}
