import Link from "next/link";
import { notFound } from "next/navigation";
import { and, eq } from "drizzle-orm";
import { requireSession } from "@/lib/auth";
import { db } from "@/db";
import { customers } from "@/db/schema";
import { scopeFilter } from "@/lib/rbac";
import { PageHeader } from "@/components/ui";
import { loadCustomerFormOptions } from "../../form-options";
import { CustomerForm } from "../../moi/customer-form";
import { idOr404 } from "@/lib/route-params";

export const dynamic = "force-dynamic";

export default async function EditCustomerPage({ params }: { params: Promise<{ id: string }> }) {
  const session = await requireSession();
  const id = idOr404((await params).id);

  const scope = await scopeFilter(session, {
    tenantId: customers.tenantId,
    ownerId: customers.ownerId,
    territoryId: customers.territoryId,
  });
  const [customer] = await db
    .select()
    .from(customers)
    .where(and(scope, eq(customers.id, id)))
    .limit(1);
  if (!customer) notFound();

  const options = await loadCustomerFormOptions(session, {
    channelId: customer.channelId,
    territoryId: customer.territoryId,
    ownerId: customer.ownerId,
  });

  return (
    <>
      <PageHeader
        title={`Sửa hồ sơ — ${customer.orgName}`}
        subtitle={`${customer.code} · mọi thay đổi được ghi vào nhật ký thao tác để Ban giám đốc xem lại.`}
        actions={
          <Link href={`/khach-hang/${customer.id}`} className="btn-ghost">
            ← Hồ sơ
          </Link>
        }
      />
      <CustomerForm
        {...options}
        initial={{
          id: customer.id,
          code: customer.code,
          orgName: customer.orgName,
          contactName: customer.contactName ?? "",
          contactPosition: customer.contactPosition ?? "",
          contactBirthDate: customer.contactBirthDate ?? "",
          phone: customer.phone ?? "",
          email: customer.email ?? "",
          taxCode: customer.taxCode ?? "",
          channelId: customer.channelId ?? "",
          territoryId: customer.territoryId ?? "",
          ward: customer.ward ?? "",
          address: customer.address ?? "",
          receiverName: customer.receiverName ?? "",
          receiverPhone: customer.receiverPhone ?? "",
          receiverAddress: customer.receiverAddress ?? "",
          leadNeed: customer.leadNeed ?? "",
          leadSource: customer.leadSource ?? "",
          stage: customer.stage,
          ownerId: customer.ownerId ?? "",
          note: customer.note ?? "",
        }}
      />
    </>
  );
}
