'use client';

import { useEffect, useMemo, useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { ArrowLeft, CheckCircle2, CircleDollarSign, Clock3, Download, Loader2, MessageCircle, Package, RefreshCcw, ShieldAlert, ShieldCheck, Store, Truck, UserRound } 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 label: Record<string, string> = { ESCROW: 'Đang giữ tiền', DELIVERED: 'Đã giao', COMPLETED: 'Đã hoàn thành', DISPUTED: 'Tranh chấp', CANCELLED: 'Đã hoàn tiền', PENDING: 'Chờ thanh toán' };

export default function SellerOrderDetailPage() {
  const router = useRouter();
  const params = useParams<{ id: string; locale: string }>();
  const [order, setOrder] = useState<any>(null);
  const [messages, setMessages] = useState<any[]>([]);
  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 [orderResponse, chatResponse] = await Promise.all([api.get(`/orders/seller/${params.id}`), api.get(`/orders/${params.id}/messages`)]);
      setOrder(orderResponse.data); setMessages(chatResponse.data || []);
    } catch (err: any) { setError(err.response?.data?.message || 'Không thể tải chi tiết đơn bán.'); }
    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?.status === 'HOLD' && ['ESCROW', 'DELIVERED'].includes(order?.status));
  const timeline = useMemo(() => order ? [
    ['Đặt hàng', order.createdAt, true],
    ['Thanh toán', order.escrow?.heldAt, Boolean(order.escrow)],
    ['Đã giao hàng', order.deliveredAt, ['DELIVERED', 'COMPLETED'].includes(order.status)],
    [order.escrow?.status === 'REFUNDED' ? 'Đã hoàn tiền' : 'Giữ tiền', order.escrow?.refundedAt || order.escrow?.heldAt, Boolean(order.escrow)],
    ['Đã xong', order.confirmedAt, order.status === 'COMPLETED'],
  ] as [string, string | null | undefined, boolean][] : [], [order]);

  const refund = async () => {
    if (!order || !confirm(`Hoàn ${money(order.totalAmount)} trực tiếp về ví người mua?`)) return;
    try { setRefunding(true); await api.post(`/orders/${order.id}/seller-refund`); await load(); }
    catch (err: any) { setError(err.response?.data?.message || 'Không thể hoàn tiền đơn bán này.'); }
    finally { setRefunding(false); }
  };
  const download = async () => {
    try { setDownloading(true); const response = await api.get(`/orders/${order.id}/download`, { responseType: 'blob' }); const url = URL.createObjectURL(response.data); const link = document.createElement('a'); link.href = url; link.download = `order-${order.id}.zip`; 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-xl border border-red-500/30 bg-red-500/10 p-6 text-red-200"><p>{error || 'Không tìm thấy đơn bán.'}</p><button onClick={() => router.back()} className="mt-3 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 || 'vi'}/seller/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"/>Đơn bán</button><h1 className="text-xl font-black text-white">Chi tiết đơn bán</h1><p className="mt-1 text-xs text-zinc-500">Theo dõi thanh toán, bàn giao và trao đổi với người mua.</p></div><div className="flex gap-2"><span className="rounded-lg border border-violet-400/30 bg-violet-500/10 px-3 py-2 text-xs font-bold text-violet-200">{label[order.status] || order.status}</span><button onClick={() => void load()} className="rounded-lg border border-white/10 bg-white/5 p-2 text-zinc-300"><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.slice(0, 8).toUpperCase()}</p><div className="mt-5 flex 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 || 'Khách hàng'}</p><p className="text-xs text-zinc-500">{order.buyer?.email || '—'}</p></div></div><p className="mt-5 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></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 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">Bạn</p></div></div><p className="mt-5 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 className="mt-6 grid gap-3 md:grid-cols-5">{timeline.map(([name, time, done]) => <div key={name} className="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 ${done ? 'bg-emerald-400' : 'bg-zinc-700'}`}/><p className="text-xs font-bold text-zinc-200">{name}</p><p className="mt-1 text-[10px] text-zinc-500">{dateTime(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>{order.items?.map((item: any) => <div key={item.id} className="grid gap-4 border-b border-white/5 p-5 last:border-0 md:grid-cols-[1fr_auto_auto_auto]"><div className="flex gap-3"><div className="flex h-14 w-14 items-center justify-center rounded-lg bg-sky-500/15 text-sky-300"><Package className="h-6 w-6"/></div><div><p className="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 title="Đơn giá" value={money(item.price)}/><Metric title="Số lượng" value={`x${item.quantity}`}/><Metric title="Thành tiền" value={money(Number(item.price) * item.quantity)}/></div>)}</section><section className="rounded-xl border border-white/10 bg-[#141414]"><div className="flex items-center justify-between border-b border-white/10 px-5 py-4"><div><h2 className="font-bold text-white">Đơn vị đã bàn giao ({order.allocations?.length || 0})</h2><p className="mt-1 text-xs text-zinc-500">Tên thư mục kho được hiển thị để đối soát.</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 tải...' : 'Tải sản phẩm'}</button></div>{order.allocations?.length ? <div className="divide-y divide-white/5">{order.allocations.map((allocation: any, index: number) => <div key={allocation.id} className="flex items-center justify-between gap-4 px-5 py-3"><p className="font-mono text-xs font-bold text-white">{index + 1}. {allocation.inventoryItem?.folderName || allocation.inventoryItemId}</p><span className="rounded bg-emerald-500/10 px-2 py-1 text-xs font-bold text-emerald-300">{allocation.inventoryItem?.status || 'DELIVERED'}</span></div>)}</div> : <p className="p-5 text-sm text-zinc-500">Đơn giao thủ công hoặc chưa có đơn vị kho được phân bổ.</p>}</section><section 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">{messages.length ? messages.map((message) => <div key={message.id} className={`rounded-lg p-3 ${message.senderId === order.sellerId ? 'ml-auto max-w-[78%] bg-violet-500/15' : 'mr-auto max-w-[78%] bg-white/[.04]'}`}><p className="text-xs font-bold text-cyan-300">{message.sender?.name || (message.senderId === order.sellerId ? 'Bạn' : order.buyer?.name || 'Người mua')}</p><p className="mt-1 text-sm text-zinc-200">{message.content}</p><p className="mt-1 text-[10px] text-zinc-500">{dateTime(message.createdAt)}</p></div>) : <p className="py-8 text-center text-sm text-zinc-500">Chưa có trao đổi.</p>}</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"><Row label="Tổng tiền đơn hàng" value={money(order.totalAmount)}/><Row label="Phí nền tảng" value={`-${money(order.platformFee)}`}/></div><div className="mt-4 space-y-3"><Row label="Doanh thu shop nhận" value={money(order.sellerPayout)} green/><Row label="Trạng thái giữ tiền" value={order.escrow?.status || 'Không có'} green={order.escrow?.status === 'RELEASED'}/><Row 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">Seller có thể hoàn tiền trực tiếp khi tiền vẫn đang giữ trong Escrow. Đơn đã giải ngân cần xử lý qua khiếu nại/Admin.</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"/>Giao dịch được ghi nhận</p><p className="mt-2 text-xs leading-relaxed text-zinc-500">Mọi hoàn tiền do seller thực hiện đều có lịch sử giao dịch và thông báo cho buyer.</p></section></aside></div></div>;
}

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