"use client";

import Link from "next/link";
import { useCallback, useEffect, useState } from "react";

import { ArrowLeft, Download, FileText, History, Pencil } from "lucide-react";

import type { OrderBlotterHistory } from "@/app/dashboard/order-blotter/_components/history-types";
import { OrderBlotterHistorySheet } from "@/app/dashboard/order-blotter/_components/order-blotter-history-sheet";
import { Button } from "@/components/ui/button";
import { isRecord } from "@/lib/server-utils";

type OrderBlotterDetailHeaderProps = {
  id: number;
  action?: string;
  basePath?: string;
  listPath?: string;
  listLabel?: string;
  /** When set, appended to action links (`&ref=…`). */
  refToken?: string | null;
  /** Came from blotter list — keep `from=list` on internal links. */
  fromList?: boolean;
  /** Open change history in a side sheet instead of navigating. */
  historyInSheet?: boolean;
  history?: OrderBlotterHistory | null;
  /** Absolute or app-relative download URLs (proxy routes). */
  pdfHref?: string | null;
  exportHref?: string | null;
};

function buildDownloadHref(
  explicit: string | null | undefined,
  fallbackBase: string,
  kind: "pdf" | "export",
  id: number,
  refToken: string | null,
) {
  if (explicit) return explicit;
  const params = new URLSearchParams();
  if (id > 0) params.set("id", String(id));
  if (refToken?.trim()) params.set("ref", refToken.trim());
  const qs = params.toString();
  // /dashboard/order-blotter/2 → /dashboard/order-blotter/pdf
  const root = fallbackBase.replace(/\/\d+$/, "");
  return `${root}/${kind}${qs ? `?${qs}` : ""}`;
}

function buildHistoryApiHref(basePath: string, id: number, refToken: string | null) {
  const params = new URLSearchParams();
  if (id > 0) params.set("id", String(id));
  if (refToken?.trim()) params.set("ref", refToken.trim());
  const qs = params.toString();
  const root = basePath.replace(/\/\d+$/, "");
  return `${root}/history${qs ? `?${qs}` : ""}`;
}

export function OrderBlotterDetailHeader({
  id,
  action,
  basePath = "/dashboard/order-blotter",
  listPath = "/dashboard/order-blotter",
  listLabel = "Back to list",
  refToken = null,
  fromList = false,
  historyInSheet = false,
  history = null,
  pdfHref = null,
  exportHref = null,
}: OrderBlotterDetailHeaderProps) {
  const [historyOpen, setHistoryOpen] = useState(false);
  const [loadedHistory, setLoadedHistory] = useState<OrderBlotterHistory | null>(history);
  const [historyLoading, setHistoryLoading] = useState(false);

  useEffect(() => {
    if (history) setLoadedHistory(history);
  }, [history]);

  const base = `${basePath}/${id}`;
  const refQs = refToken?.trim() ? `&ref=${encodeURIComponent(refToken.trim())}` : "";
  const fromQs = fromList ? "&from=list" : "";
  const resolvedPdfHref = buildDownloadHref(pdfHref, basePath, "pdf", id, refToken);
  const resolvedExportHref = buildDownloadHref(exportHref, basePath, "export", id, refToken);
  const historyApi = buildHistoryApiHref(basePath, id, refToken);
  const actionLabel =
    action === "view"
      ? "View"
      : action === "update"
        ? "Edit"
        : action === "history"
          ? "Change history"
          : "Detail";

  const openHistorySheet = useCallback(async () => {
    setHistoryOpen(true);
    if (loadedHistory || historyLoading) return;

    setHistoryLoading(true);
    try {
      const response = await fetch(historyApi, {
        method: "GET",
        headers: { Accept: "application/json" },
        cache: "no-store",
      });
      const payload = (await response.json().catch(() => null)) as unknown;
      if (!response.ok || !isRecord(payload) || !isRecord(payload.data)) {
        setLoadedHistory(null);
        return;
      }
      setLoadedHistory(payload.data as OrderBlotterHistory);
    } catch {
      setLoadedHistory(null);
    } finally {
      setHistoryLoading(false);
    }
  }, [historyApi, historyLoading, loadedHistory]);

  return (
    <>
      <div className="flex flex-col gap-3 border-b border-border/70 pb-3 sm:flex-row sm:items-center sm:justify-between">
        <h1 className="font-semibold text-base tracking-tight">
          {actionLabel} order blotter #{id}
        </h1>
        <div className="flex flex-wrap items-center gap-2">
          <Button variant="outline" size="sm" className="gap-1.5" asChild>
            <a href={resolvedPdfHref} target="_blank" rel="noreferrer">
              <FileText className="size-4" />
              Download PDF
            </a>
          </Button>
          <Button size="sm" className="gap-1.5" asChild>
            <Link href={`${base}?action=update${fromQs}${refQs}`}>
              <Pencil className="size-4" />
              Edit
            </Link>
          </Button>
          {historyInSheet ? (
            <Button
              type="button"
              variant="outline"
              size="sm"
              className="gap-1.5"
              onClick={() => void openHistorySheet()}
              disabled={historyLoading}
            >
              <History className="size-4" />
              Change history
            </Button>
          ) : (
            <Button variant="outline" size="sm" className="gap-1.5" asChild>
              <Link href={`${base}?action=history${fromQs}${refQs}`}>
                <History className="size-4" />
                Change history
              </Link>
            </Button>
          )}
          <Button variant="outline" size="sm" className="gap-1.5" asChild>
            <a href={resolvedExportHref}>
              <Download className="size-4" />
              Export row CSV
            </a>
          </Button>
          <Button variant="outline" size="sm" className="gap-1.5" asChild>
            <Link href={listPath}>
              <ArrowLeft className="size-4" />
              {listLabel}
            </Link>
          </Button>
        </div>
      </div>

      {historyInSheet ? (
        <OrderBlotterHistorySheet
          id={id}
          history={loadedHistory}
          open={historyOpen}
          onOpenChange={setHistoryOpen}
        />
      ) : null}
    </>
  );
}
