/**
 * Transaction Logs Table
 * Enterprise Logging System — Admin Dashboard
 *
 * Renders paginated financial transaction logs with amounts, currency,
 * status, before/after balances, and a detail modal.
 */

'use client';

import { useState } from 'react';
import type { TransactionLog } from '@/types/logging.types';
import { LogPagination } from './LogPagination';
import { LogDetailModal } from './LogDetailModal';

function StatusBadge({ status }: { status: string }) {
  const colors: Record<string, string> = {
    COMPLETED: 'bg-emerald-500/15 text-emerald-400',
    PENDING: 'bg-amber-500/15 text-amber-400',
    FAILED: 'bg-rose-500/15 text-rose-400',
    CANCELLED: 'bg-slate-500/15 text-slate-400',
    REVERSED: 'bg-sky-500/15 text-sky-400',
  };
  return (
    <span className={`rounded-full px-2 py-0.5 text-xs font-medium ${colors[status] ?? 'bg-slate-500/15 text-slate-400'}`}>
      {status}
    </span>
  );
}

export function TransactionLogsTable({
  logs,
  page,
  totalPages,
  total,
  limit,
  onPageChange,
}: {
  logs: TransactionLog[];
  page: number;
  totalPages: number;
  total: number;
  limit: number;
  onPageChange: (page: number) => void;
}) {
  const [selected, setSelected] = useState<TransactionLog | null>(null);

  return (
    <div className="overflow-hidden rounded-xl border border-white/5">
      <div className="overflow-x-auto">
        <table className="w-full min-w-[1000px] text-left text-sm">
          <thead className="border-b border-white/5 bg-slate-900/70 text-xs uppercase text-slate-400">
            <tr>
              <th className="px-4 py-3">Type</th>
              <th className="px-4 py-3">Amount</th>
              <th className="px-4 py-3">Currency</th>
              <th className="px-4 py-3">Status</th>
              <th className="px-4 py-3">Wallet</th>
              <th className="px-4 py-3">Reference</th>
              <th className="px-4 py-3">Timestamp</th>
              <th className="px-4 py-3 text-right">Action</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-white/5">
            {logs.length === 0 && (
              <tr>
                <td colSpan={8} className="px-4 py-10 text-center text-slate-500">
                  No transaction logs found.
                </td>
              </tr>
            )}
            {logs.map((log) => (
              <tr key={log.id} className="hover:bg-white/[0.02]">
                <td className="px-4 py-3 font-medium text-slate-200">{log.type.replace(/_/g, ' ')}</td>
                <td className="px-4 py-3 text-emerald-400">
                  {Number(log.amount).toLocaleString(undefined, { maximumFractionDigits: 8 })}
                </td>
                <td className="px-4 py-3 text-slate-300">{log.currency}</td>
                <td className="px-4 py-3">
                  <StatusBadge status={log.status} />
                </td>
                <td className="px-4 py-3 text-slate-400">{log.walletId?.slice(0, 12) ?? '—'}</td>
                <td className="px-4 py-3 text-slate-400">{log.referenceNumber ?? '—'}</td>
                <td className="px-4 py-3 text-slate-400">{new Date(log.createdAt).toLocaleString()}</td>
                <td className="px-4 py-3 text-right">
                  <button
                    onClick={() => setSelected(log)}
                    className="rounded-lg border border-white/10 px-2.5 py-1 text-xs text-slate-300 hover:bg-white/5"
                  >
                    View
                  </button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <LogPagination page={page} totalPages={totalPages} total={total} limit={limit} onChange={onPageChange} />

      <LogDetailModal
        open={selected !== null}
        onClose={() => setSelected(null)}
        title="Transaction Log Details"
        rows={
          selected
            ? [
                { label: 'ID', value: selected.id },
                { label: 'Transaction ID', value: selected.transactionId ?? '—' },
                { label: 'Type', value: selected.type },
                { label: 'Amount', value: `${selected.amount} ${selected.currency}` },
                { label: 'Status', value: selected.status },
                { label: 'Wallet ID', value: selected.walletId ?? '—' },
                { label: 'User ID', value: selected.userId ?? '—' },
                { label: 'Previous Balance', value: selected.previousBalance ?? '—' },
                { label: 'New Balance', value: selected.newBalance ?? '—' },
                { label: 'Reference', value: selected.referenceNumber ?? '—' },
                { label: 'IP Address', value: selected.ipAddress ?? '—' },
                { label: 'Timestamp', value: new Date(selected.createdAt).toLocaleString() },
              ]
            : []
        }
        raw={selected?.metadata ?? undefined}
      />
    </div>
  );
}

