"use client";

import type { ReactNode } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";

import { RecordViewActions } from "@/app/customer/_components/record-view/record-view-layout";
import { postCustomerMutation } from "@/app/customer/_lib/customer-asset-mutation-client";

type RecordViewMutationActionsProps = {
  localId: string;
  refId: string;
  listHref: string;
  cashflowHref: string;
  editHref: string;
  reportHref?: string | null;
  reportLabel?: string;
  canDelete?: boolean;
  deleteLabel?: string;
  deleteDescription?: ReactNode;
  /** Absolute Next.js route that accepts `{ id }` — must be serializable for RSC. */
  deleteHref: string;
  successTitle?: string;
};

export function RecordViewMutationActions({
  localId,
  refId,
  listHref,
  cashflowHref,
  editHref,
  reportHref,
  reportLabel,
  canDelete = true,
  deleteLabel = "transaction",
  deleteDescription,
  deleteHref,
  successTitle,
}: RecordViewMutationActionsProps) {
  const router = useRouter();

  async function handleDelete() {
    try {
      await postCustomerMutation(
        deleteHref,
        { id: localId },
        `${deleteLabel} could not be deleted.`,
      );
      toast.success(successTitle ?? `${deleteLabel} deleted`, {
        description: `${refId} has been removed.`,
      });
      router.push(listHref);
      router.refresh();
    } catch (error) {
      toast.error(
        error instanceof Error ? error.message : `${deleteLabel} could not be deleted.`,
      );
      throw error;
    }
  }

  return (
    <RecordViewActions
      backHref={listHref}
      cashflowHref={cashflowHref}
      editHref={editHref}
      reportHref={reportHref}
      reportLabel={reportLabel}
      onDelete={handleDelete}
      canDelete={canDelete}
      deleteLabel={deleteLabel}
      deleteDescription={
        deleteDescription ?? (
          <>
            <span className="font-medium text-foreground">{refId}</span> will be removed. This
            cannot be undone.
          </>
        )
      }
    />
  );
}
