import Link from "next/link";
import { and, eq, ilike, or, desc } from "drizzle-orm";
import { requireSession } from "@/lib/auth";
import { db } from "@/db";
import { customers, orders } from "@/db/schema";
import { scopeFilter } from "@/lib/rbac";
import { formatVnd, formatDate, STAGE_LABEL } from "@/lib/format";
import { PageHeader, TableWrap, Badge, EmptyState } from "@/components/ui";

export const dynamic = "force-dynamic";

const MAX_RESULTS = 20;

export default async function SearchPage({
  searchParams,
}: {
  searchParams: Promise<{ q?: string }>;
}) {
  const session = await requireSession();
  const params = await searchParams;
  const q = (params.q ?? "").trim();

  let customerRows: {
    id: string;
    code: string;
    orgName: string;
    phone: string | null;
    stage: "LEAD" | "PROSPECT" | "DEALER";
  }[] = [];
  let orderRows: {
    id: string;
    code: string;
    orderDate: string;
    totalAmount: number;
    customerName: string;
  }[] = [];

  if (q) {
    const term = `%${q}%`;

    const customerScope = await scopeFilter(session, {
      tenantId: customers.tenantId,
      ownerId: customers.ownerId,
      territoryId: customers.territoryId,
    });

    customerRows = await db
      .select({
        id: customers.id,
        code: customers.code,
        orgName: customers.orgName,
        phone: customers.phone,
        stage: customers.stage,
      })
      .from(customers)
      .where(
        and(
          customerScope,
          eq(customers.isActive, true),
          or(ilike(customers.orgName, term), ilike(customers.code, term), ilike(customers.phone, term)),
        ),
      )
      .limit(MAX_RESULTS);

    const orderScope = await scopeFilter(session, {
      tenantId: orders.tenantId,
      ownerId: orders.salesUserId,
      territoryId: orders.territoryId,
    });

    orderRows = await db
      .select({
        id: orders.id,
        code: orders.code,
        orderDate: orders.orderDate,
        totalAmount: orders.totalAmount,
        customerName: customers.orgName,
      })
      .from(orders)
      .innerJoin(customers, eq(orders.customerId, customers.id))
      .where(and(orderScope, ilike(orders.code, term)))
      .orderBy(desc(orders.orderDate))
      .limit(MAX_RESULTS);
  }

  return (
    <>
      <PageHeader title="Tìm kiếm" subtitle={q ? `Kết quả cho "${q}"` : "Nhập từ khoá để tìm khách hàng hoặc đơn hàng."} />

      {!q ? (
        <EmptyState message="Chưa có từ khoá tìm kiếm." />
      ) : customerRows.length === 0 && orderRows.length === 0 ? (
        <EmptyState message={`Không tìm thấy khách hàng hoặc đơn hàng nào khớp với "${q}".`} />
      ) : (
        <div className="flex flex-col gap-6">
          {customerRows.length > 0 && (
            <div>
              <h2 className="mb-2 text-sm font-bold text-ink-600">Khách hàng ({customerRows.length})</h2>
              <TableWrap>
                <thead>
                  <tr>
                    <th>Mã</th>
                    <th>Tên đơn vị</th>
                    <th>Điện thoại</th>
                    <th>Trạng thái</th>
                  </tr>
                </thead>
                <tbody>
                  {customerRows.map((c) => (
                    <tr key={c.id}>
                      <td className="font-medium text-ink-700">
                        <Link href={`/khach-hang/${c.id}`} className="hover:underline">
                          {c.code}
                        </Link>
                      </td>
                      <td>{c.orgName}</td>
                      <td className="tnum text-ink-500">{c.phone ?? "—"}</td>
                      <td>
                        <Badge tone={c.stage === "DEALER" ? "brand" : c.stage === "PROSPECT" ? "gold" : "neutral"}>
                          {STAGE_LABEL[c.stage]}
                        </Badge>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </TableWrap>
            </div>
          )}

          {orderRows.length > 0 && (
            <div>
              <h2 className="mb-2 text-sm font-bold text-ink-600">Đơn hàng ({orderRows.length})</h2>
              <TableWrap>
                <thead>
                  <tr>
                    <th>Mã đơn</th>
                    <th>Khách hàng</th>
                    <th>Ngày</th>
                    <th className="text-right">Thành tiền</th>
                  </tr>
                </thead>
                <tbody>
                  {orderRows.map((o) => (
                    <tr key={o.id}>
                      <td className="font-medium text-ink-700">
                        <Link href={`/don-hang/${o.id}`} className="hover:underline">
                          {o.code}
                        </Link>
                      </td>
                      <td>{o.customerName}</td>
                      <td className="tnum text-ink-500">{formatDate(o.orderDate)}</td>
                      <td className="tnum text-right font-semibold">{formatVnd(Number(o.totalAmount))}</td>
                    </tr>
                  ))}
                </tbody>
              </TableWrap>
            </div>
          )}
        </div>
      )}
    </>
  );
}
