import Link from "next/link";
import { notFound } from "next/navigation";

import {
  CheckCircle2,
  Clock3,
  FileText,
  Send,
  XCircle,
} from "lucide-react";

import CustomerAdminShell from "../../CustomerAdminShell";
import {
  createInvoiceFromQuotation,
  updateQuotationStatus,
} from "../actions";
import { requireCrmAdmin } from "@/lib/crm/admin-access";
import { prisma } from "@/lib/prisma";

export const dynamic = "force-dynamic";

const transitionMap = {
  DRAFT: ["SENT", "EXPIRED", "CANCELLED"],
  SENT: [
    "VIEWED",
    "APPROVED",
    "REJECTED",
    "EXPIRED",
    "CANCELLED",
  ],
  VIEWED: [
    "APPROVED",
    "REJECTED",
    "EXPIRED",
    "CANCELLED",
  ],
  APPROVED: [],
  REJECTED: [],
  EXPIRED: [],
  CANCELLED: [],
} as const;

function formatDate(value: Date | null) {
  if (!value) return "—";

  return value.toLocaleString("en-IN", {
    timeZone: "Asia/Kolkata",
    dateStyle: "medium",
    timeStyle: "short",
  });
}

function statusClass(status: string) {
  if (status === "APPROVED") {
    return "bg-emerald-100 text-emerald-700";
  }

  if (status === "REJECTED" || status === "CANCELLED") {
    return "bg-red-100 text-red-700";
  }

  if (status === "EXPIRED") {
    return "bg-amber-100 text-amber-700";
  }

  if (status === "SENT" || status === "VIEWED") {
    return "bg-blue-100 text-blue-700";
  }

  return "bg-slate-100 text-slate-700";
}

