import Link from "next/link";
import { prisma } from "@/lib/prisma";
import { requireCrmAdmin } from "@/lib/crm/admin-access";
import CustomerAdminShell from "../CustomerAdminShell";
import { createQuotation } from "./actions";

export const dynamic = "force-dynamic";

export default async function QuotationsPage() {
  await requireCrmAdmin();

  const [quotations, customers, projects] = await Promise.all([
    prisma.quotation.findMany({
      orderBy: { createdAt: "desc" },
      take: 100,
      select: {
        quotationNumber: true,
        title: true,
        status: true,
        totalAmount: true,
        client: { select: { name: true } },
      },
    }),
    prisma.client.findMany({
      where: { status: "ACTIVE" },
      orderBy: { name: "asc" },
      take: 500,
      select: { id: true, name: true, clientCode: true },
    }),
    prisma.project.findMany({
      orderBy: { createdAt: "desc" },
      take: 500,
      select: {
        id: true,
        name: true,
        projectCode: true,
        clientId: true,
      },
    }),
  ]);

  return (
    <CustomerAdminShell>
      <main className="mx-auto max-w-6xl space-y-8 px-5 py-8">
        <h1 className="text-3xl font-bold">Quotation Management</h1>

        <section className="rounded-2xl border bg-white p-6">
          <h2 className="mb-4 text-xl font-bold">Create Quotation</h2>

          <form action={createQuotation} className="grid gap-4">
            <label className="grid gap-2 text-sm font-semibold">
              Customer *
              <select
                name="clientId"
                required
                defaultValue=""
                className="rounded-xl border p-3"
              >
                <option value="" disabled>Select Customer</option>
                {customers.map((customer) => (
                  <option key={customer.id} value={customer.id}>
                    {customer.name} — {customer.clientCode}
                  </option>
                ))}
              </select>
            </label>

            <label className="grid gap-2 text-sm font-semibold">
              Project (optional)
              <select
                name="projectId"
                defaultValue=""
                className="rounded-xl border p-3"
              >
                <option value="">No Project</option>
                {projects.map((project) => (
                  <option key={project.id} value={project.id}>
                    {project.name} — {project.projectCode}
                  </option>
                ))}
              </select>
            </label>

            <input
              name="title"
              required
              maxLength={191}
              placeholder="Quotation Title"
              className="rounded-xl border p-3"
            />

            <input
              name="description"
              required
              maxLength={255}
              placeholder="Item / Service Description"
              className="rounded-xl border p-3"
            />

            <label className="grid gap-2 text-sm font-semibold">
              Quantity *
              <input
                name="quantity"
                required
                defaultValue="1"
                inputMode="decimal"
                className="rounded-xl border p-3"
              />
            </label>

            <label className="grid gap-2 text-sm font-semibold">
              Unit Price (₹) *
              <input
                name="unitPrice"
                required
                inputMode="decimal"
                placeholder="0.00"
                className="rounded-xl border p-3"
              />
            </label>

            <label className="grid gap-2 text-sm font-semibold">
              Tax Rate (%) *
              <input
                name="taxRate"
                required
                defaultValue="0"
                inputMode="decimal"
                className="rounded-xl border p-3"
              />
            </label>

            <button
              type="submit"
              className="rounded-xl bg-blue-600 p-3 font-bold text-white"
            >
              Create Quotation
            </button>
          </form>
        </section>

        <section className="rounded-2xl border bg-white p-6">
          <h2 className="mb-4 text-xl font-bold">Quotations</h2>

          {quotations.length === 0 ? (
            <p className="text-sm text-slate-500">
              No quotations created yet.
            </p>
          ) : (
            <div className="space-y-3">
              {quotations.map((quotation) => (
                <Link
                  key={quotation.quotationNumber}
                  href={`/admin/quotations/${quotation.quotationNumber}`}
                  className="block rounded-xl border p-4 hover:bg-slate-50"
                >
                  <strong>{quotation.title}</strong>
                  <p className="text-sm text-slate-500">
                    {quotation.quotationNumber} · {quotation.client.name}
                  </p>
                  <p className="mt-1 text-sm">
                    {quotation.status} · ₹{quotation.totalAmount.toString()}
                  </p>
                </Link>
              ))}
            </div>
          )}
        </section>
      </main>
    </CustomerAdminShell>
  );
}
