'use client';

import { useCallback, useEffect, useMemo, useState } from 'react';
import Link from 'next/link';
import { useParams } from 'next/navigation';
import {
  ArrowLeft,
  Building2,
  Check,
  Clipboard,
  Coins,
  Clock3,
  Copy,
  CreditCard,
  Loader2,
  QrCode,
  RefreshCcw,
  ShieldCheck,
} from 'lucide-react';
import Navbar from '@/components/Navbar';
import Footer from '@/components/Footer';
import { api } from '@/lib/api';

type DepositSession = {
  sessionId: string;
  transactionCode: string;
  providerCode: string;
  providerName: string;
  method: string;
  amount: string | number;
  currency: string;
  status: string;
  checkoutUrl?: string | null;
  createdAt: string;
  expiresAt: string;
  transferContent: string;
  qrCodeUrl?: string | null;
  crypto?: { network?: string | null; walletAddress?: string | null; usdtAmount?: number; usdtRate?: number } | null;
  bank: {
    code?: string | null;
    name?: string | null;
    accountNumber?: string | null;
    accountName?: string | null;
  };
};

const completedStatuses = new Set(['COMPLETED', 'SUCCESS', 'PAID']);
const failedStatuses = new Set(['FAILED', 'CANCELLED', 'EXPIRED']);

