import { ActionForm } from "@/components/action-form";
import Link from "next/link";
import { notFound } from "next/navigation";
import { and, desc, eq, inArray } from "drizzle-orm";
import { alias } from "drizzle-orm/pg-core";
import { requireSession } from "@/lib/auth";
import { db } from "@/db";
import {
  orders,
  orderLines,
  orderPayments,
  products,
  customers,
  users,
  territories,
  channels,
  departments,
  programs,
  orderAttachments,
  auditLogs,
} from "@/db/schema";
import { formatVnd, formatDate, formatDateTime, formatNumber } from "@/lib/format";
import { PageHeader, TableWrap, Badge, StatCard } from "@/components/ui";
import {
  approveOrderAction,
  cancelOrderAction,
  deleteOrderAction,
  recordPaymentAction,
  deletePaymentAction,
  requestOrderRevisionAction,
  uploadOrderAttachmentAction,
  deleteOrderAttachmentAction,
} from "../actions";
import { today } from "@/lib/period";
import { canApproveOrders, canManageSettings, canViewOrder } from "@/lib/rbac";
import { loadEntityHistory } from "@/lib/audit-view";
import { EntityHistory } from "@/components/entity-history";
import { idOr404 } from "@/lib/route-params";

export const dynamic = "force-dynamic";

const FIELD_LABEL: Record<string, string> = {
  customerId: "khách hàng",
  orderDate: "ngày đặt",
  dueDate: "hạn thanh toán",
  totalAmount: "tổng tiền hàng",
  vatRequired: "cần xuất VAT",
  receiverName: "người nhận",
  receiverPhone: "SĐT người nhận",
  receiverAddress: "địa chỉ nhận",
  carrierName: "nhà xe",
  carrierPhone: "SĐT nhà xe",
  carrierAddress: "địa chỉ nhà xe",
  surchargeAmount: "phụ thu phí",
  note: "ghi chú",
  lines: "dòng hàng",
};

/** Mô tả một dòng nhật ký thành câu đọc được; trả rỗng nếu không cần hiển thị. */
function describeOrderEvent(entityType: string, action: string, payload: unknown): string {
  const data = (payload ?? {}) as Record<string, unknown>;
  if (entityType === "payment") {
    const amount = Number(data.amount ?? 0).toLocaleString("vi-VN");
    return action === "DELETE" ? `Xoá phiếu thu ${amount} đ` : `Ghi nhận thu ${amount} đ (ngày ${formatDate(String(data.paidOn ?? ""))})`;
  }
  if (entityType === "order_attachment") return action === "DELETE" ? `Gỡ tệp ${String(data.fileName ?? "")}` : `Đính kèm tệp ${String(data.fileName ?? "")}`;
  if (action === "CREATE") return "Lập đơn — đề xuất chờ duyệt";
  if (data.status === "CONFIRMED") return "Duyệt đơn";
  if (data.status === "CANCELLED") return data.previousStatus === "DRAFT" ? "Từ chối đơn" : "Huỷ đơn";
  const changes = (data.changes ?? {}) as Record<string, { from: unknown; to: unknown }>;
  if (changes.needsRevision?.to === true) return `Yêu cầu điều chỉnh: ${String(changes.revisionNote?.to ?? "")}`;
  const fields = Object.keys(changes).map((key) => FIELD_LABEL[key]).filter(Boolean);
  return fields.length > 0 ? `Sửa đơn: ${fields.join(", ")}` : "Sửa đơn";
}

