'use client';
import { useEffect, useState, useCallback } from 'react';
import { adminService } from '@/services/admin.service';
import type { OrderInfo, PaginationMeta, TradeInfo } from '@/types/admin.types';

type BadgeColor = 'green' | 'red' | 'yellow' | 'blue' | 'gray' | 'purple' | 'orange';
function StatusBadge({ label, color }: { label: string; color: BadgeColor }) {
  const colors: Record<string, string> = {
    green: 'bg-emerald-500/20 text-emerald-400 border-emerald-500/30', red: 'bg-red-500/20 text-red-400 border-red-500/30',
    yellow: 'bg-amber-500/20 text-amber-400 border-amber-500/30', blue: 'bg-blue-500/20 text-blue-400 border-blue-500/30',
    gray: 'bg-slate-500/20 text-slate-400 border-slate-500/30', purple: 'bg-purple-500/20 text-purple-400 border-purple-500/30',
    orange: 'bg-orange-500/20 text-orange-400 border-orange-500/30',
  };
  return <span className={`inline-flex rounded-full border px-2 py-0.5 text-[10px] font-semibold uppercase ${colors[color] || colors.gray}`}>{label}</span>;
}

export default function AdminOrdersPage() {
  const [orders, setOrders] = useState<OrderInfo[]>([]);
  const [trades, setTrades] = useState<TradeInfo[]>([]);
  const [meta, setMeta] = useState<PaginationMeta | null>(null);
  const [loading, setLoading] = useState(true);
  const [tab, setTab] = useState<'orders' | 'trades'>('orders');
  const [statusFilter, setStatusFilter] = useState('');
  const [page, setPage] = useState(1);
  const [actionMsg, setActionMsg] = useState('');

  const [resolveOpen, setResolveOpen] = useState<string | null>(null);
  const [resolveText, setResolveText] = useState('');
  const [releaseOpen, setReleaseOpen] = useState<string | null>(null);
  const [releaseNotes, setReleaseNotes] = useState('');
  const [actionLoading, setActionLoading] = useState(false);

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const params: any = { page, limit: 20 };
      if (statusFilter) params.status = statusFilter;
      if (tab === 'orders') {
        const res = await adminService.listOrders(params);
        setOrders(res.data); setMeta(res.meta);
      } else {
        const res = await adminService.getTradeHistory(params);
        setTrades(res.data); setMeta(res.meta);
      }
    } catch (e) { console.error(e); }
    finally { setLoading(false); }
  }, [page, statusFilter, tab]);

  useEffect(() => { fetchData(); }, [fetchData]);

  const handleCancelOrder = async (orderId: string) => {
    try {
      await adminService.cancelOrder({ orderId, reason: 'Admin cancelled' });
      setActionMsg('Order cancelled'); fetchData();
    } catch (e: any) { setActionMsg(e?.response?.data?.message || 'Error'); }
  };

  const handleResolveDispute = async (orderId: string) => {
    if (!resolveText.trim()) { setActionMsg('Resolution reason is required'); return; }
    setActionLoading(true);
    try {
      await adminService.resolveDispute({ orderId, resolution: resolveText.trim() });
      setActionMsg('Dispute resolved'); setResolveOpen(null); setResolveText(''); fetchData();
    } catch (e: any) { setActionMsg(e?.response?.data?.message || 'Error resolving dispute'); }
    finally { setActionLoading(false); }
  };

  const handleReleaseFunds = async (tradeId: string) => {
    setActionLoading(true);
    try {
      await adminService.releaseFunds({ tradeId, notes: releaseNotes.trim() || undefined });
      setActionMsg('Funds released'); setReleaseOpen(null); setReleaseNotes(''); fetchData();
    } catch (e: any) { setActionMsg(e?.response?.data?.message || 'Error releasing funds'); }
    finally { setActionLoading(false); }
  };

  const statusColor = (s: string): BadgeColor => {
    const map: Record<string, BadgeColor> = { PENDING: 'yellow', OPEN: 'blue', MATCHED: 'purple', PARTIALLY_FILLED: 'orange', COMPLETED: 'green', CANCELLED: 'red', EXPIRED: 'gray', DISPUTED: 'red' };
    return map[s] || 'gray';
  };

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold text-white">Order Management</h1>
          <p className="mt-1 text-sm text-white/50">View, cancel orders and resolve disputes</p>
        </div>
      </div>

      <div className="flex gap-4 border-b border-white/10">
        {(['orders', 'trades'] as const).map((t) => (
          <button key={t} onClick={() => { setTab(t); setPage(1); }} className={`pb-2 text-sm font-medium capitalize ${tab === t ? 'text-white border-b-2 border-indigo-400' : 'text-slate-500 hover:text-slate-300'}`}>{t}</button>
        ))}
      </div>

      <div className="flex flex-wrap gap-3">
        <select value={statusFilter} onChange={(e) => { setStatusFilter(e.target.value); setPage(1); }} className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-xs text-white">
          <option value="">All Status</option>
          <option value="PENDING">Pending</option>
          <option value="OPEN">Open</option>
          <option value="MATCHED">Matched</option>
          <option value="COMPLETED">Completed</option>
          <option value="CANCELLED">Cancelled</option>
          <option value="DISPUTED">Disputed</option>
        </select>
        <button onClick={fetchData} className="rounded-lg bg-white/10 px-3 py-2 text-xs text-white/70 hover:bg-white/20">Refresh</button>
      </div>

      {actionMsg && <div className="rounded-lg bg-blue-500/10 p-3 text-sm text-blue-400">{actionMsg}</div>}

      <div className="overflow-x-auto rounded-xl border border-white/5">
        <table className="w-full text-left text-sm">
          <thead className="border-b border-white/5 bg-white/[0.02]">
            <tr>
              {tab === 'orders' ? (
                <><th className="px-4 py-3 text-slate-400">ID</th><th className="px-4 py-3 text-slate-400">User</th><th className="px-4 py-3 text-slate-400">Side</th><th className="px-4 py-3 text-slate-400">Currency</th><th className="px-4 py-3 text-slate-400">Price</th><th className="px-4 py-3 text-slate-400">Qty</th><th className="px-4 py-3 text-slate-400">Filled</th><th className="px-4 py-3 text-slate-400">Status</th><th className="px-4 py-3 text-slate-400">Actions</th></>
              ) : (
                <><th className="px-4 py-3 text-slate-400">ID</th><th className="px-4 py-3 text-slate-400">Buyer</th><th className="px-4 py-3 text-slate-400">Seller</th><th className="px-4 py-3 text-slate-400">Currency</th><th className="px-4 py-3 text-slate-400">Price</th><th className="px-4 py-3 text-slate-400">Qty</th><th className="px-4 py-3 text-slate-400">Status</th><th className="px-4 py-3 text-slate-400">Escrow</th><th className="px-4 py-3 text-slate-400">Actions</th></>
              )}
            </tr>
          </thead>
          <tbody>
            {loading ? <tr><td colSpan={tab === 'orders' ? 9 : 10} className="px-4 py-8 text-center text-slate-500">Loading...</td></tr>
            : (tab === 'orders' ? orders : trades).length === 0 ? <tr><td colSpan={tab === 'orders' ? 9 : 10} className="px-4 py-8 text-center text-slate-500">No data</td></tr>
            : tab === 'orders' ? orders.map((o) => (
              <tr key={o.id} className="border-b border-white/5 hover:bg-white/[0.02]">
                <td className="px-4 py-3 font-mono text-xs text-slate-400">{o.id.slice(0, 8)}...</td>
                <td className="px-4 py-3"><span className="text-white">{o.user?.firstName} {o.user?.lastName}</span><br /><span className="text-xs text-slate-400">{o.user?.email}</span></td>
                <td className="px-4 py-3"><StatusBadge label={o.side} color={o.side === 'BUY' ? 'green' : 'red'} /></td>
                <td className="px-4 py-3 text-white">{o.currency}</td>
                <td className="px-4 py-3 font-mono">${Number(o.price).toLocaleString()}</td>
                <td className="px-4 py-3 font-mono">{Number(o.quantity).toFixed(4)}</td>
                <td className="px-4 py-3 font-mono">{Number(o.filledAmount).toFixed(4)}</td>
                <td className="px-4 py-3"><StatusBadge label={o.status} color={statusColor(o.status)} /></td>
                <td className="px-4 py-3">
                  {o.status === 'PENDING' || o.status === 'OPEN' ? (
                    <button onClick={() => handleCancelOrder(o.id)} className="rounded-lg bg-red-500/10 px-3 py-1.5 text-xs text-red-400 hover:bg-red-500/20">Cancel</button>
                  ) : o.status === 'DISPUTED' ? (
                    resolveOpen === o.id ? (
                      <div className="space-y-2">
                        <textarea value={resolveText} onChange={(e) => setResolveText(e.target.value)} placeholder="Resolution reason..." className="w-full rounded-lg border border-white/10 bg-white/5 px-2 py-1 text-xs text-white placeholder-slate-500" rows={2} />
                        <div className="flex gap-2">
                          <button onClick={() => handleResolveDispute(o.id)} disabled={actionLoading} className="rounded-lg bg-emerald-500/10 px-2 py-1 text-xs text-emerald-400 hover:bg-emerald-500/20 disabled:opacity-50">Submit</button>
                          <button onClick={() => { setResolveOpen(null); setResolveText(''); }} className="rounded-lg bg-white/10 px-2 py-1 text-xs text-white/70 hover:bg-white/20">Cancel</button>
                        </div>
                      </div>
                    ) : (
                      <button onClick={() => setResolveOpen(o.id)} className="rounded-lg bg-amber-500/10 px-3 py-1.5 text-xs text-amber-400 hover:bg-amber-500/20">Resolve</button>
                    )
                  ) : <span className="text-xs text-slate-500">-</span>}
                </td>
              </tr>
            )) : trades.map((t) => (
              <tr key={t.id} className="border-b border-white/5 hover:bg-white/[0.02]">
                <td className="px-4 py-3 font-mono text-xs text-slate-400">{t.id.slice(0, 8)}...</td>
                <td className="px-4 py-3 text-white">{t.buyer?.email}</td>
                <td className="px-4 py-3 text-white">{t.seller?.email}</td>
                <td className="px-4 py-3 text-white">{t.currency}</td>
                <td className="px-4 py-3 font-mono">${Number(t.price).toLocaleString()}</td>
                <td className="px-4 py-3 font-mono">{Number(t.quantity).toFixed(4)}</td>
                <td className="px-4 py-3"><StatusBadge label={t.status} color={statusColor(t.status)} /></td>
                <td className="px-4 py-3">{t.escrow ? <StatusBadge label={t.escrow.status} color={t.escrow.status === 'LOCKED' ? 'yellow' : 'green'} /> : <span className="text-xs text-slate-500">-</span>}</td>
                <td className="px-4 py-3">
                  {t.escrow?.status === 'LOCKED' ? (
                    releaseOpen === t.id ? (
                      <div className="space-y-2">
                        <textarea value={releaseNotes} onChange={(e) => setReleaseNotes(e.target.value)} placeholder="Notes (optional)..." className="w-full rounded-lg border border-white/10 bg-white/5 px-2 py-1 text-xs text-white placeholder-slate-500" rows={2} />
                        <div className="flex gap-2">
                          <button onClick={() => handleReleaseFunds(t.id)} disabled={actionLoading} className="rounded-lg bg-emerald-500/10 px-2 py-1 text-xs text-emerald-400 hover:bg-emerald-500/20 disabled:opacity-50">Release</button>
                          <button onClick={() => { setReleaseOpen(null); setReleaseNotes(''); }} className="rounded-lg bg-white/10 px-2 py-1 text-xs text-white/70 hover:bg-white/20">Cancel</button>
                        </div>
                      </div>
                    ) : (
                      <button onClick={() => setReleaseOpen(t.id)} className="rounded-lg bg-emerald-500/10 px-3 py-1.5 text-xs text-emerald-400 hover:bg-emerald-500/20">Release Funds</button>
                    )
                  ) : <span className="text-xs text-slate-500">-</span>}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {meta && (
        <div className="flex items-center justify-between">
          <p className="text-xs text-slate-500">Page {meta.page} of {meta.totalPages} ({meta.total} total)</p>
          <div className="flex gap-2">
            <button disabled={page <= 1} onClick={() => setPage(page - 1)} className="rounded-lg bg-white/5 px-3 py-1.5 text-xs text-white disabled:opacity-30 hover:bg-white/10">Previous</button>
            <button disabled={page >= meta.totalPages} onClick={() => setPage(page + 1)} className="rounded-lg bg-white/5 px-3 py-1.5 text-xs text-white disabled:opacity-30 hover:bg-white/10">Next</button>
          </div>
        </div>
      )}
    </div>
  );
}
