import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowLeft, ScrollText } from "lucide-react";

import { CustomerPageShell } from "@/app/customer/_components/customer-page-shell";
import { OrderBlotterStepForm } from "@/app/dashboard/order-blotter/_components/order-blotter-step-form";
import { fetchCustomerOrderBlotterCreateDraft } from "@/lib/order-blotter/order-blotter-server-api";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import {
  decodeCorporateDbSlugFromUrl,
  decodeRouteIntParam,
} from "@/lib/order-blotter/route-params";
import { customerUrl } from "@/lib/tenant";

type PageProps = {
  params: Promise<{ tenant: string }>;
  searchParams: Promise<{
    transaction_id?: string;
    customer_id?: string;
    corporate_db?: string;
  }>;
};

export default async function CustomerOrderBlotterCreatePage({ params, searchParams }: PageProps) {
  const { tenant } = await params;
  const q = await searchParams;
  const transactionId = decodeRouteIntParam(q.transaction_id ?? "");
  if (transactionId <= 0) {
    notFound();
  }

  const customerIdRaw = decodeRouteIntParam(q.customer_id ?? "");
  const customerId = customerIdRaw > 0 ? customerIdRaw : null;
  const corporateDb = q.corporate_db ? decodeCorporateDbSlugFromUrl(q.corporate_db) || null : null;
  const blotterBase = customerUrl(tenant, "/order-blotter");
  const transactionsHref = customerUrl(tenant, "/transactions");

  const { detail, errorMessage, prefilled } = await fetchCustomerOrderBlotterCreateDraft(tenant, {
    transactionId,
    customerId,
    corporateDb,
  });

  return (
    <CustomerPageShell>
      <div className="flex flex-col gap-3 md:gap-4">
        <div className="flex flex-col gap-2 border-b pb-3 sm:flex-row sm:items-center sm:justify-between">
          <div className="flex items-center gap-2">
            <ScrollText className="size-5 text-violet-600 dark:text-violet-400" />
            <h1 className="font-semibold text-base tracking-tight">
              {prefilled
                ? `New order blotter from transaction #${transactionId}`
                : "New order blotter"}
            </h1>
          </div>
          <Button variant="outline" size="sm" className="gap-1.5" asChild>
            <Link href={transactionsHref}>
              <ArrowLeft className="size-4" />
              Back to transactions
            </Link>
          </Button>
        </div>

        {!detail ? (
          <Card>
            <CardContent className="pt-6">
              <p className="text-destructive text-sm">
                {errorMessage ?? "Could not prefill order blotter from this transaction."}
              </p>
            </CardContent>
          </Card>
        ) : (
          <OrderBlotterStepForm
            detail={detail}
            isCreate
            savePath={customerUrl(tenant, "/order-blotter/save")}
            ocrPath={customerUrl(tenant, "/order-blotter/ocr")}
            redirectBase={blotterBase}
            prefilledFromTransaction={prefilled}
            transactionId={transactionId}
          />
        )}
      </div>
    </CustomerPageShell>
  );
}