export default async function QuotationDetailsPage({
  params,
  searchParams,
}: {
  params: Promise<{ quotationNumber: string }>;
  searchParams: Promise<{
    updated?: string;
    error?: string;
  }>;
}) {
  await requireCrmAdmin();

  const { quotationNumber } = await params;
  const query = await searchParams;

  const quotation = await prisma.quotation.findUnique({
    where: {
      quotationNumber,
    },
    select: {
      quotationNumber: true,
      title: true,
      status: true,
      subtotal: true,
      taxAmount: true,
      discountAmount: true,
      totalAmount: true,
      validUntil: true,
      notes: true,
      sentAt: true,
      approvedAt: true,
      createdAt: true,
      updatedAt: true,

      invoice: {
        select: {
          invoiceNumber: true,
          status: true,
        },
      },

      client: {
        select: {
          name: true,
          clientCode: true,
        },
      },

      project: {
        select: {
          name: true,
          projectCode: true,
        },
      },

      items: {
        orderBy: {
          sequence: "asc",
        },
        select: {
          description: true,
          quantity: true,
          unitPrice: true,
          taxRate: true,
          amount: true,
        },
      },
    },
  });

  if (!quotation) {
    notFound();
  }

  const nextStatuses =
    transitionMap[quotation.status];

  return (
    <CustomerAdminShell>
      <main className="mx-auto max-w-6xl space-y-7 px-5 py-8">
        <div className="flex flex-wrap items-center justify-between gap-3">
          <Link
            href="/admin/quotations"
            className="text-sm font-bold text-blue-600 hover:text-blue-700"
          >
            ← All Quotations
          </Link>

          <span
            className={`rounded-full px-3 py-1.5 text-xs font-extrabold ${statusClass(
              quotation.status,
            )}`}
          >
            {quotation.status.replaceAll("_", " ")}
          </span>
        </div>

        {query.updated === "1" && (
          <div className="rounded-xl border border-emerald-200 bg-emerald-50 p-4 text-sm font-semibold text-emerald-700">
            Quotation status updated successfully.
          </div>
        )}

        {query.error === "stale" && (
          <div className="rounded-xl border border-amber-200 bg-amber-50 p-4 text-sm font-semibold text-amber-800">
            This quotation changed in another session. The latest record has been loaded. Review it before updating again.
          </div>
        )}

        {query.error === "transition" && (
          <div className="rounded-xl border border-red-200 bg-red-50 p-4 text-sm font-semibold text-red-700">
            That quotation status transition is not allowed.
          </div>
        )}

        {query.error === "invalid" && (
          <div className="rounded-xl border border-red-200 bg-red-50 p-4 text-sm font-semibold text-red-700">
            Invalid quotation update request.
          </div>
        )}

        <section className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
          <div className="flex flex-col justify-between gap-5 md:flex-row md:items-start">
            <div>
              <p className="text-xs font-extrabold uppercase tracking-[0.16em] text-blue-700">
                QUOTATION
              </p>

              <h1 className="mt-2 text-3xl font-extrabold text-slate-900">
                {quotation.title}
              </h1>

              <p className="mt-2 text-sm font-semibold text-slate-500">
                {quotation.quotationNumber}
              </p>

              <div className="mt-5 space-y-1 text-sm text-slate-600">
                <p>
                  <strong>Customer:</strong>{" "}
                  {quotation.client.name} (
                  {quotation.client.clientCode})
                </p>

                {quotation.project && (
                  <p>
                    <strong>Project:</strong>{" "}
                    {quotation.project.name} (
                    {quotation.project.projectCode})
                  </p>
                )}
              </div>
            </div>

            <div className="grid min-w-[250px] gap-2 rounded-xl bg-slate-50 p-4 text-sm">
              <p>
                <strong>Created:</strong>{" "}
                {formatDate(quotation.createdAt)}
              </p>

              <p>
                <strong>Sent:</strong>{" "}
                {formatDate(quotation.sentAt)}
              </p>

              <p>
                <strong>Approved:</strong>{" "}
                {formatDate(quotation.approvedAt)}
              </p>

              <p>
                <strong>Valid Until:</strong>{" "}
                {formatDate(quotation.validUntil)}
              </p>
            </div>
          </div>
        </section>

        <section className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
          <div className="mb-5 flex items-center gap-3">
            <FileText
              size={20}
              className="text-blue-600"
            />
            <h2 className="text-xl font-extrabold text-slate-900">
              Quotation Items
            </h2>
          </div>

          <div className="space-y-4">
            {quotation.items.map((item, index) => (
              <div
                key={`${quotation.quotationNumber}-${index}`}
                className="rounded-xl border border-slate-200 p-4"
              >
                <strong className="text-slate-900">
                  {item.description}
                </strong>

                <div className="mt-3 grid gap-2 text-sm text-slate-600 sm:grid-cols-4">
                  <p>
                    Quantity:{" "}
                    {item.quantity.toString()}
                  </p>

                  <p>
                    Unit Price: ₹
                    {item.unitPrice.toString()}
                  </p>

                  <p>
                    Tax:{" "}
                    {item.taxRate.toString()}%
                  </p>

                  <p>
                    Amount: ₹
                    {item.amount.toString()}
                  </p>
                </div>
              </div>
            ))}
          </div>

          <div className="mt-6 ml-auto max-w-sm space-y-2 border-t border-slate-200 pt-5 text-sm">
            <div className="flex justify-between gap-5">
              <span>Subtotal</span>
              <strong>
                ₹{quotation.subtotal.toString()}
              </strong>
            </div>

            <div className="flex justify-between gap-5">
              <span>Tax</span>
              <strong>
                ₹{quotation.taxAmount.toString()}
              </strong>
            </div>

            <div className="flex justify-between gap-5">
              <span>Discount</span>
              <strong>
                ₹{quotation.discountAmount.toString()}
              </strong>
            </div>

            <div className="flex justify-between gap-5 border-t pt-3 text-lg">
              <span className="font-extrabold">
                Total
              </span>

              <strong>
                ₹{quotation.totalAmount.toString()}
              </strong>
            </div>
          </div>

          {quotation.notes && (
            <div className="mt-6 rounded-xl bg-slate-50 p-4">
              <p className="text-xs font-bold uppercase text-slate-400">
                Notes
              </p>

              <p className="mt-2 whitespace-pre-wrap text-sm text-slate-600">
                {quotation.notes}
              </p>
            </div>
          )}
        </section>

        {quotation.status === "APPROVED" && (
          <section className="rounded-2xl border border-emerald-200 bg-emerald-50 p-6 shadow-sm">
            <h2 className="text-xl font-extrabold text-slate-900">
              Invoice Handoff
            </h2>

            <p className="mt-2 text-sm text-slate-600">
              This approved quotation is eligible for invoicing.
            </p>

            {quotation.invoice ? (
              <div className="mt-5">
                <p className="text-sm font-semibold text-emerald-800">
                  Invoice already created: {quotation.invoice.invoiceNumber} · {quotation.invoice.status}
                </p>

                <Link
                  href={`/admin/invoices/${quotation.invoice.invoiceNumber}`}
                  className="mt-4 inline-flex rounded-xl bg-emerald-600 px-5 py-3 font-extrabold text-white hover:bg-emerald-700"
                >
                  Open Invoice
                </Link>
              </div>
            ) : (
              <form
                action={createInvoiceFromQuotation}
                className="mt-5"
              >
                <input
                  type="hidden"
                  name="quotationNumber"
                  value={quotation.quotationNumber}
                />

                <input
                  type="hidden"
                  name="updatedAt"
                  value={quotation.updatedAt.toISOString()}
                />

                <button
                  type="submit"
                  className="rounded-xl bg-emerald-600 px-5 py-3 font-extrabold text-white transition hover:bg-emerald-700"
                >
                  Create Draft Invoice
                </button>
              </form>
            )}
          </section>
        )}

        <section className="rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
          <div className="mb-5">
            <h2 className="text-xl font-extrabold text-slate-900">
              Quotation Workflow
            </h2>

            <p className="mt-1 text-sm text-slate-500">
              Move this quotation through the controlled commercial lifecycle.
            </p>
          </div>

          {nextStatuses.length === 0 ? (
            <div className="flex items-center gap-3 rounded-xl bg-slate-50 p-4 text-sm font-semibold text-slate-600">
              {quotation.status === "APPROVED" ? (
                <CheckCircle2
                  size={20}
                  className="text-emerald-600"
                />
              ) : quotation.status === "REJECTED" ||
                quotation.status === "CANCELLED" ? (
                <XCircle
                  size={20}
                  className="text-red-600"
                />
              ) : (
                <Clock3
                  size={20}
                  className="text-amber-600"
                />
              )}

              This quotation is in a final status:{" "}
              {quotation.status.replaceAll("_", " ")}.
            </div>
          ) : (
            <form
              action={updateQuotationStatus}
              className="grid gap-4 md:grid-cols-[1fr_auto]"
            >
              <input
                type="hidden"
                name="quotationNumber"
                value={quotation.quotationNumber}
              />

              <input
                type="hidden"
                name="updatedAt"
                value={quotation.updatedAt.toISOString()}
              />

              <label className="grid gap-2 text-sm font-semibold text-slate-700">
                Next Status
                <select
                  name="status"
                  required
                  defaultValue=""
                  className="rounded-xl border border-slate-200 bg-white p-3"
                >
                  <option
                    value=""
                    disabled
                  >
                    Select next status
                  </option>

                  {nextStatuses.map((status) => (
                    <option
                      key={status}
                      value={status}
                    >
                      {status.replaceAll("_", " ")}
                    </option>
                  ))}
                </select>
              </label>

              <button
                type="submit"
                className="self-end rounded-xl bg-blue-600 px-5 py-3 font-extrabold text-white transition hover:bg-blue-700"
              >
                <span className="inline-flex items-center gap-2">
                  <Send size={17} />
                  Update Status
                </span>
              </button>
            </form>
          )}

          <p className="mt-4 text-xs text-slate-400">
            Approved, rejected, expired and cancelled quotations are locked against further lifecycle changes.
          </p>
        </section>
      </main>
    </CustomerAdminShell>
  );
}
