'use client';

import { useEffect, useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { EmptyState } from '@/components/ui/empty-state';
import { formatCurrency, formatDateTime } from '@/lib/utils';
import { getErrorMessage } from '@/lib/errors';
import { walletService, type WalletHistoryItem } from '@/services/wallet.service';
import { ArrowDownLeft, ArrowUpRight, History } from 'lucide-react';

const TYPE_FILTERS = [
  { id: 'all', label: 'All' },
  { id: 'DEPOSIT', label: 'Deposits' },
  { id: 'WITHDRAWAL', label: 'Withdrawals' },
  { id: 'TRANSFER', label: 'Transfers' },
  { id: 'ORDER', label: 'Orders' },
  { id: 'COMMISSION', label: 'Commission' },
] as const;

const statusVariant: Record<string, 'success' | 'warning' | 'danger'> = {
  COMPLETED: 'success',
  PENDING: 'warning',
  FAILED: 'danger',
  CANCELLED: 'danger',
  REVERSED: 'danger',
};

export default function UserTransactionsPage() {
  const [loading, setLoading] = useState(true);
  const [items, setItems] = useState<WalletHistoryItem[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [activeType, setActiveType] = useState<(typeof TYPE_FILTERS)[number]['id']>('all');
  const [searchQuery, setSearchQuery] = useState('');

  const filtered = items.filter((tx) => {
    if (activeType !== 'all' && tx.type !== activeType) return false;
    if (searchQuery) {
      const q = searchQuery.toLowerCase();
      return (
        tx.description?.toLowerCase().includes(q) ||
        tx.type.toLowerCase().includes(q) ||
        tx.id.toLowerCase().includes(q)
      );
    }
    return true;
  });

  useEffect(() => {
    let active = true;
    (async () => {
      try {
        const res = await walletService.getHistory({ limit: 50 });
        if (!active) return;
        setItems(res.data ?? []);
      } catch (err) {
        if (active) setError(getErrorMessage(err));
      } finally {
        if (active) setLoading(false);
      }
    })();
    return () => { active = false; };
  }, []);

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold tracking-tight text-ink">Transactions</h1>
        <p className="mt-1 text-sm text-ink-muted">View and manage your transaction history</p>
      </div>

      <Card>
        <CardHeader className="flex-row items-center justify-between space-y-0">
          <div>
            <CardTitle>Transaction History</CardTitle>
            <CardDescription>All your past transactions in one place</CardDescription>
          </div>
        </CardHeader>
        <CardContent>
          {/* Filters */}
          <div className="mb-4 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
            <div className="flex flex-wrap gap-2">
              {TYPE_FILTERS.map((t) => (
                <button
                  key={t.id}
                  onClick={() => setActiveType(t.id)}
                  className={`rounded-full px-3 py-1.5 text-xs font-medium transition-colors ${
                    activeType === t.id
                      ? 'bg-primary-600 text-white'
                      : 'bg-surface-raised text-ink-muted hover:text-ink'
                  }`}
                >
                  {t.label}
                </button>
              ))}
            </div>
            <input
              type="text"
              placeholder="Search transactions..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="input w-full sm:w-64"
            />
          </div>

          {loading ? (
            <div className="space-y-3">
              {Array.from({ length: 5 }).map((_, i) => (
                <Skeleton key={i} className="h-12 w-full" />
              ))}
            </div>
          ) : error ? (
            <p className="text-sm text-red-500">{error}</p>
          ) : filtered.length === 0 ? (
            <div className="py-8">
              <EmptyState
                icon={History}
                title="No transactions yet"
                description="Your completed activity will appear here once you start trading."
                action={
                  <a href="/dashboard/referral" className="text-sm font-medium text-primary-600 hover:underline">
                    Refer Friends
                  </a>
                }
              />
            </div>
          ) : (
            <div className="divide-y divide-line">
              {filtered.map((tx) => {
                const isCredit = tx.amount >= 0;
                return (
                  <div key={tx.id} className="flex items-center justify-between py-3 first:pt-0 last:pb-0">
                    <div className="flex items-center gap-3">
                      <div
                        className={`flex h-10 w-10 shrink-0 items-center justify-center rounded-xl ${
                          isCredit ? 'bg-emerald-500/10 text-emerald-500' : 'bg-surface-raised text-ink-muted'
                        }`}
                      >
                        {isCredit ? <ArrowDownLeft className="h-4 w-4" /> : <ArrowUpRight className="h-4 w-4" />}
                      </div>
                      <div>
                        <p className="text-sm font-medium text-ink">{tx.type.replace(/_/g, ' ')}</p>
                        <p className="text-xs text-ink-faint">{tx.description ?? tx.id}</p>
                        <p className="text-xs text-ink-faint">{formatDateTime(tx.createdAt)}</p>
                      </div>
                    </div>
                    <div className="text-right">
                      <p className={`text-sm font-semibold ${tx.amount >= 0 ? 'text-emerald-600' : 'text-red-600'}`}>
                        {tx.amount >= 0 ? '+' : ''}{formatCurrency(tx.amount)}
                      </p>
                      {tx.status && (
                        <Badge variant={statusVariant[tx.status] ?? 'success'} className="mt-0.5">
                          {tx.status.toLowerCase()}
                        </Badge>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
