'use client';

import React, { useState, useEffect } from 'react';
import { CreditCard, Download, Search } from 'lucide-react';
import SmartAuthCard from '@/components/ui/smartauth/SmartAuthCard';
import SmartAuthButton from '@/components/ui/smartauth/SmartAuthButton';
import SmartAuthBadge from '@/components/ui/smartauth/SmartAuthBadge';

export default function ApiTransactionsPage() {
  const [transactions, setTransactions] = useState<any[]>([]);
  const [search, setSearch] = useState('');

  useEffect(() => {
    async function fetchTxns() {
      try {
        const res = await fetch('/api/v1/transactions');
        const data = await res.json();
        if (data.success) {
          setTransactions(data.data.transactions || []);
        }
      } catch {}
    }
    fetchTxns();
  }, []);

  const filtered = transactions.filter((t) =>
    t.reference?.toLowerCase().includes(search.toLowerCase()) ||
    t.description?.toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div className="space-y-7 animate-in fade-in duration-150">
      <div className="flex flex-wrap items-center justify-between gap-4">
        <div>
          <h1 className="text-2xl font-extrabold text-slate-900 tracking-tight">Transaction History</h1>
          <p className="text-xs text-slate-500 mt-1">Audit log of all financial credits and verification unit debits.</p>
        </div>
      </div>

      <SmartAuthCard title="All Transactions" subtitle={`Total ${filtered.length} records`} headerIcon={CreditCard}>
        <div className="mb-4 max-w-sm">
          <input
            type="text"
            placeholder="Search reference or description..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full px-4 py-2 text-xs rounded-xl border border-slate-200 focus:outline-none focus:ring-2 focus:ring-emerald-500/20"
          />
        </div>

        {filtered.length > 0 ? (
          <div className="overflow-x-auto">
            <table className="w-full text-left text-xs">
              <thead>
                <tr className="border-b border-slate-100 text-slate-500 font-mono">
                  <th className="pb-3 font-semibold">Reference</th>
                  <th className="pb-3 font-semibold">Type</th>
                  <th className="pb-3 font-semibold">Description</th>
                  <th className="pb-3 font-semibold">Units</th>
                  <th className="pb-3 font-semibold">Balance After</th>
                  <th className="pb-3 font-semibold">Date & Time</th>
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-100">
                {filtered.map((t) => (
                  <tr key={t.id} className="hover:bg-slate-50 transition-colors">
                    <td className="py-3 font-mono font-bold text-slate-900">{t.reference}</td>
                    <td className="py-3">
                      <SmartAuthBadge variant={t.type === 'CREDIT' ? 'success' : 'neutral'} size="sm">
                        {t.type}
                      </SmartAuthBadge>
                    </td>
                    <td className="py-3 text-slate-700">{t.description}</td>
                    <td className={`py-3 font-mono font-bold ${t.type === 'CREDIT' ? 'text-emerald-700' : 'text-slate-900'}`}>
                      {t.type === 'CREDIT' ? '+' : '-'}{t.units} Units
                    </td>
                    <td className="py-3 font-mono text-slate-600">{t.unitsAfter}</td>
                    <td className="py-3 font-mono text-slate-400">{new Date(t.createdAt).toLocaleString()}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <p className="text-xs text-slate-400 font-mono text-center py-6">No transactions found.</p>
        )}
      </SmartAuthCard>
    </div>
  );
}
