import { notFound } from "next/navigation";

import { CustomerPageShell } from "@/app/customer/_components/customer-page-shell";
import { OrderBlotterDetailHeader } from "@/app/dashboard/order-blotter/_components/order-blotter-detail-header";
import { OrderBlotterHistoryHeader } from "@/app/dashboard/order-blotter/_components/order-blotter-history-header";
import { OrderBlotterHistoryTimeline } from "@/app/dashboard/order-blotter/_components/order-blotter-history-timeline";
import { OrderBlotterStepForm } from "@/app/dashboard/order-blotter/_components/order-blotter-step-form";
import { OrderBlotterViewDocument } from "@/app/dashboard/order-blotter/_components/order-blotter-view-document";
import {
  fetchCustomerOrderBlotterDetail,
  fetchCustomerOrderBlotterHistory,
} from "@/lib/order-blotter/order-blotter-server-api";
import { Card, CardContent } from "@/components/ui/card";
import { customerUrl } from "@/lib/tenant";

type PageProps = {
  params: Promise<{ tenant: string; id: string }>;
  searchParams: Promise<{ action?: string; ref?: string; from?: string }>;
};

export default async function CustomerOrderBlotterDetailPage({ params, searchParams }: PageProps) {
  const { tenant, id: idParam } = await params;
  const { action, ref, from } = await searchParams;
  const id = Number(idParam);
  const hasRef = typeof ref === "string" && ref.trim() !== "";
  const fromList = from === "list";

  if (!hasRef && !Number.isFinite(id)) {
    notFound();
  }

  const lookup = {
    id: Number.isFinite(id) && id > 0 ? id : null,
    ref: hasRef ? ref.trim() : null,
  };

  const blotterBase = customerUrl(tenant, "/order-blotter");
  const transactionsHref = customerUrl(tenant, "/transactions");
  const listPath = fromList ? blotterBase : transactionsHref;
  const listLabel = fromList ? "Back to order blotter" : "Back to transactions";
  const savePath = customerUrl(tenant, "/order-blotter/save");

  const resolvedAction = action ?? "view";
  const needsHistory = resolvedAction === "history" || resolvedAction === "view";

  let detail: Awaited<ReturnType<typeof fetchCustomerOrderBlotterDetail>>["detail"] = null;
  let history: Awaited<ReturnType<typeof fetchCustomerOrderBlotterHistory>>["history"] = null;

  if (needsHistory) {
    const [detailResult, historyResult] = await Promise.all([
      fetchCustomerOrderBlotterDetail(tenant, lookup),
      fetchCustomerOrderBlotterHistory(tenant, lookup),
    ]);
    detail = detailResult.detail;
    history = historyResult.history;
  } else {
    const detailResult = await fetchCustomerOrderBlotterDetail(tenant, lookup);
    detail = detailResult.detail;
  }

  if (!detail) {
    notFound();
  }

  const resolvedId = detail.id > 0 ? detail.id : id;

  if (resolvedAction === "history") {
    if (!history) {
      notFound();
    }

    return (
      <CustomerPageShell>
        <div className="flex flex-col gap-3">
          <OrderBlotterHistoryHeader
            id={resolvedId}
            basePath={blotterBase}
            listPath={listPath}
            listLabel={listLabel}
            showBreadcrumb={false}
          />
          <Card className="gap-0 overflow-hidden border-border/80 py-0 shadow-sm">
            <CardContent className="p-4">
              <OrderBlotterHistoryTimeline history={history} />
            </CardContent>
          </Card>
        </div>
      </CustomerPageShell>
    );
  }

  if (resolvedAction === "view") {
    return (
      <CustomerPageShell>
        <div className="flex flex-col gap-3">
          <OrderBlotterDetailHeader
            id={resolvedId}
            action="view"
            basePath={blotterBase}
            listPath={listPath}
            listLabel={listLabel}
            refToken={lookup.ref}
            fromList={fromList}
            historyInSheet
            history={history}
          />
          <Card className="gap-0 overflow-hidden border-border/80 py-0 shadow-sm">
            <CardContent className="p-4">
              <OrderBlotterViewDocument detail={detail} />
            </CardContent>
          </Card>
        </div>
      </CustomerPageShell>
    );
  }

  if (resolvedAction === "update") {
    return (
      <CustomerPageShell>
        <div className="flex flex-col gap-4 md:gap-6">
          <OrderBlotterDetailHeader
            id={resolvedId}
            action="update"
            basePath={blotterBase}
            listPath={listPath}
            listLabel={listLabel}
            refToken={lookup.ref}
            fromList={fromList}
            historyInSheet
          />
          <Card>
            <CardContent className="pt-6">
              <OrderBlotterStepForm
                detail={detail}
                savePath={savePath}
                ocrPath={customerUrl(tenant, "/order-blotter/ocr")}
                redirectBase={blotterBase}
              />
            </CardContent>
          </Card>
        </div>
      </CustomerPageShell>
    );
  }

  notFound();
}
