'use client';

import { motion } from 'framer-motion';
import { CreditCard } from 'lucide-react';
import { cn, formatDateTime, formatInvoiceStatus, formatInvoiceStatusClass, formatUsd } from '@/lib/admin/utils';
import { PLAN_LABEL, type BillingInvoice, type BillingStats } from '@/lib/types/admin';

type PaymentsTabProps = {
  invoices: BillingInvoice[];
  billingStats: BillingStats;
};

export function PaymentsTab({ invoices, billingStats }: PaymentsTabProps) {
  // billingStats прокидывается родителем для потенциальных виджетов; текущая разметка
  // использует только invoices, но поле сохранено для совместимости контракта.
  void billingStats;
  return (
    <motion.div key="payments" initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: -10 }} className="space-y-6">
      <div className="bg-[#0A0A0A] border border-white/5 rounded-3xl overflow-hidden shadow-xl overflow-x-auto relative group hover:border-white/10 transition-colors">
        <div className="absolute top-0 inset-x-0 mx-auto w-1/3 h-px bg-gradient-to-r from-transparent via-green-500/20 to-transparent" />
        <div className="p-6 md:p-8 border-b border-white/5 flex flex-col md:flex-row md:items-center justify-between gap-4 relative z-10">
          <div>
            <h3 className="font-bold text-xl mb-1 flex items-center gap-2"><CreditCard className="w-5 h-5 text-green-400" /> Недавние транзакции</h3>
            <p className="text-sm text-gray-500">Счета пользователей из базы: оплаченные, ожидающие и отменённые.</p>
          </div>
        </div>
        {invoices.length === 0 ? (
          <div className="px-6 py-10 text-center text-sm text-gray-500">
            Счета пока отсутствуют.
          </div>
        ) : (
          <>
            {/* Desktop table */}
            <table className="hidden md:table w-full text-left bg-black/20">
              <thead>
                <tr className="border-b border-white/5 text-xs font-semibold text-gray-400 uppercase tracking-wider bg-white/[0.02]">
                  <th className="px-6 py-5">№ / Дата</th>
                  <th className="px-6 py-5">Пользователь</th>
                  <th className="px-6 py-5">Тариф</th>
                  <th className="px-6 py-5 text-right">Сумма, USD</th>
                  <th className="px-6 py-5 text-right">Оплачено криптой</th>
                  <th className="px-6 py-5 text-right">Статус</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-white/5">
                {invoices.map((invoice) => (
                  <tr key={invoice.id} className="hover:bg-white/[0.02] transition-colors group/row">
                    <td className="px-6 py-5">
                      <div className="text-sm font-bold text-white mb-1 font-mono group-hover/row:text-green-300 transition-colors">{invoice.id.slice(0, 12)}</div>
                      <div className="text-xs text-gray-500">{formatDateTime(invoice.createdAt)}</div>
                    </td>
                    <td className="px-6 py-5">
                      <span className="text-sm font-medium text-gray-200 hover:text-white bg-white/5 hover:bg-white/10 px-3 py-1.5 rounded-lg border border-white/5 cursor-pointer transition-all">
                        {invoice.user.telegramUsername ? `@${invoice.user.telegramUsername}` : (invoice.user.telegramId || invoice.user.name || invoice.userId.slice(0, 8))}
                      </span>
                    </td>
                    <td className="px-6 py-5 text-sm text-gray-400">
                      {PLAN_LABEL[invoice.plan]}{invoice.interval === 'YEARLY' ? ' · год' : ' · месяц'}
                    </td>
                    <td className="px-6 py-5 text-sm font-bold text-right text-white">{formatUsd(invoice.amountUsdCents)}</td>
                    <td className="px-6 py-5 text-right">
                      <div className="text-sm font-medium text-gray-300">
                        {invoice.paidAmount && invoice.paidAsset ? `${invoice.paidAmount} ${invoice.paidAsset}` : '—'}
                      </div>
                    </td>
                    <td className="px-6 py-5 text-right">
                      <span className={cn('inline-flex justify-center px-3 py-1.5 rounded-lg text-[10px] font-bold uppercase tracking-wider border', formatInvoiceStatusClass(invoice.status))}>
                        {formatInvoiceStatus(invoice.status)}
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>

            {/* Mobile card list */}
            <div className="md:hidden divide-y divide-white/5">
              {invoices.map((invoice) => (
                <div key={invoice.id} className="p-4 space-y-2.5">
                  <div className="flex items-start justify-between gap-3">
                    <div className="min-w-0">
                      <div className="text-sm font-bold text-white font-mono">{invoice.id.slice(0, 12)}</div>
                      <div className="text-xs text-gray-500 mt-0.5">{formatDateTime(invoice.createdAt)}</div>
                    </div>
                    <span className={cn('inline-flex justify-center px-2.5 py-1 rounded-lg text-[10px] font-bold uppercase tracking-wider border shrink-0', formatInvoiceStatusClass(invoice.status))}>
                      {formatInvoiceStatus(invoice.status)}
                    </span>
                  </div>
                  <div className="flex flex-wrap items-center gap-2 text-sm">
                    <span className="text-gray-200 bg-white/5 px-2.5 py-1 rounded-lg border border-white/5">
                      {invoice.user.telegramUsername ? `@${invoice.user.telegramUsername}` : (invoice.user.telegramId || invoice.user.name || invoice.userId.slice(0, 8))}
                    </span>
                    <span className="text-gray-400">
                      {PLAN_LABEL[invoice.plan]}{invoice.interval === 'YEARLY' ? ' · год' : ' · месяц'}
                    </span>
                  </div>
                  <div className="flex items-center justify-between text-sm">
                    <span className="font-bold text-white">{formatUsd(invoice.amountUsdCents)}</span>
                    <span className="text-gray-400 text-xs">
                      {invoice.paidAmount && invoice.paidAsset ? `${invoice.paidAmount} ${invoice.paidAsset}` : ''}
                    </span>
                  </div>
                </div>
              ))}
            </div>
          </>
        )}
      </div>
    </motion.div>
  );
}