export default function DepositSessionPage() {
  const params = useParams<{ locale: string; sessionId: string }>();
  const locale = params?.locale || 'vi';
  const isVi = locale === 'vi';
  const sessionId = params?.sessionId;
  const [session, setSession] = useState<DepositSession | null>(null);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [error, setError] = useState('');
  const [copied, setCopied] = useState('');
  const [now, setNow] = useState(Date.now());

  const loadSession = useCallback(async (manual = false) => {
    if (!sessionId) return;
    manual ? setRefreshing(true) : setLoading(true);
    setError('');
    try {
      const response = await api.get(`/payment/deposit/${sessionId}`);
      setSession(response.data);
    } catch (requestError: any) {
      setError(requestError.response?.data?.message || (isVi ? 'Không thể tải phiên nạp tiền.' : 'Unable to load this deposit session.'));
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  }, [isVi, sessionId]);

  useEffect(() => {
    void loadSession();
  }, [loadSession]);

  // Keep the session status in sync while the buyer is on this screen. The
  // payment provider/webhook can complete a transfer without a page reload.
  useEffect(() => {
    if (!sessionId || !session || completedStatuses.has(session.status) || failedStatuses.has(session.status)) return;
    const poll = window.setInterval(() => void loadSession(true), 8000);
    return () => window.clearInterval(poll);
  }, [loadSession, session, sessionId]);

  useEffect(() => {
    const timer = window.setInterval(() => setNow(Date.now()), 1000);
    return () => window.clearInterval(timer);
  }, []);

  const remainingSeconds = useMemo(() => {
    if (!session?.expiresAt) return 0;
    return Math.max(0, Math.floor((new Date(session.expiresAt).getTime() - now) / 1000));
  }, [now, session?.expiresAt]);
  const minutes = Math.floor(remainingSeconds / 60);
  const seconds = remainingSeconds % 60;
  const isPaid = session ? completedStatuses.has(session.status) : false;
  const isExpired = session ? failedStatuses.has(session.status) || (!isPaid && remainingSeconds <= 0) : false;

  const copyValue = async (key: string, value?: string | number | null) => {
    if (!value) return;
    await navigator.clipboard.writeText(String(value));
    setCopied(key);
    window.setTimeout(() => setCopied(''), 1500);
  };

  const formatMoney = (value: string | number) =>
    new Intl.NumberFormat(isVi ? 'vi-VN' : 'en-US', {
      style: 'currency',
      currency: session?.currency || 'VND',
      maximumFractionDigits: 0,
    }).format(Number(value || 0));

  const legacyLabels = isVi ? {
    back: 'Về ví',
    title: 'Phiên nạp tiền',
    check: 'Kiểm tra lại',
    waiting: 'Chờ chuyển khoản',
    paid: 'Đã thanh toán',
    expired: 'Đã hết hạn',
    instruction: 'Chuyển đúng số tiền và đúng nội dung bên dưới. Hệ thống sẽ tự động kiểm tra giao dịch.',
    amount: 'Số tiền',
    bank: 'Ngân hàng',
    accountNumber: 'Số tài khoản',
    accountName: 'Chủ tài khoản',
    content: 'Nội dung chuyển khoản',
    transaction: 'Mã giao dịch',
    remaining: 'Còn hiệu lực',
    expiredAt: 'Hết hạn',
    missingAccount: 'Admin chưa cấu hình tài khoản nhận tiền. Vui lòng không chuyển khoản và liên hệ hỗ trợ.',
    safe: 'QR chứa đúng số tiền và nội dung của phiên này.',
    paidMessage: 'Giao dịch đã được ghi nhận và số dư ví đã được cập nhật.',
    errorTitle: 'Không mở được phiên nạp tiền',
  } : {
    back: 'Back to wallet',
    title: 'Deposit session',
    check: 'Check again',
    waiting: 'Awaiting transfer',
    paid: 'Paid',
    expired: 'Expired',
    instruction: 'Transfer the exact amount with the exact reference below. The system will verify the transaction automatically.',
    amount: 'Amount',
    bank: 'Bank',
    accountNumber: 'Account number',
    accountName: 'Account holder',
    content: 'Transfer reference',
    transaction: 'Transaction code',
    remaining: 'Time remaining',
    expiredAt: 'Expires',
    missingAccount: 'The receiving account has not been configured. Do not transfer and contact support.',
    safe: 'The QR contains the exact amount and reference for this session.',
    paidMessage: 'The transaction was recorded and your wallet balance was updated.',
    errorTitle: 'Unable to open deposit session',
  };

  // Keep the Vietnamese copy in source code as UTF-8. Older builds contained
  // mojibake literals; this override guarantees the deposit screen remains
  // readable even when that bundle is still cached by Next.js.
  const labels = isVi ? {
    back: 'Về ví', title: 'Phiên nạp tiền', check: 'Kiểm tra lại',
    waiting: 'Chờ chuyển khoản', paid: 'Đã thanh toán', expired: 'Đã hết hạn',
    instruction: 'Chuyển đúng số tiền và đúng nội dung bên dưới. Hệ thống sẽ tự động kiểm tra giao dịch.',
    amount: 'Số tiền', bank: 'Ngân hàng', accountNumber: 'Số tài khoản',
    accountName: 'Chủ tài khoản', content: 'Nội dung chuyển khoản', transaction: 'Mã giao dịch',
    remaining: 'Còn hiệu lực', expiredAt: 'Hết hạn',
    missingAccount: 'Admin chưa cấu hình tài khoản nhận tiền. Vui lòng không chuyển khoản và liên hệ hỗ trợ.',
    safe: 'QR chứa đúng số tiền và nội dung của phiên này.',
    paidMessage: 'Giao dịch đã được ghi nhận và số dư ví đã được cập nhật.',
    errorTitle: 'Không mở được phiên nạp tiền',
  } : legacyLabels;

  return (
    <div className="min-h-screen bg-[#080808] text-white">
      <Navbar />
      <main className="mx-auto w-full max-w-6xl px-4 py-8 md:py-10">
        <div className="mb-4 flex items-center justify-between gap-3">
          <Link href={`/${locale}/wallet`} className="inline-flex items-center gap-2 rounded-lg border border-white/10 bg-[#141414] px-3 py-2 text-sm font-semibold text-zinc-300 transition hover:border-white/20 hover:text-white">
            <ArrowLeft className="h-4 w-4" />
            {labels.back}
          </Link>
          <button type="button" onClick={() => void loadSession(true)} disabled={refreshing} className="inline-flex items-center gap-2 rounded-lg border border-white/10 bg-[#141414] px-3 py-2 text-sm font-semibold text-zinc-300 transition hover:border-white/20 hover:text-white disabled:opacity-50">
            <RefreshCcw className={`h-4 w-4 ${refreshing ? 'animate-spin' : ''}`} />
            {labels.check}
          </button>
        </div>

        {loading ? (
          <div className="flex min-h-[460px] items-center justify-center rounded-2xl border border-white/10 bg-[#141414]">
            <Loader2 className="h-7 w-7 animate-spin text-rose-400" />
          </div>
        ) : error || !session ? (
          <div className="rounded-2xl border border-red-500/25 bg-red-500/10 p-8 text-center">
            <QrCode className="mx-auto h-10 w-10 text-red-300" />
            <h1 className="mt-4 text-xl font-bold">{labels.errorTitle}</h1>
            <p className="mt-2 text-sm text-red-200/80">{error}</p>
          </div>
        ) : (
          <section className="overflow-hidden rounded-2xl border border-white/10 bg-[#141414] shadow-2xl shadow-black/30">
            <header className="flex flex-col gap-4 border-b border-white/10 px-5 py-5 sm:flex-row sm:items-start sm:justify-between md:px-7">
              <div>
                <div className="flex items-center gap-2">
                  <CreditCard className="h-5 w-5 text-amber-200" />
                  <h1 className="text-xl font-black md:text-2xl">{labels.title}</h1>
                </div>
                <p className="mt-1 text-sm text-zinc-500">{labels.transaction} <span className="font-mono text-zinc-300">{session.transactionCode}</span></p>
              </div>
              <span className={`w-fit rounded-full px-3 py-1 text-xs font-bold ${isPaid ? 'bg-emerald-500/15 text-emerald-300' : isExpired ? 'bg-red-500/15 text-red-300' : 'bg-amber-500/15 text-amber-200'}`}>
                {isPaid ? labels.paid : isExpired ? labels.expired : labels.waiting}
              </span>
            </header>

            <div className="grid gap-5 p-5 md:grid-cols-[310px_minmax(0,1fr)] md:p-7">
              <div className="space-y-4">
                <div className={`flex min-h-[310px] items-center justify-center overflow-hidden rounded-xl border p-3 ${session.crypto ? 'border-amber-500/30 bg-black/40' : 'border-white/10 bg-white'}`}>
                  {session.crypto ? (
                    <div className="w-full px-5 text-center text-amber-100">
                      <Coins className="mx-auto h-16 w-16 text-amber-300" />
                      <p className="mt-5 text-lg font-bold">USDT BEP20</p>
                      <p className="mt-2 text-xs text-zinc-400">{isVi ? 'Chỉ gửi USDT qua mạng BNB Smart Chain' : 'Send USDT only through BNB Smart Chain'}</p>
                    </div>
                  ) : session.qrCodeUrl ? (
                    <img src={session.qrCodeUrl} alt="QR nạp tiền" className="h-auto w-full max-w-[285px] object-contain" />
                  ) : (
                    <div className="px-6 text-center text-zinc-700">
                      <Building2 className="mx-auto h-12 w-12" />
                      <p className="mt-3 text-sm font-semibold">{labels.missingAccount}</p>
                    </div>
                  )}
                </div>
                <div className="rounded-xl border border-white/10 bg-black/25 p-4">
                  <p className="text-xs text-zinc-500">{labels.remaining}</p>
                  <p className={`mt-1 font-mono text-2xl font-black ${isExpired ? 'text-red-300' : 'text-amber-100'}`}>
                    {String(minutes).padStart(2, '0')}:{String(seconds).padStart(2, '0')}
                  </p>
                  <p className="mt-2 text-xs text-zinc-500">{labels.expiredAt}: {new Date(session.expiresAt).toLocaleString(isVi ? 'vi-VN' : 'en-US')}</p>
                </div>
                <div className="flex items-start gap-2 rounded-xl border border-emerald-500/15 bg-emerald-500/[.06] p-3 text-xs leading-relaxed text-emerald-200/80">
                  <ShieldCheck className="mt-0.5 h-4 w-4 shrink-0" />
                  {isPaid ? labels.paidMessage : labels.safe}
                </div>
              </div>

              <div className="space-y-3">
                <div className="rounded-xl border border-white/10 bg-black/35 px-4 py-4 text-sm leading-relaxed text-zinc-400">{labels.instruction}</div>
                {session.crypto && (
                  <div className="rounded-xl border border-amber-500/30 bg-amber-500/10 px-4 py-4 text-sm text-amber-100">
                    <div className="font-semibold">{isVi ? 'Nạp USDT mạng BEP20' : 'USDT BEP20 deposit'}</div>
                    <div className="mt-2 break-all font-mono text-xs">{session.crypto.walletAddress}</div>
                  </div>
                )}
                <DetailRow icon={CreditCard} label={session.crypto ? (isVi ? 'Số tiền USDT' : 'USDT amount') : labels.amount} value={session.crypto?.usdtAmount ? `${session.crypto.usdtAmount} USDT` : formatMoney(session.amount)} important copyKey="amount" copied={copied} onCopy={copyValue} />
                {session.crypto ? (
                  <>
                    <DetailRow icon={CreditCard} label={isVi ? 'Địa chỉ ví BEP20' : 'BEP20 wallet address'} value={session.crypto.walletAddress || '—'} important copyKey="walletAddress" copied={copied} onCopy={copyValue} />
                    <DetailRow icon={Clipboard} label="Memo" value={session.transferContent} important copyKey="content" copied={copied} onCopy={copyValue} />
                  </>
                ) : (
                  <>
                    <DetailRow icon={Building2} label={labels.bank} value={session.bank.name || session.bank.code || '—'} />
                    <DetailRow icon={CreditCard} label={labels.accountNumber} value={session.bank.accountNumber || '—'} copyKey="accountNumber" copied={copied} onCopy={copyValue} />
                    <DetailRow icon={ShieldCheck} label={labels.accountName} value={session.bank.accountName || '—'} />
                    <DetailRow icon={Clipboard} label={labels.content} value={session.transferContent} important copyKey="content" copied={copied} onCopy={copyValue} />
                  </>
                )}
                <DetailRow icon={Clock3} label={labels.transaction} value={session.transactionCode} copyKey="transaction" copied={copied} onCopy={copyValue} />
                {session.checkoutUrl && (
                  <a href={session.checkoutUrl} target="_blank" rel="noreferrer" className="flex w-full items-center justify-center rounded-xl bg-gradient-to-r from-violet-600 to-cyan-500 px-4 py-3 text-sm font-bold text-white transition hover:brightness-110">
                    {isVi ? 'Mở cổng thanh toán' : 'Open payment gateway'}
                  </a>
                )}
              </div>
            </div>
          </section>
        )}
      </main>
      <Footer locale={locale} />
    </div>
  );
}

function DetailRow({
  icon: Icon,
  label,
  value,
  important = false,
  copyKey,
  copied,
  onCopy,
}: {
  icon: typeof CreditCard;
  label: string;
  value: string;
  important?: boolean;
  copyKey?: string;
  copied?: string;
  onCopy?: (key: string, value: string) => void;
}) {
  return (
    <div className={`flex min-h-14 items-center justify-between gap-3 rounded-xl border px-4 py-3 ${important ? 'border-amber-200/20 bg-amber-200/[.035]' : 'border-white/10 bg-black/20'}`}>
      <div className="flex min-w-0 items-center gap-3">
        <Icon className="h-4 w-4 shrink-0 text-zinc-600" />
        <span className="text-sm text-zinc-500">{label}</span>
      </div>
      <div className="flex min-w-0 items-center justify-end gap-2">
        <strong className={`truncate text-right text-sm ${important ? 'text-amber-100' : 'text-zinc-100'}`}>{value}</strong>
        {copyKey && onCopy && value !== '—' && (
          <button type="button" onClick={() => onCopy(copyKey, value)} className="shrink-0 rounded-md p-1.5 text-zinc-500 transition hover:bg-white/5 hover:text-white" aria-label={`Copy ${label}`}>
            {copied === copyKey ? <Check className="h-4 w-4 text-emerald-400" /> : <Copy className="h-4 w-4" />}
          </button>
        )}
      </div>
    </div>
  );
}
