'use client';

import { useEffect, useMemo, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { Area, AreaChart, CartesianGrid, Legend, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts';
import { AlertCircle, CalendarDays, CheckCircle2, CircleDollarSign, Clock3, Download, FileText, Loader2, RefreshCcw, Search, ShieldAlert, WalletCards } from 'lucide-react';
import { api } from '@/lib/api';

const money = (value?: number | string) => `${Number(value || 0).toLocaleString('vi-VN')} đ`;
const time = (value: string) => new Intl.DateTimeFormat('vi-VN', { dateStyle: 'short', timeStyle: 'short' }).format(new Date(value));
const statusLabel: Record<string, string> = { COMPLETED: 'Đã thanh toán', ESCROW: 'Chờ đối soát', DELIVERED: 'Chờ đối soát', CANCELLED: 'Đã hoàn tiền', DISPUTED: 'Có rủi ro', PENDING: 'Chưa thanh toán' };
const statusTone: Record<string, string> = { COMPLETED: 'bg-emerald-500/10 text-emerald-300', ESCROW: 'bg-amber-500/10 text-amber-300', DELIVERED: 'bg-amber-500/10 text-amber-300', CANCELLED: 'bg-rose-500/10 text-rose-300', DISPUTED: 'bg-red-500/10 text-red-300', PENDING: 'bg-zinc-500/10 text-zinc-300' };

export default function SellerPaymentsPage() {
  const router = useRouter();
  const params = useParams<{ locale: string }>();
  const [data, setData] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [search, setSearch] = useState('');
  const [filter, setFilter] = useState('ALL');

  const load = async () => {
    try { setLoading(true); setError(''); const response = await api.get('/wallet/seller/payments'); setData(response.data); }
    catch (err: any) { setError(err.response?.data?.message || 'Không thể tải dữ liệu thanh toán seller.'); }
    finally { setLoading(false); }
  };
  useEffect(() => {
    const timer = window.setTimeout(() => { void load(); }, 0);
    return () => window.clearTimeout(timer);
  }, []);
  const payments = useMemo(() => (data?.payments || []).filter((payment: any) => {
    const text = `${payment.orderId} ${payment.buyer?.name || ''} ${payment.buyer?.email || ''} ${payment.productName || ''}`.toLowerCase();
    const statusMatch = filter === 'ALL' || (filter === 'RECONCILE' ? ['ESCROW', 'DELIVERED'].includes(payment.status) : filter === 'RISK' ? payment.status === 'DISPUTED' : payment.status === filter);
    return statusMatch && (!search.trim() || text.includes(search.trim().toLowerCase()));
  }), [data, filter, search]);
  const summary = data?.summary || {}; const counts = summary.status || {};
  if (loading) return <div className="flex min-h-[420px] items-center justify-center"><Loader2 className="h-8 w-8 animate-spin text-rose-400" /></div>;

  const cards = [
    { label: 'Doanh thu gộp tháng này', value: money(summary.grossThisMonth), icon: FileText, tone: 'text-rose-300 bg-rose-500/10' },
    { label: 'Thực nhận của shop', value: money(summary.shopReceived), icon: WalletCards, tone: 'text-emerald-300 bg-emerald-500/10' },
    { label: 'Đang chờ đối soát', value: money(summary.pendingReconciliation), icon: Clock3, tone: 'text-amber-300 bg-amber-500/10' },
    { label: 'Hoàn tiền / tranh chấp', value: money(summary.refundOrDispute), icon: RefreshCcw, tone: 'text-red-300 bg-red-500/10' },
  ];
  return <div className="space-y-4 pb-8"><section className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-white/10 bg-[#141414] p-4"><div><h1 className="text-xl font-black text-white">Thanh toán</h1><p className="mt-1 text-xs text-zinc-500">Theo dõi dòng tiền, đối soát và trạng thái thanh toán của đơn bán.</p></div><button onClick={() => void load()} className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-xs font-bold text-zinc-300"><RefreshCcw className="mr-1 inline h-3.5 w-3.5"/>Làm mới</button></section>{error && <div className="rounded-xl border border-red-500/30 bg-red-500/10 px-4 py-3 text-sm text-red-200">{error}</div>}<section className="grid gap-3 md:grid-cols-2 xl:grid-cols-4">{cards.map((card) => { const Icon = card.icon; return <div key={card.label} className="rounded-xl border border-white/10 bg-[#141414] p-4"><span className={`inline-flex rounded-full p-3 ${card.tone}`}><Icon className="h-5 w-5"/></span><p className="mt-3 text-xs text-zinc-500">{card.label}</p><p className="mt-1 text-xl font-black text-white">{card.value}</p><p className="mt-1 text-[10px] text-zinc-600">Theo bộ lọc 30 ngày hiện tại</p></div>; })}</section><section className="grid gap-4 xl:grid-cols-[minmax(0,1.4fr)_300px_300px]"><div className="rounded-xl border border-white/10 bg-[#141414] p-4"><div className="mb-3 flex items-center justify-between"><div><h2 className="font-bold text-white">Dòng tiền 30 ngày</h2><p className="mt-1 text-xs text-zinc-500">Doanh thu gộp và thực nhận đã hoàn thành</p></div><span className="rounded-md border border-white/10 px-2 py-1 text-xs text-zinc-400">30 ngày qua</span></div><div className="h-48"><ResponsiveContainer width="100%" height="100%"><AreaChart data={data?.trend || []}><defs><linearGradient id="grossSeller" x1="0" y1="0" x2="0" y2="1"><stop offset="5%" stopColor="#fb7185" stopOpacity={.35}/><stop offset="95%" stopColor="#fb7185" stopOpacity={0}/></linearGradient></defs><CartesianGrid stroke="#ffffff0c" vertical={false}/><XAxis dataKey="date" tickFormatter={(value) => value.slice(8)} tick={{ fill: '#71717a', fontSize: 10 }} axisLine={false} tickLine={false}/><YAxis tick={{ fill: '#71717a', fontSize: 10 }} axisLine={false} tickLine={false} width={44}/><Tooltip contentStyle={{ background: '#101010', border: '1px solid #ffffff1a', borderRadius: 10 }} formatter={(value: any, name: any) => [money(value), name === 'gross' ? 'Doanh thu gộp' : 'Thực nhận']}/><Legend formatter={(value) => value === 'gross' ? 'Doanh thu gộp' : 'Thực nhận'}/><Area type="monotone" dataKey="gross" name="gross" stroke="#fb7185" strokeWidth={2} fill="url(#grossSeller)"/><Area type="monotone" dataKey="received" name="received" stroke="#a78bfa" strokeWidth={2} fill="transparent"/></AreaChart></ResponsiveContainer></div></div><div className="rounded-xl border border-white/10 bg-[#141414] p-4"><h2 className="font-bold text-white">Cổng thanh toán</h2><div className="mt-5 flex items-center gap-4"><div className="relative flex h-20 w-20 items-center justify-center rounded-full border-[10px] border-rose-500"><CircleDollarSign className="h-7 w-7 text-rose-300"/></div><div><p className="font-bold text-white">Ví hệ thống</p><p className="mt-1 text-sm text-zinc-400">{money(data?.wallet?.availableBalance)}</p><p className="mt-1 text-xs text-zinc-600">Số dư khả dụng</p></div></div><div className="mt-5 h-2 overflow-hidden rounded-full bg-white/5"><div className="h-full w-full bg-rose-500"/></div><p className="mt-2 text-right text-xs text-zinc-500">100% giao dịch nội bộ</p></div><div className="rounded-xl border border-white/10 bg-[#141414] p-4"><h2 className="font-bold text-white">Tình trạng thanh toán</h2><StatusLine label="Đã thanh toán" count={counts.paid || 0} tone="bg-emerald-500/15 text-emerald-300"/><StatusLine label="Chờ đối soát" count={counts.holding || 0} tone="bg-amber-500/15 text-amber-300"/><StatusLine label="Đã hoàn tiền" count={counts.refunded || 0} tone="bg-rose-500/15 text-rose-300"/><StatusLine label="Có rủi ro" count={counts.risk || 0} tone="bg-red-500/15 text-red-300"/></div></section><section className="grid gap-4 xl:grid-cols-[minmax(0,1fr)_280px]"><div className="rounded-xl border border-white/10 bg-[#141414]"><div className="border-b border-white/10 p-3"><div className="flex flex-wrap gap-2">{[{ key: 'ALL', label: 'Tất cả' }, { key: 'COMPLETED', label: 'Đã thanh toán' }, { key: 'RECONCILE', label: 'Chờ đối soát' }, { key: 'CANCELLED', label: 'Hoàn tiền' }, { key: 'RISK', label: 'Có rủi ro' }].map((tab) => <button key={tab.key} onClick={() => setFilter(tab.key)} className={`rounded-md px-3 py-2 text-xs font-bold ${filter === tab.key ? 'bg-rose-500 text-white' : 'bg-white/5 text-zinc-400 hover:text-white'}`}>{tab.label}</button>)}</div><div className="relative mt-3"><Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-zinc-600"/><input value={search} onChange={(event) => setSearch(event.target.value)} placeholder="Tìm theo mã thanh toán, đơn hàng, người mua..." className="w-full rounded-lg border border-white/10 bg-black/25 py-2.5 pl-9 pr-3 text-sm text-white outline-none placeholder:text-zinc-600"/></div></div><div className="overflow-x-auto"><table className="w-full min-w-[850px] text-left"><thead className="border-b border-white/5 text-[10px] uppercase text-zinc-600"><tr><th className="px-4 py-3">Thanh toán</th><th className="px-4 py-3">Đơn hàng</th><th className="px-4 py-3">Người mua</th><th className="px-4 py-3">Số tiền</th><th className="px-4 py-3">Thực nhận</th><th className="px-4 py-3">Trạng thái</th><th className="px-4 py-3">Ngày tạo</th><th className="px-4 py-3"></th></tr></thead><tbody>{payments.length ? payments.map((payment: any) => <tr key={payment.orderId} className="border-b border-white/[.045] text-sm hover:bg-white/[.025]"><td className="px-4 py-3"><p className="font-mono text-xs font-bold text-zinc-200">pay_{payment.id.slice(0, 10)}</p><p className="mt-1 text-[10px] text-zinc-600">Giao dịch ví</p></td><td className="px-4 py-3 font-mono text-xs text-white">ord_{payment.orderId.slice(0, 10)}</td><td className="px-4 py-3"><p className="font-semibold text-zinc-200">{payment.buyer?.name || 'Khách hàng'}</p><p className="text-[10px] text-zinc-600">{payment.buyer?.memberCode || payment.buyer?.email}</p></td><td className="px-4 py-3 font-bold text-white">{money(payment.amount)}</td><td className="px-4 py-3 font-bold text-emerald-300">{payment.status === 'COMPLETED' ? money(payment.netAmount) : '0 đ'}</td><td className="px-4 py-3"><span className={`rounded-full px-2 py-1 text-[10px] font-bold ${statusTone[payment.status] || 'bg-white/5 text-zinc-300'}`}>{statusLabel[payment.status] || payment.status}</span></td><td className="px-4 py-3 text-xs text-zinc-500">{time(payment.createdAt)}</td><td className="px-4 py-3 text-right"><button onClick={() => router.push(`/${params.locale || 'vi'}/seller/orders/${payment.orderId}`)} className="text-xs font-bold text-rose-300 hover:text-rose-200">Xem chi tiết</button></td></tr>) : <tr><td colSpan={8} className="px-4 py-16 text-center text-sm text-zinc-500">Không có giao dịch phù hợp.</td></tr>}</tbody></table></div></div><aside className="space-y-4"><section className="rounded-xl border border-white/10 bg-[#141414] p-4"><h2 className="font-bold text-white">Tóm tắt payout</h2><p className="mt-4 text-xs text-zinc-500">Số dư khả dụng</p><p className="mt-1 text-2xl font-black text-rose-400">{money(data?.wallet?.availableBalance)}</p><p className="mt-4 text-xs text-zinc-500">Tiền đang bảo vệ</p><p className="mt-1 font-bold text-amber-300">{money(data?.wallet?.pendingBalance)}</p><button onClick={() => router.push(`/${params.locale || 'vi'}/seller/withdraw`)} className="mt-5 w-full rounded-lg bg-white/5 px-3 py-2.5 text-xs font-bold text-white hover:bg-white/10">Tạo yêu cầu rút tiền</button></section><section className="rounded-xl border border-white/10 bg-[#141414] p-4"><h2 className="font-bold text-white">Bộ lọc nhanh</h2><div className="mt-3 flex flex-wrap gap-2"><span className="rounded bg-rose-500/15 px-2 py-1 text-xs text-rose-200">30 ngày qua</span><span className="rounded bg-white/5 px-2 py-1 text-xs text-zinc-400">Ví hệ thống</span><span className="rounded bg-white/5 px-2 py-1 text-xs text-zinc-400">VND</span></div><p className="mt-4 text-xs leading-relaxed text-zinc-500">Số liệu hiển thị từ đơn của chính shop, escrow và ví seller.</p></section></aside></section></div>;
}

function StatusLine({ label, count, tone }: { label: string; count: number; tone: string }) { return <div className={`mt-3 flex items-center justify-between rounded-lg px-3 py-2 text-xs font-bold ${tone}`}><span>{label}</span><span>{count}</span></div>; }
