'use client';

import { useEffect, useState } from 'react';
import { api } from '@/lib/api';
import { DataTable, ColumnDef } from '@/components/ui/DataTable';
import { RefreshCw, Search } from 'lucide-react';
import { Toaster, toast } from 'react-hot-toast';

interface PaymentSession {
  id: string;
  user?: { id: string; name?: string; email?: string };
  amount: number;
  currency: string;
  status: string;
  providerCode: string;
  providerName: string;
  method: string;
  providerReference?: string;
  providerTransactionId?: string;
  providerOrderId?: string;
  metadata?: { note?: string; operation?: string };
  webhooks?: Array<{ status: string; error?: string }>;
  createdAt: string;
}

export default function AdminPaymentsPage() {
  const [payments, setPayments] = useState<PaymentSession[]>([]);
  const [loading, setLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [statusFilter, setStatusFilter] = useState('PENDING');
  const [stats, setStats] = useState<Record<string, number>>({});
  const [search, setSearch] = useState('');
  const [actionLoading, setActionLoading] = useState<string | null>(null);
  const limit = 20;

  const getErrorMessage = (error: unknown) => {
    if (typeof error === 'object' && error !== null && 'response' in error) {
      const response = (error as { response?: { data?: { message?: string } } }).response;
      return response?.data?.message || 'Lỗi máy chủ';
    }
    return error instanceof Error ? error.message : 'Lỗi không xác định';
  };

  const fetchPayments = async (status = statusFilter, requestedPage = page) => {
    setLoading(true);
    try {
      const res = await api.get('/admin/payments', { params: { page: requestedPage, limit, status } });
      const items = Array.isArray(res.data?.items) ? res.data.items : [];
      setTotal(Number(res.data?.total || items.length));
      setPayments(items);
    } catch (error) {
      toast.error(`Không thể tải danh sách nạp tiền: ${getErrorMessage(error)}`);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    void fetchPayments();
  }, [page, statusFilter]);

  useEffect(() => {
    api.get('/admin/payments/stats').then((res) => setStats(res.data || {})).catch(() => setStats({}));
  }, []);

  const handleApprove = async (id: string) => {
    if (!confirm('Duyệt yêu cầu nạp tiền này?')) return;
    setActionLoading(`${id}_approve`);
    try {
      await api.patch(`/admin/payments/${id}/approve`, { note: 'Đã duyệt bởi admin' });
      toast.success('Đã duyệt nạp tiền thành công');
      await fetchPayments();
    } catch (error) {
      toast.error(getErrorMessage(error));
    } finally {
      setActionLoading(null);
    }
  };

  const handleReject = async (id: string) => {
    if (!confirm('Từ chối yêu cầu nạp tiền này?')) return;
    setActionLoading(`${id}_reject`);
    try {
      await api.patch(`/admin/payments/${id}/reject`, { note: 'Từ chối bởi admin' });
      toast.success('Đã từ chối nạp tiền');
      await fetchPayments();
    } catch (error) {
      toast.error(getErrorMessage(error));
    } finally {
      setActionLoading(null);
    }
  };

  const columns: ColumnDef<PaymentSession>[] = [
    { header: 'ID', accessorKey: 'id' },
    { header: 'Webhook', cell: (item) => item.webhooks?.[0] ? <span title={item.webhooks[0].error || ''} className="text-xs font-semibold uppercase">{item.webhooks[0].status}</span> : <span className="text-xs text-gray-500">—</span> },
    { header: 'Người dùng', cell: (item) => <div className="flex flex-col text-sm"><span className="font-semibold">{item.user?.name || '—'}</span><span className="text-muted-foreground text-xs">{item.user?.email || '—'}</span></div> },
    { header: 'Số tiền', cell: (item) => `${Number(item.amount).toLocaleString('vi-VN')} ${item.currency}`, align: 'right' },
    { header: 'Hình thức', cell: (item) => `${item.providerName || item.method}${item.metadata?.operation ? ` (${item.metadata.operation})` : ''}` },
    { header: 'Tham chiếu', cell: (item) => item.providerReference || item.providerTransactionId || item.providerOrderId || '—' },
    { header: 'Ghi chú', cell: (item) => item.metadata?.note || '—' },
    { header: 'Trạng thái', cell: (item) => <span className="text-xs font-semibold uppercase">{item.status}</span>, align: 'center' },
    { header: 'Ngày tạo', cell: (item) => new Date(item.createdAt).toLocaleString('vi-VN'), align: 'right' },
    { header: 'Hành động', cell: (item) => item.providerCode === 'MANUAL' && item.status === 'PENDING' ? <div className="flex items-center justify-end gap-2"><button disabled={Boolean(actionLoading?.startsWith(item.id))} onClick={() => handleApprove(item.id)} className="rounded-lg bg-emerald-500/10 px-3 py-1 text-xs text-emerald-300 hover:bg-emerald-500/20 disabled:opacity-50">Duyệt</button><button disabled={Boolean(actionLoading?.startsWith(item.id))} onClick={() => handleReject(item.id)} className="rounded-lg bg-red-500/10 px-3 py-1 text-xs text-red-300 hover:bg-red-500/20 disabled:opacity-50">Từ chối</button></div> : <span className="text-xs text-gray-500">{item.status === 'PENDING' ? 'Chờ webhook' : 'Đã xử lý'}</span>, align: 'right' },
  ];

  const totalPages = Math.max(1, Math.ceil(total / limit));
  const filteredPayments = payments.filter((item) => {
    const query = search.trim().toLowerCase();
    return !query || `${item.user?.name || ''} ${item.user?.email || ''} ${item.providerName || ''}`.toLowerCase().includes(query);
  });

  return (
    <div className="space-y-6">
      <Toaster position="top-right" />
      <div className="flex flex-col items-start justify-between gap-4 md:flex-row md:items-center">
        <div>
          <h1 className="text-2xl font-bold text-white">Quản lý giao dịch nạp tiền</h1>
          <p className="mt-1 text-sm text-gray-400">Theo dõi yêu cầu nạp tiền và trạng thái xử lý. Cộng/trừ số dư được thực hiện trong chi tiết người dùng.</p>
        </div>
        <button onClick={() => void fetchPayments()} className="inline-flex items-center gap-2 rounded-xl border border-white/10 bg-white/5 px-4 py-2 text-sm text-gray-300 hover:bg-white/10"><RefreshCw className="h-4 w-4" /> Làm mới</button>
      </div>

      <div className="grid gap-4 md:grid-cols-4">
        {[['Tổng yêu cầu', stats.total ?? total, 'text-blue-400'], ['Đang chờ', stats.pending ?? 0, 'text-yellow-400'], ['Hoàn tất', stats.completed ?? 0, 'text-green-400'], ['Thất bại', stats.failed ?? 0, 'text-red-400']].map(([label, value, color]) => <div key={String(label)} className="rounded-2xl border border-white/10 bg-[#141414] p-5"><p className="text-xs text-gray-400">{label}</p><p className={`mt-3 text-2xl font-bold ${color}`}>{value}</p></div>)}
      </div>

      <div className="space-y-6">
        <div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
          <div className="flex flex-wrap gap-2">{['PENDING', 'WAITING_PAYMENT', 'COMPLETED', 'FAILED', 'CANCELLED', 'EXPIRED'].map((status) => <button key={status} onClick={() => { setStatusFilter(status); setPage(1); }} className={`rounded-xl px-3 py-2 text-xs font-semibold ${statusFilter === status ? 'border border-red-500/30 bg-red-500/20 text-red-300' : 'bg-white/5 text-gray-300 hover:bg-white/10'}`}>{status}</button>)}</div>
          <div className="relative min-w-[220px] flex-1"><input value={search} onChange={(event) => setSearch(event.target.value)} placeholder="Tìm theo người dùng hoặc provider..." className="w-full rounded-xl border border-white/10 bg-[#101010] px-4 py-2 text-sm text-white focus:outline-none focus:border-red-500" /><Search className="absolute right-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-500" /></div>
        </div>
        <DataTable columns={columns} data={filteredPayments} searchPlaceholder="Tìm kiếm..." searchValue={search} onSearchChange={setSearch} emptyMessage={loading ? 'Đang tải...' : 'Không tìm thấy giao dịch nạp tiền'} />
      </div>

      <div className="flex items-center justify-between text-sm text-gray-500"><p>Trang {page} / {totalPages}</p><div className="flex items-center gap-2"><button disabled={page === 1} onClick={() => setPage((current) => Math.max(1, current - 1))} className="rounded-xl border border-white/10 px-3 py-2 text-xs font-semibold disabled:opacity-40">Trước</button><button disabled={page === totalPages} onClick={() => setPage((current) => Math.min(totalPages, current + 1))} className="rounded-xl border border-white/10 px-3 py-2 text-xs font-semibold disabled:opacity-40">Tiếp</button></div></div>
    </div>
  );
}
