"use client";

import { useState } from "react";
import { useLang } from "@/context/LanguageContext";

/* An institution's receiving accounts (active Payment Collection Accounts)
   shown to applicants — on the /apply fee notice, the success screen and the
   /track page — each with a copy button for the number. */

export interface PublicAccount {
  type: "MOBILE" | "BANK" | "OTHER";
  provider: string | null;
  accountType: string | null;
  label: string;
  accountName: string | null;
  accountNumber: string;
  branch: string | null;
  note: string | null;
}

export function PaymentAccountCard({ acc }: { acc: PublicAccount }) {
  const { t } = useLang();
  const [copied, setCopied] = useState(false);

  async function copy() {
    try {
      await navigator.clipboard.writeText(acc.accountNumber);
      setCopied(true);
      setTimeout(() => setCopied(false), 1500);
    } catch {
      /* clipboard unavailable */
    }
  }

  const title =
    acc.type === "MOBILE" && acc.provider
      ? t.methods[acc.provider as keyof typeof t.methods] ?? acc.label
      : acc.label;

  return (
    <div className="col-12 col-sm-6">
      <div className="p-3 h-100 rounded" style={{ background: "rgba(36,105,92,0.05)", border: "1px solid rgba(36,105,92,0.12)" }}>
        <div className="d-flex align-items-center gap-2 mb-2">
          <span className="badge badge-soft-teal">{title}</span>
          {acc.type === "MOBILE" && acc.accountType && (
            <span className="badge badge-secondary">
              {acc.accountType === "MERCHANT" ? t.me.payMerchant : t.me.payPersonal}
            </span>
          )}
        </div>
        <div className="d-flex align-items-center justify-content-between gap-2 mb-1">
          <code className="ems-invoice-badge" style={{ fontSize: 13 }}>{acc.accountNumber}</code>
          <button type="button" className="btn btn-sm btn-outline-secondary ems-fs-11 f-w-600" onClick={copy}>
            {copied ? t.me.payCopied : t.me.payCopy}
          </button>
        </div>
        {acc.accountName && <div className="ems-fs-12 text-muted">{acc.accountName}</div>}
        {acc.branch && <div className="ems-fs-12 text-muted">{acc.branch}</div>}
        {acc.note && <div className="ems-fs-11 text-muted mt-1">{acc.note}</div>}
      </div>
    </div>
  );
}

export function PaymentAccountCards({ accounts }: { accounts: PublicAccount[] }) {
  if (!accounts || accounts.length === 0) return null;
  return (
    <div className="row g-2">
      {accounts.map((acc, i) => (
        <PaymentAccountCard key={i} acc={acc} />
      ))}
    </div>
  );
}
