'use client';

import { useEffect, useMemo, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import {
  ArrowLeft, CheckCircle2, CircleDollarSign, Clock3, Download, FileText,
  Loader2, MessageCircle, Package, RefreshCcw, ShieldAlert, ShieldCheck,
  Store, UserRound, WalletCards, XCircle,
} from 'lucide-react';
import { api } from '@/lib/api';

const money = (value?: number | string) => `${Number(value || 0).toLocaleString('vi-VN')} đ`;
const dateTime = (value?: string | null) => value ? new Intl.DateTimeFormat('vi-VN', { dateStyle: 'short', timeStyle: 'short' }).format(new Date(value)) : 'Chưa có';

const statusStyle: Record<string, string> = {
  PENDING: 'border-amber-400/30 bg-amber-400/10 text-amber-300',
  ESCROW: 'border-violet-400/30 bg-violet-400/10 text-violet-300',
  DELIVERED: 'border-cyan-400/30 bg-cyan-400/10 text-cyan-300',
  COMPLETED: 'border-emerald-400/30 bg-emerald-400/10 text-emerald-300',
  DISPUTED: 'border-red-400/30 bg-red-400/10 text-red-300',
  CANCELLED: 'border-rose-400/30 bg-rose-400/10 text-rose-300',
};
const statusText: Record<string, string> = { PENDING: 'Chờ thanh toán', ESCROW: 'Đang giữ tiền', DELIVERED: 'Đã bàn giao', COMPLETED: 'Hoàn thành', DISPUTED: 'Tranh chấp', CANCELLED: 'Đã hoàn tiền' };

export default function AdminOrderDetailPage() {
  const router = useRouter();
  const params = useParams<{ id: string; locale: string }>();
  const [order, setOrder] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [refunding, setRefunding] = useState(false);
  const [downloading, setDownloading] = useState(false);

  const load = async () => {
    try {
      setLoading(true); setError('');
      const response = await api.get(`/admin/orders/${params.id}`);
      setOrder(response.data);
    } catch (err: any) { setError(err.response?.data?.message || 'Không thể tải chi tiết đơn hàng.'); }
    finally { setLoading(false); }
  };
  useEffect(() => {
    if (!params.id) return;
    const timer = window.setTimeout(() => { void load(); }, 0);
    return () => window.clearTimeout(timer);
  }, [params.id]);

  const canRefund = Boolean(order?.escrow && ['HOLD', 'RELEASED'].includes(order.escrow.status) && order?.status !== 'CANCELLED');
  const deliveryRows = order?.allocations || [];
  const timeline = useMemo(() => order ? [
    { label: 'Đặt hàng', time: order.createdAt, done: true },
    { label: 'Thanh toán', time: order.escrow?.heldAt || order.createdAt, done: Boolean(order.escrow) },
    { label: 'Đã giao hàng', time: order.deliveredAt, done: ['DELIVERED', 'COMPLETED'].includes(order.status) },
    { label: order.escrow?.status === 'REFUNDED' ? 'Đã hoàn tiền' : 'Giữ tiền', time: order.escrow?.refundedAt || order.escrow?.heldAt, done: Boolean(order.escrow) },
    { label: 'Đã xong', time: order.confirmedAt, done: order.status === 'COMPLETED' },
  ] : [], [order]);

  const refund = async () => {
    if (!order || !confirm(`Hoàn ${money(order.totalAmount)} về ví người mua? Hành động này sẽ hủy đơn và không thể hoàn tác.`)) return;
    try {
      setRefunding(true); setError('');
      await api.post(`/admin/orders/${order.id}/refund`);
      await load();
    } catch (err: any) { setError(err.response?.data?.message || 'Không thể hoàn tiền đơn hàng này.'); }
    finally { setRefunding(false); }
  };
  const download = async () => {
    if (!order) return;
    try {
      setDownloading(true);
      const response = await api.get(`/admin/orders/${order.id}/download`, { responseType: 'blob' });
      const disposition = String(response.headers['content-disposition'] || '');
      const filename = disposition.match(/filename="?([^";]+)"?/i)?.[1] || `order-${order.id}.zip`;
      const url = URL.createObjectURL(response.data); const link = document.createElement('a'); link.href = url; link.download = filename; link.click(); URL.revokeObjectURL(url);
    } catch (err: any) { setError(err.response?.data?.message || 'Đơn này chưa có tệp giao tự động để tải.'); }
    finally { setDownloading(false); }
  };

  if (loading) return <div className="flex min-h-[460px] items-center justify-center"><Loader2 className="h-8 w-8 animate-spin text-rose-400" /></div>;
  if (!order) return <div className="rounded-2xl border border-red-500/30 bg-red-500/10 p-6 text-red-200"><p>{error || 'Không tìm thấy đơn hàng.'}</p><button onClick={() => router.back()} className="mt-4 rounded-lg border border-red-300/30 px-3 py-2 text-sm font-bold">Quay lại</button></div>;

  return <div className="mx-auto max-w-[1540px] space-y-4 pb-10">
    <section className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-white/10 bg-[#141414] px-4 py-3"><div><button onClick={() => router.push(`/${params.locale}/admin/orders`)} className="mb-2 inline-flex items-center gap-1 text-xs font-bold text-zinc-500 hover:text-white"><ArrowLeft className="h-3.5 w-3.5"/>Quản lý đơn hàng</button><h1 className="text-xl font-black text-white">Chi tiết đơn hàng</h1><p className="mt-1 text-xs text-zinc-500">Theo dõi thanh toán, bàn giao, hội thoại và khiếu nại bằng dữ liệu thực tế.</p></div><div className="flex items-center gap-2"><span className={`rounded-lg border px-3 py-2 text-xs font-bold ${statusStyle[order.status] || 'border-white/10 bg-white/5 text-zinc-300'}`}>{statusText[order.status] || order.status}</span><button onClick={() => void load()} className="rounded-lg border border-white/10 bg-white/5 p-2 text-zinc-300 hover:bg-white/10" title="Làm mới"><RefreshCcw className="h-4 w-4"/></button></div></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>}

    <div className="grid gap-4 xl:grid-cols-[minmax(0,1fr)_300px]"><main className="space-y-4"><section className="rounded-xl border border-white/10 bg-[#141414] p-5"><div className="grid gap-5 lg:grid-cols-2"><div><p className="text-xs text-zinc-500">Mã đơn hàng</p><p className="mt-1 font-mono text-base font-black text-white">ord_{order.id}</p><div className="mt-5 flex items-center gap-3"><span className="rounded-full bg-rose-500/10 p-2 text-rose-300"><UserRound className="h-4 w-4"/></span><div><p className="text-[11px] text-zinc-500">Người mua</p><p className="font-bold text-white">{order.buyer?.name || '—'}</p><p className="text-xs text-zinc-500">ID {order.buyer?.memberCode || order.buyer?.id}</p></div></div><div className="mt-5"><p className="text-xs text-zinc-500">Tổng tiền đơn hàng</p><p className="mt-1 text-2xl font-black text-white">{money(order.totalAmount)}</p><p className="mt-4 text-xs text-zinc-500">Thanh toán</p><p className="mt-1 font-bold text-emerald-300">{order.escrow ? 'Đã thanh toán' : 'Chưa có thanh toán'}</p></div></div><div className="border-white/10 lg:border-l lg:pl-5"><p className="text-xs text-zinc-500">Thời gian đặt</p><p className="mt-1 font-bold text-white">{dateTime(order.createdAt)}</p><div className="mt-5 flex items-center gap-3"><span className="rounded-full bg-rose-500/10 p-2 text-rose-300"><Store className="h-4 w-4"/></span><div><p className="text-[11px] text-zinc-500">Người bán</p><p className="font-bold text-white">{order.seller?.name || '—'}</p><p className="text-xs text-zinc-500">ID {order.seller?.memberCode || order.seller?.id}</p></div></div><div className="mt-5"><p className="text-xs text-zinc-500">Doanh thu shop nhận</p><p className="mt-1 text-2xl font-black text-emerald-300">{money(order.sellerPayout)}</p><p className="mt-1 text-xs text-zinc-500">Đã trừ phí sàn {money(order.platformFee)}</p></div></div></div><div className="mt-6 grid grid-cols-1 gap-3 md:grid-cols-5">{timeline.map((item, index) => <div key={item.label} className="relative min-h-16 border-t border-white/10 pt-3 md:border-l md:border-t-0 md:pl-3"><span className={`mb-2 block h-3 w-3 rounded-full ${item.done ? 'bg-emerald-400 shadow-[0_0_0_4px_rgba(52,211,153,.12)]' : 'bg-zinc-700'}`}/><p className="text-xs font-bold text-zinc-200">{item.label}</p><p className="mt-1 text-[10px] text-zinc-500">{dateTime(item.time)}</p></div>)}</div></section>

      <section className="rounded-xl border border-white/10 bg-[#141414]"><h2 className="border-b border-white/10 px-5 py-4 font-bold text-white">Sản phẩm trong đơn</h2><div className="divide-y divide-white/5">{order.items?.map((item: any) => <div key={item.id} className="grid gap-4 p-5 md:grid-cols-[1fr_auto_auto_auto]"><div className="flex gap-3"><div className="flex h-14 w-14 shrink-0 items-center justify-center rounded-lg bg-sky-500/15 text-sky-300"><Package className="h-6 w-6"/></div><div><span className="rounded bg-white/5 px-2 py-0.5 text-[10px] text-zinc-400">Sản phẩm số</span><p className="mt-1 font-bold text-white">{item.product?.name || 'Sản phẩm'}</p><p className="mt-1 text-xs text-zinc-500">SKU: {item.variant?.name || 'Mặc định'} · {item.product?.deliveryMethod === 'AUTO_TXT' ? 'Giao TXT tự động' : item.product?.deliveryMethod === 'AUTO_ZIP' ? 'Giao ZIP tự động' : 'Giao thủ công'}</p></div></div><Metric label="Đơn giá" value={money(item.price)}/><Metric label="Số lượng" value={`x${item.quantity}`}/><Metric label="Thành tiền" value={money(Number(item.price) * item.quantity)}/></div>)}</div></section>

      <section className="rounded-xl border border-white/10 bg-[#141414]"><div className="flex flex-wrap items-center justify-between gap-3 border-b border-white/10 px-5 py-4"><div><h2 className="font-bold text-white">Danh sách đơn vị bàn giao ({deliveryRows.length})</h2><p className="mt-1 text-xs text-zinc-500">Thông tin kho chỉ hiển thị cho quản trị viên.</p></div><button onClick={download} disabled={downloading} className="rounded-lg border border-emerald-400/30 bg-emerald-500/10 px-3 py-2 text-xs font-bold text-emerald-300 disabled:opacity-50"><Download className="mr-1 inline h-4 w-4"/>{downloading ? 'Đang chuẩn bị...' : 'Tải đơn hàng'}</button></div>{deliveryRows.length ? <div className="overflow-x-auto"><table className="w-full min-w-[650px] text-left text-sm"><thead className="border-b border-white/5 text-[10px] uppercase text-zinc-600"><tr><th className="px-5 py-3">STT</th><th className="px-5 py-3">Mã hàng / vị trí</th><th className="px-5 py-3">Trạng thái</th><th className="px-5 py-3">Thời điểm giao</th></tr></thead><tbody>{deliveryRows.map((allocation: any, index: number) => <tr key={allocation.id} className="border-b border-white/[.04]"><td className="px-5 py-3 text-zinc-400">{index + 1}</td><td className="px-5 py-3"><p className="font-mono text-xs font-bold text-white">{allocation.inventoryItem?.folderName || allocation.inventoryItemId}</p></td><td className="px-5 py-3"><span className="rounded bg-emerald-500/10 px-2 py-1 text-xs font-bold text-emerald-300">{allocation.inventoryItem?.status || 'DELIVERED'}</span></td><td className="px-5 py-3 text-xs text-zinc-400">{dateTime(allocation.createdAt)}</td></tr>)}</tbody></table></div> : <p className="p-5 text-sm text-zinc-500">Đơn này không có dữ liệu kho tự động. Hàng có thể được giao thủ công qua chat.</p>}</section>

      <section className="grid gap-4 lg:grid-cols-2"><div className="rounded-xl border border-white/10 bg-[#141414]"><div className="flex items-center gap-2 border-b border-white/10 px-5 py-4"><MessageCircle className="h-4 w-4 text-violet-300"/><h2 className="font-bold text-white">Trao đổi về đơn hàng</h2></div><div className="max-h-72 space-y-3 overflow-y-auto p-4">{order.messages?.length ? order.messages.map((message: any) => <div key={message.id} className="rounded-lg bg-white/[.035] p-3"><div className="flex justify-between gap-3"><p className="text-xs font-bold text-cyan-300">{message.sender?.name || 'Thành viên'} <span className="text-zinc-600">· {message.sender?.role?.name || 'USER'}</span></p><time className="text-[10px] text-zinc-600">{dateTime(message.createdAt)}</time></div><p className="mt-2 text-sm text-zinc-300">{message.content}</p></div>) : <p className="py-8 text-center text-sm text-zinc-500">Chưa có trao đổi cho đơn này.</p>}</div></div><div className="rounded-xl border border-white/10 bg-[#141414] p-5"><div className="flex items-center gap-2"><ShieldAlert className="h-4 w-4 text-rose-300"/><h2 className="font-bold text-white">Hỗ trợ & khiếu nại</h2></div>{order.dispute ? <div className="mt-4 rounded-lg border border-rose-400/30 bg-rose-500/10 p-3"><p className="text-sm font-bold text-rose-200">{order.dispute.status === 'RESOLVED' ? 'Khiếu nại đã xử lý' : 'Đang có khiếu nại'}</p><p className="mt-2 text-sm text-zinc-300">{order.dispute.reason || 'Chưa có nội dung.'}</p><p className="mt-3 text-xs text-zinc-500">Tạo lúc: {dateTime(order.dispute.createdAt)}</p></div> : <div className="mt-4 rounded-lg border border-emerald-400/20 bg-emerald-500/5 p-3 text-sm text-emerald-300">Không có khiếu nại đang mở.</div>}</div></section></main>

      <aside className="h-fit space-y-4 xl:sticky xl:top-4"><section className="rounded-xl border border-white/10 bg-[#141414] p-5"><h2 className="font-bold text-white">Tóm tắt thanh toán</h2><div className="mt-4 space-y-3 border-b border-white/10 pb-4"><SummaryRow label="Tổng tiền đơn hàng" value={money(order.totalAmount)}/><SummaryRow label="Phí nền tảng" value={`-${money(order.platformFee)}`} muted/><SummaryRow label="Phí chuyển tiền" value="0 đ" muted/></div><div className="mt-4"><SummaryRow label="Doanh thu shop nhận" value={money(order.sellerPayout)} green/><SummaryRow label="Trạng thái thanh toán" value={order.escrow ? 'Đã thanh toán' : 'Chưa thanh toán'} green={Boolean(order.escrow)}/><SummaryRow label="Trạng thái giữ tiền" value={order.escrow?.status || 'Không có'} green={order.escrow?.status === 'RELEASED'}/><SummaryRow label="Thời gian giữ tiền" value={dateTime(order.escrow?.heldAt)} /></div><div className="mt-5 border-t border-white/10 pt-4"><p className="text-sm font-bold text-rose-200">Hoàn tiền cho khách</p><p className="mt-1 text-xs leading-relaxed text-zinc-500">Hoàn toàn bộ số tiền vào ví buyer. Nếu escrow đã giải ngân, hệ thống sẽ trừ doanh thu của seller trước.</p><button onClick={refund} disabled={!canRefund || refunding} className="mt-3 w-full rounded-lg bg-rose-500 px-3 py-2.5 text-xs font-black text-white disabled:cursor-not-allowed disabled:opacity-35"><CircleDollarSign className="mr-1 inline h-4 w-4"/>{refunding ? 'Đang hoàn tiền...' : canRefund ? 'Hoàn tiền cho khách' : 'Không thể hoàn tiền'}</button></div></section><section className="rounded-xl border border-white/10 bg-[#141414] p-4"><p className="flex items-center gap-2 text-sm font-bold text-zinc-200"><ShieldCheck className="h-4 w-4 text-emerald-300"/>Dữ liệu giao dịch an toàn</p><p className="mt-2 text-xs leading-relaxed text-zinc-500">Lịch sử hoàn tiền, thay đổi trạng thái và số tiền được ghi audit log để đối soát.</p></section></aside></div>
  </div>;
}

function Metric({ label, value }: { label: string; value: string }) { return <div className="border-l border-white/10 pl-4"><p className="text-[10px] uppercase text-zinc-600">{label}</p><p className="mt-1 font-bold text-white">{value}</p></div>; }
function SummaryRow({ label, value, green = false, muted = false }: { label: string; value: string; green?: boolean; muted?: boolean }) { return <div className="flex items-start justify-between gap-3 text-xs"><span className="text-zinc-500">{label}</span><span className={`text-right font-bold ${green ? 'text-emerald-300' : muted ? 'text-zinc-400' : 'text-white'}`}>{value}</span></div>; }