export default async function OrderDetailPage({ params }: { params: Promise<{ id: string }> }) {
  const session = await requireSession();
  const id = idOr404((await params).id);
  const creator = alias(users, "creator");
  const approver = alias(users, "approver");
  const customerTerritory = alias(territories, "customer_territory");

  const [order] = await db
    .select({
      id: orders.id,
      code: orders.code,
      orderDate: orders.orderDate,
      status: orders.status,
      totalAmount: orders.totalAmount,
      promoValue: orders.promoValue,
      vatRequired: orders.vatRequired,
      receiverName: orders.receiverName,
      receiverPhone: orders.receiverPhone,
      receiverAddress: orders.receiverAddress,
      carrierName: orders.carrierName,
      carrierPhone: orders.carrierPhone,
      carrierAddress: orders.carrierAddress,
      surchargeAmount: orders.surchargeAmount,
      note: orders.note,
      createdAt: orders.createdAt,
      customerId: customers.id,
      customerName: customers.orgName,
      customerCode: customers.code,
      customerPhone: customers.phone,
      customerAddress: customers.address,
      customerWard: customers.ward,
      customerTerritoryName: customerTerritory.name,
      createdByName: creator.fullName,
      approvedByName: approver.fullName,
      approvedAt: orders.approvedAt,
      customerTaxCode: customers.taxCode,
      customerEmail: customers.email,
      customerContact: customers.contactName,
      needsRevision: orders.needsRevision,
      revisionNote: orders.revisionNote,
      salesName: users.fullName,
      salesUserId: orders.salesUserId,
      territoryId: orders.territoryId,
      territoryName: territories.name,
      channelName: channels.name,
      departmentName: departments.name,
      dueDate: orders.dueDate,
    })
    .from(orders)
    .innerJoin(customers, eq(orders.customerId, customers.id))
    .leftJoin(users, eq(orders.salesUserId, users.id))
    .leftJoin(territories, eq(orders.territoryId, territories.id))
    .leftJoin(channels, eq(orders.channelId, channels.id))
    .leftJoin(departments, eq(orders.departmentId, departments.id))
    .leftJoin(customerTerritory, eq(customers.territoryId, customerTerritory.id))
    .leftJoin(creator, eq(orders.createdBy, creator.id))
    .leftJoin(approver, eq(orders.approvedBy, approver.id))
    .where(and(eq(orders.tenantId, session.tenantId), eq(orders.id, id)))
    .limit(1);

  if (!order) notFound();
  // Ngoài phạm vi dữ liệu của người xem thì coi như không tồn tại: NVKD chỉ thấy đơn của mình, quản lý thấy nhánh phòng ban mình phụ trách.
  if (!(await canViewOrder(session, { salesUserId: order.salesUserId, territoryId: order.territoryId }))) notFound();

  const attachments = await db
    .select({
      id: orderAttachments.id,
      fileName: orderAttachments.fileName,
      fileSize: orderAttachments.fileSize,
      filePath: orderAttachments.filePath,
      mimeType: orderAttachments.mimeType,
      uploadedAt: orderAttachments.uploadedAt,
      uploadedBy: orderAttachments.uploadedBy,
      uploadedByName: users.fullName,
    })
    .from(orderAttachments)
    .leftJoin(users, eq(orderAttachments.uploadedBy, users.id))
    .where(and(eq(orderAttachments.tenantId, session.tenantId), eq(orderAttachments.orderId, id)))
    .orderBy(desc(orderAttachments.uploadedAt));

  // Đơn đã duyệt chỉ Ban giám đốc mới sửa được (thông tin đã duyệt không được chỉnh — yêu cầu bổ sung của khách).
  const canEditOrder = order.status === "DRAFT" || (order.status === "CONFIRMED" && session.role === "DIRECTOR");
  const canCancelOrder =
    session.role !== "SALES" && (order.status === "DRAFT" || (order.status === "CONFIRMED" && session.role === "DIRECTOR"));

  const lines = await db
    .select({
      id: orderLines.id,
      qtySold: orderLines.qtySold,
      qtyPromo: orderLines.qtyPromo,
      unitPrice: orderLines.unitPrice,
      amount: orderLines.amount,
      productCode: products.code,
      productName: products.name,
      unit: products.unit,
      catalogPrice: products.unitPrice,
      programName: programs.name,
    })
    .from(orderLines)
    .innerJoin(products, eq(orderLines.productId, products.id))
    .leftJoin(programs, eq(orderLines.programId, programs.id))
    .where(eq(orderLines.orderId, id));

  const payments = await db
    .select({
      id: orderPayments.id,
      paidOn: orderPayments.paidOn,
      amount: orderPayments.amount,
      method: orderPayments.method,
      note: orderPayments.note,
    })
    .from(orderPayments)
    .where(eq(orderPayments.orderId, id))
    .orderBy(orderPayments.paidOn);

  // Lịch sử chỉnh sửa CHI TIẾT (từng trường "cũ → mới", kể cả dòng hàng) — chỉ Ban giám đốc xem.
  const editHistory = canManageSettings(session) ? await loadEntityHistory(session.tenantId, id, ["order", "payment", "order_attachment"]) : null;

  // Lịch sử xử lý đơn (đề xuất → sửa/điều chỉnh → duyệt/huỷ → thu tiền) đọc từ nhật ký thao tác, mới nhất trước.
  const historyRows = await db
    .select({
      at: auditLogs.createdAt,
      action: auditLogs.action,
      entityType: auditLogs.entityType,
      payload: auditLogs.payload,
      who: users.fullName,
    })
    .from(auditLogs)
    .leftJoin(users, eq(auditLogs.userId, users.id))
    .where(
      and(
        eq(auditLogs.tenantId, session.tenantId),
        eq(auditLogs.entityId, id),
        inArray(auditLogs.entityType, ["order", "payment", "order_attachment"]),
      ),
    )
    .orderBy(desc(auditLogs.createdAt))
    .limit(40);
  const history = historyRows
    .map((row) => ({ at: row.at, who: row.who ?? "—", text: describeOrderEvent(row.entityType, row.action, row.payload) }))
    .filter((row) => row.text);

  const totalAmount = Number(order.totalAmount);
  const surchargeAmount = Number(order.surchargeAmount);
  // Phụ thu phí không tính vào doanh thu sản phẩm (totalAmount ở các thẻ thống kê phía
  // trên giữ nguyên), nhưng khách vẫn phải trả khoản này — nên "phải thu" thực tế phải
  // cộng thêm, khớp với ràng buộc chặn thu quá tiền ở recordPaymentAction.
  const payableAmount = totalAmount + surchargeAmount;
  const paidAmount = payments.reduce((sum, row) => sum + Number(row.amount), 0);
  const remaining = payableAmount - paidAmount;
  const workDate = today();
  /* Tuổi nợ tính từ hạn thanh toán, không phải từ ngày đặt hàng: đơn còn trong hạn
     thì chưa phải là nợ quá hạn dù đã đặt từ lâu. */
  const overdueDays =
    order.dueDate && remaining > 0 && order.dueDate < workDate
      ? Math.round(
          (Date.parse(`${workDate}T00:00:00Z`) - Date.parse(`${order.dueDate}T00:00:00Z`)) /
            86_400_000,
        )
      : 0;

  const totalQtySold = lines.reduce((sum, line) => sum + line.qtySold, 0);
  const totalQtyPromo = lines.reduce((sum, line) => sum + line.qtyPromo, 0);
  const customerFullAddress = [order.customerAddress, order.customerWard, order.customerTerritoryName].filter(Boolean).join(", ") || "—";
  // Xuất hoá đơn VAT cần ít nhất mã số thuế và địa chỉ của bên mua.
  const vatGaps = [!order.customerTaxCode && "mã số thuế", !order.customerAddress && "địa chỉ"].filter(Boolean);
  // Người duyệt thấy ngay dòng hàng có đơn giá khác bảng giá hiện hành (đơn còn chờ duyệt) để soát trước khi bấm Duyệt.
  const priceDeviations = order.status === "DRAFT" ? lines.filter((line) => Number(line.unitPrice) !== Number(line.catalogPrice)) : [];

  return (
    <>
      <PageHeader
        title={`Đơn hàng ${order.code}`}
        subtitle={`${formatDate(order.orderDate)} · ${order.customerName}`}
        actions={
          <div className="flex flex-wrap gap-2">
            <Link href="/don-hang" className="btn-ghost">
              ← Danh sách
            </Link>
            {canEditOrder && (
              <Link href={`/don-hang/${order.id}/sua`} className="btn-ghost">
                Sửa đơn
              </Link>
            )}
            {order.status === "DRAFT" && canApproveOrders(session) && (
              <ActionForm action={approveOrderAction} success="Đã duyệt đơn hàng." confirm="Duyệt đơn hàng này? Đơn sẽ bắt đầu tính vào doanh thu và công nợ.">
                <input type="hidden" name="id" value={order.id} />
                <button type="submit" className="btn-primary">
                  Duyệt đơn
                </button>
              </ActionForm>
            )}
            {canCancelOrder && (
              <ActionForm
                action={cancelOrderAction}
                success={order.status === "DRAFT" ? "Đã từ chối đơn hàng." : "Đã huỷ đơn hàng."}
                confirm={
                  order.status === "DRAFT"
                    ? "Từ chối đơn hàng này?"
                    : "Huỷ đơn hàng này? Đơn sẽ không còn tính vào doanh thu."
                }
              >
                <input type="hidden" name="id" value={order.id} />
                <button type="submit" className="btn-ghost text-red-600">
                  {order.status === "DRAFT" ? "Từ chối" : "Huỷ đơn"}
                </button>
              </ActionForm>
            )}
            {session.role === "DIRECTOR" && (
              <ActionForm action={deleteOrderAction} success="Đã xoá đơn hàng." confirm="Xoá hẳn đơn hàng này? Thao tác không thể hoàn tác." redirects>
                <input type="hidden" name="id" value={order.id} />
                <button type="submit" className="btn-ghost text-red-600">
                  Xoá hẳn
                </button>
              </ActionForm>
            )}
          </div>
        }
      />

      {order.status === "DRAFT" && order.needsRevision && (
        <div role="status" className="mb-4 rounded-lg border border-gold-500/40 bg-gold-100 px-4 py-3 text-sm text-ink-700">
          <div className="font-semibold">Đơn được yêu cầu điều chỉnh</div>
          <div className="mt-0.5 text-ink-600">{order.revisionNote}</div>
          <div className="mt-1 text-xs text-ink-400">Sửa đơn xong, đơn tự quay lại hàng chờ duyệt.</div>
        </div>
      )}

      {order.status === "DRAFT" && !order.needsRevision && canApproveOrders(session) && (
        <details className="mb-4">
          <summary className="cursor-pointer text-sm font-semibold text-brand-600">Yêu cầu NVKD điều chỉnh đơn</summary>
          <ActionForm action={requestOrderRevisionAction} success="Đã yêu cầu điều chỉnh đơn." className="mt-2 flex flex-wrap items-end gap-2">
            <input type="hidden" name="id" value={order.id} />
            <input name="note" required className="input min-w-64 flex-1" placeholder="Cần sửa gì? (ví dụ: giảm số lượng KM dòng 2, thêm hạn thanh toán)" />
            <button type="submit" className="btn-ghost">
              Gửi yêu cầu
            </button>
          </ActionForm>
        </details>
      )}

      {order.status !== "CONFIRMED" && (
        <div className="mb-4 flex flex-wrap gap-2">
          <Badge tone={order.status === "DRAFT" ? "gold" : "red"}>
            {order.status === "DRAFT"
              ? order.needsRevision
                ? "Chờ NVKD điều chỉnh — chưa tính vào doanh thu"
                : "Chờ Giám đốc Khu vực duyệt — chưa tính vào doanh thu"
              : "Đơn đã huỷ — không tính vào doanh thu"}
          </Badge>
        </div>
      )}

      {/* Đơn cần xuất VAT phải NỔI BẬT (yêu cầu mục Bán hàng) và báo ngay nếu thiếu thông tin để xuất hoá đơn. */}
      {order.vatRequired && (
        <div role="note" className="mb-4 rounded-lg border-2 border-brand-500 bg-brand-50 px-4 py-3">
          <div className="text-sm font-bold uppercase tracking-wide text-brand-700">Đơn cần xuất hoá đơn VAT</div>
          <div className="mt-1 text-sm text-ink-600">
            Người mua: <b>{order.customerName}</b> · MST: <b>{order.customerTaxCode ?? "—"}</b> · Địa chỉ: {customerFullAddress}
          </div>
          {vatGaps.length > 0 && (
            <div className="mt-1.5 text-sm font-semibold text-red-600">
              Hồ sơ khách còn thiếu {vatGaps.join(", ")} — bổ sung ở{" "}
              <Link href={`/khach-hang/${order.customerId}/sua`} className="underline">
                Sửa hồ sơ khách
              </Link>{" "}
              trước khi xuất hoá đơn.
            </div>
          )}
        </div>
      )}

      <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">
        <StatCard label="Tổng tiền hàng bán" value={formatVnd(Number(order.totalAmount))} />
        <StatCard
          label="Giá trị hàng KM"
          value={formatVnd(Number(order.promoValue))}
          hint={
            Number(order.totalAmount) > 0
              ? `${((Number(order.promoValue) / Number(order.totalAmount)) * 100).toFixed(1)}% doanh thu`
              : undefined
          }
        />
        <StatCard label="Số lượng bán" value={formatNumber(totalQtySold)} hint={`${lines.length} mặt hàng`} />
        <StatCard label="Số lượng KM" value={formatNumber(totalQtyPromo)} />
      </div>

      <div className="mt-5 grid gap-4 lg:grid-cols-3">
        <div className="card p-4">
          <h2 className="mb-3 text-base font-bold text-ink-700">Thông tin đơn</h2>
          <dl className="flex flex-col gap-2 text-sm">
            <div className="flex justify-between gap-3">
              <dt className="text-ink-400">Khách hàng</dt>
              <dd className="text-right">
                <Link href={`/khach-hang/${order.customerId}`} className="text-ink-700 hover:text-brand-600">
                  {order.customerName}
                </Link>
                <div className="text-[11px] text-ink-400">{order.customerCode}</div>
              </dd>
            </div>
            <div className="flex justify-between gap-3">
              <dt className="text-ink-400">Kênh</dt>
              <dd className="text-right text-ink-700">{order.channelName ?? "—"}</dd>
            </div>
            <div className="flex justify-between gap-3">
              <dt className="text-ink-400">Khu vực</dt>
              <dd className="text-right text-ink-700">{order.territoryName ?? "—"}</dd>
            </div>
            <div className="flex justify-between gap-3">
              <dt className="text-ink-400">NVKD</dt>
              <dd className="text-right text-ink-700">{order.salesName ?? "—"}</dd>
            </div>
            <div className="flex justify-between gap-3">
              <dt className="text-ink-400">Phòng ban</dt>
              <dd className="text-right text-ink-700">{order.departmentName ?? "—"}</dd>
            </div>
            <div className="flex justify-between gap-3">
              <dt className="text-ink-400">Hạn thanh toán</dt>
              <dd className="tnum text-right text-ink-700">{formatDate(order.dueDate)}</dd>
            </div>
            <div className="flex justify-between gap-3">
              <dt className="text-ink-400">Người đại diện</dt>
              <dd className="text-right text-ink-700">{order.customerContact ?? "—"}</dd>
            </div>
            <div className="flex justify-between gap-3">
              <dt className="text-ink-400">Mã số thuế</dt>
              <dd className="tnum text-right text-ink-700">{order.customerTaxCode ?? "—"}</dd>
            </div>
            <div className="flex justify-between gap-3">
              <dt className="text-ink-400">Điện thoại</dt>
              <dd className="tnum text-right text-ink-700">{order.customerPhone ?? "—"}</dd>
            </div>
            <div className="flex justify-between gap-3">
              <dt className="text-ink-400">Email</dt>
              <dd className="text-right text-ink-700">{order.customerEmail ?? "—"}</dd>
            </div>
            <div className="flex flex-col gap-1">
              <dt className="text-ink-400">Địa chỉ</dt>
              <dd className="text-ink-700">{customerFullAddress}</dd>
            </div>
            <div className="flex justify-between gap-3">
              <dt className="text-ink-400">Số phiếu đặt hàng</dt>
              <dd className="tnum text-right text-ink-700">{order.code}</dd>
            </div>
            <div className="flex justify-between gap-3">
              <dt className="text-ink-400">Xuất VAT</dt>
              <dd className="text-right">{order.vatRequired ? <Badge tone="brand">Cần xuất VAT</Badge> : <span className="text-ink-500">Không</span>}</dd>
            </div>
            <div className="flex justify-between gap-3">
              <dt className="text-ink-400">Người đề xuất</dt>
              <dd className="text-right text-ink-700">
                {order.createdByName ?? "—"}
                <div className="text-[11px] text-ink-400">{formatDateTime(order.createdAt)}</div>
              </dd>
            </div>
            <div className="flex justify-between gap-3">
              <dt className="text-ink-400">Người duyệt</dt>
              <dd className="text-right text-ink-700">
                {order.approvedByName ?? (order.status === "DRAFT" ? "Chưa duyệt" : "—")}
                {order.approvedAt && <div className="text-[11px] text-ink-400">{formatDateTime(order.approvedAt)}</div>}
              </dd>
            </div>
            {(order.receiverName || order.carrierName) && (
              <div className="flex flex-col gap-2 border-t border-[var(--color-line)] pt-2">
                <dt className="label-caps text-ink-400">Giao hàng</dt>
                {order.receiverName && (
                  <dd className="text-ink-700">
                    Nhận: {order.receiverName}
                    {order.receiverPhone ? ` · ${order.receiverPhone}` : ""}
                    {order.receiverAddress && (
                      <div className="text-[11px] text-ink-400">{order.receiverAddress}</div>
                    )}
                  </dd>
                )}
                {order.carrierName && (
                  <dd className="text-ink-700">
                    Nhà xe: {order.carrierName}
                    {order.carrierPhone ? ` · ${order.carrierPhone}` : ""}
                    {order.carrierAddress && (
                      <div className="text-[11px] text-ink-400">{order.carrierAddress}</div>
                    )}
                  </dd>
                )}
              </div>
            )}
            {Number(order.surchargeAmount) > 0 && (
              <div className="flex justify-between gap-3 border-t border-[var(--color-line)] pt-2">
                <dt className="text-ink-400">Phụ thu phí</dt>
                <dd className="tnum text-right text-ink-700">{formatVnd(Number(order.surchargeAmount))}</dd>
              </div>
            )}
            {order.note && (
              <div className="flex flex-col gap-1 border-t border-[var(--color-line)] pt-2">
                <dt className="text-ink-400">Ghi chú</dt>
                <dd className="text-ink-700">{order.note}</dd>
              </div>
            )}
          </dl>
        </div>

        <div className="lg:col-span-2">
          <TableWrap>
            <thead>
              <tr>
                <th>Mã</th>
                <th>Sản phẩm</th>
                <th className="text-right">SL bán</th>
                <th className="text-right">SL KM</th>
                <th className="text-right">Đơn giá</th>
                <th className="text-right">Thành tiền</th>
              </tr>
            </thead>
            <tbody>
              {lines.map((line) => (
                <tr key={line.id}>
                  <td className="tnum text-ink-400">{line.productCode}</td>
                  <td>
                    <div className="font-medium text-ink-700">{line.productName}</div>
                    {order.status === "DRAFT" && Number(line.unitPrice) !== Number(line.catalogPrice) && (
                      <div className="mt-0.5 text-[11px] font-semibold text-red-600">
                        Khác bảng giá: danh mục {formatVnd(Number(line.catalogPrice))}
                      </div>
                    )}
                    {line.programName && (
                      <div className="mt-0.5">
                        <Badge tone="gold">{line.programName}</Badge>
                      </div>
                    )}
                  </td>
                  <td className="tnum text-right">
                    {formatNumber(line.qtySold)}
                    <div className="text-[11px] text-ink-400">{line.unit}</div>
                  </td>
                  <td className="tnum text-right text-ink-400">
                    {line.qtyPromo > 0 ? formatNumber(line.qtyPromo) : "—"}
                  </td>
                  <td className="tnum text-right text-ink-500">{formatVnd(Number(line.unitPrice))}</td>
                  <td className="tnum text-right font-semibold">{formatVnd(Number(line.amount))}</td>
                </tr>
              ))}
              <tr>
                <td colSpan={5} className="text-right font-semibold text-ink-700">
                  Tổng cộng
                </td>
                <td className="tnum text-right text-base font-bold text-ink-700">
                  {formatVnd(Number(order.totalAmount))}
                </td>
              </tr>
              {surchargeAmount > 0 && (
                <>
                  <tr>
                    <td colSpan={5} className="text-right text-ink-500">
                      Phụ thu phí
                    </td>
                    <td className="tnum text-right text-ink-700">{formatVnd(surchargeAmount)}</td>
                  </tr>
                  <tr>
                    <td colSpan={5} className="text-right font-semibold text-ink-700">
                      Tổng phải thu
                    </td>
                    <td className="tnum text-right text-base font-bold text-ink-700">{formatVnd(payableAmount)}</td>
                  </tr>
                </>
              )}
            </tbody>
          </TableWrap>
        </div>
      </div>

      {priceDeviations.length > 0 && canApproveOrders(session) && (
        <div role="status" className="mt-4 rounded-lg border border-red-200 bg-red-50 px-4 py-2.5 text-sm text-red-700">
          <b>{priceDeviations.length} dòng hàng có đơn giá khác bảng giá hiện hành</b> — soát lại trước khi duyệt (hoặc bấm “Yêu cầu NVKD điều chỉnh đơn”).
        </div>
      )}

      {/* Quy trình duyệt & lịch sử xử lý đơn */}
      <div className="mt-6 card p-4">
        <h2 className="mb-3 text-base font-bold text-ink-700">Quy trình duyệt &amp; lịch sử</h2>
        <ol className="mb-3 flex flex-wrap items-center gap-2 text-sm">
          <li>
            <Badge tone="green">Đề xuất · {order.createdByName ?? "—"}</Badge>
          </li>
          <li className="text-ink-300">→</li>
          <li>
            <Badge tone={order.status === "CONFIRMED" ? "green" : order.status === "CANCELLED" ? "red" : "gold"}>
              {order.status === "CONFIRMED"
                ? `Duyệt · ${order.approvedByName ?? "—"}`
                : order.status === "CANCELLED"
                  ? "Không được duyệt / đã huỷ"
                  : order.needsRevision
                    ? "Chờ điều chỉnh rồi duyệt lại"
                    : "Chờ Giám đốc Khu vực / Ban giám đốc duyệt"}
            </Badge>
          </li>
        </ol>
        {history.length === 0 ? (
          <p className="text-sm text-ink-400">Chưa có lịch sử xử lý.</p>
        ) : (
          <ul className="flex flex-col gap-1 text-sm">
            {history.map((entry, index) => (
              <li key={index} className="flex flex-wrap gap-x-2 text-ink-600">
                <span className="tnum text-xs text-ink-400">{formatDateTime(entry.at)}</span>
                <span className="text-ink-700">{entry.who}</span>
                <span>— {entry.text}</span>
              </li>
            ))}
          </ul>
        )}
      </div>

      {/* Công nợ — yêu cầu Mediworld mục 3 và 7. Chỉ đơn ĐÃ DUYỆT mới có công nợ và ghi nhận thu tiền. */}
      {order.status === "DRAFT" && (
        <p className="mt-6 text-sm text-ink-400">Công nợ và thu tiền chỉ ghi nhận sau khi đơn được duyệt.</p>
      )}
      {order.status === "CONFIRMED" && (
        <div className="mt-6 grid gap-4 lg:grid-cols-3">
          <div className="card p-4">
            <h2 className="mb-3 text-base font-bold text-ink-700">Công nợ</h2>
            <dl className="flex flex-col gap-2 text-sm">
              <div className="flex justify-between gap-3">
                <dt className="text-ink-400">Tiền hàng</dt>
                <dd className="tnum text-right text-ink-700">{formatVnd(totalAmount)}</dd>
              </div>
              {surchargeAmount > 0 && (
                <div className="flex justify-between gap-3">
                  <dt className="text-ink-400">Phụ thu phí</dt>
                  <dd className="tnum text-right text-ink-700">{formatVnd(surchargeAmount)}</dd>
                </div>
              )}
              <div className="flex justify-between gap-3">
                <dt className="text-ink-400">Phải thu</dt>
                <dd className="tnum text-right font-semibold text-ink-700">{formatVnd(payableAmount)}</dd>
              </div>
              <div className="flex justify-between gap-3">
                <dt className="text-ink-400">Đã thu</dt>
                <dd className="tnum text-right text-emerald-700">{formatVnd(paidAmount)}</dd>
              </div>
              <div className="flex justify-between gap-3 border-t border-[var(--color-line)] pt-2">
                <dt className="font-semibold text-ink-700">Còn lại</dt>
                <dd
                  className={`tnum text-right text-base font-bold ${
                    remaining > 0 ? "text-gold-500" : "text-emerald-700"
                  }`}
                >
                  {formatVnd(remaining)}
                </dd>
              </div>
            </dl>
            {overdueDays > 0 && (
              <div className="mt-3">
                <Badge tone="red">Quá hạn {overdueDays} ngày</Badge>
              </div>
            )}
            {remaining === 0 && paidAmount > 0 && (
              <div className="mt-3">
                <Badge tone="green">Đã thu đủ</Badge>
              </div>
            )}
          </div>

          <div className="lg:col-span-2">
            {remaining > 0 && (
              <ActionForm action={recordPaymentAction} success="Đã ghi nhận thu tiền." resetOnSuccess className="card mb-3 flex flex-wrap items-end gap-3 p-4">
                <input type="hidden" name="orderId" value={order.id} />
                <div>
                  <label className="label-caps mb-1.5 block">Ngày thu</label>
                  <input name="paidOn" type="date" required defaultValue={workDate} min={order.orderDate} max={workDate} className="input" />
                </div>
                <div>
                  <label className="label-caps mb-1.5 block">Số tiền</label>
                  <input
                    name="amount"
                    type="number"
                    min={1}
                    max={remaining}
                    required
                    defaultValue={remaining}
                    className="input tnum w-44"
                  />
                </div>
                <div>
                  <label className="label-caps mb-1.5 block">Hình thức</label>
                  <select name="method" defaultValue="Chuyển khoản" className="input">
                    <option>Chuyển khoản</option>
                    <option>Tiền mặt</option>
                    <option>Khác</option>
                  </select>
                </div>
                <div className="min-w-40 flex-1">
                  <label className="label-caps mb-1.5 block">Ghi chú</label>
                  <input name="note" className="input" placeholder="Số chứng từ, người nộp…" />
                </div>
                <button type="submit" className="btn-primary">
                  Ghi nhận
                </button>
              </ActionForm>
            )}

            {payments.length === 0 ? (
              <div className="card px-4 py-8 text-center text-sm text-ink-400">
                Chưa ghi nhận lần thu tiền nào cho đơn này.
              </div>
            ) : (
              <TableWrap>
                <thead>
                  <tr>
                    <th>Ngày thu</th>
                    <th>Hình thức</th>
                    <th>Ghi chú</th>
                    <th className="text-right">Số tiền</th>
                    {session.role !== "SALES" && <th />}
                  </tr>
                </thead>
                <tbody>
                  {payments.map((payment) => (
                    <tr key={payment.id}>
                      <td className="tnum whitespace-nowrap text-ink-500">{formatDate(payment.paidOn)}</td>
                      <td className="text-ink-500">{payment.method ?? "—"}</td>
                      <td className="text-ink-500">{payment.note ?? "—"}</td>
                      <td className="tnum text-right font-semibold">{formatVnd(Number(payment.amount))}</td>
                      {session.role !== "SALES" && (
                        <td className="text-right">
                          <ActionForm action={deletePaymentAction} success="Đã xoá phiếu thu." confirm="Xoá lần thu tiền này?">
                            <input type="hidden" name="id" value={payment.id} />
                            <input type="hidden" name="orderId" value={order.id} />
                            <button type="submit" className="btn-ghost px-2 py-1 text-xs text-red-600">
                              Xoá
                            </button>
                          </ActionForm>
                        </td>
                      )}
                    </tr>
                  ))}
                </tbody>
              </TableWrap>
            )}
          </div>
        </div>
      )}

      <div className="mt-6">
        <h2 className="mb-3 text-base font-bold text-ink-700">Tệp đính kèm</h2>
        {order.status !== "CANCELLED" && (
          <ActionForm action={uploadOrderAttachmentAction} success="Đã đính kèm tệp." resetOnSuccess className="card mb-3 flex flex-wrap items-end gap-3 p-4">
            <input type="hidden" name="orderId" value={order.id} />
            <div className="min-w-56 flex-1">
              <label className="label-caps mb-1.5 block">Chọn tệp (ảnh, PDF, Word, Excel — tối đa 8 MB)</label>
              <input name="file" type="file" required accept="image/*,application/pdf,.docx,.xlsx" className="input" />
            </div>
            <button type="submit" className="btn-ghost">
              Đính kèm
            </button>
          </ActionForm>
        )}
        {attachments.length === 0 ? (
          <div className="card px-4 py-6 text-center text-sm text-ink-400">Chưa có tệp đính kèm.</div>
        ) : (
          <div className="card divide-y divide-[var(--color-line)]">
            {attachments.map((file) => (
              <div key={file.id} className="flex flex-wrap items-center gap-3 px-4 py-2.5">
                <a
                  href={`/api/anh/${file.filePath}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="min-w-0 flex-1 truncate text-sm font-medium text-brand-600 hover:underline"
                >
                  📎 {file.fileName}
                </a>
                <span className="text-xs text-ink-400">
                  {file.uploadedByName ?? "—"} · {formatDate(file.uploadedAt)}
                </span>
                {(order.status !== "CONFIRMED" || session.role === "DIRECTOR") &&
                  (session.role !== "SALES" || file.uploadedBy === session.userId) && (
                    <ActionForm action={deleteOrderAttachmentAction} success="Đã gỡ tệp." confirm="Gỡ tệp đính kèm này?">
                      <input type="hidden" name="id" value={file.id} />
                      <button type="submit" className="btn-ghost px-2 py-1 text-xs text-red-600">
                        Gỡ
                      </button>
                    </ActionForm>
                  )}
              </div>
            ))}
          </div>
        )}
      </div>
      {editHistory && (
        <div className="mt-6">
          <EntityHistory entries={editHistory} />
        </div>
      )}
    </>
  );
}
