"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";
import { toastApiError } from "@/lib/toast-api-error";

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;
  /**
   * Id posted to delete (defaults to localId). Use composite `id-customerId` on
   * corporate/JREPORT views so Yii soft-deletes the correct dual-DB row.
   */
  deleteId?: string;
  /** Optional portfolio client id for corporate consolidator deletes. */
  deleteCustomerId?: number | null;
};

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

  async function handleDelete() {
    try {
      const body: Record<string, unknown> = { id: deleteId?.trim() || localId };
      if (deleteCustomerId != null && deleteCustomerId > 0) {
        body.row_customer_id = deleteCustomerId;
        body.customer_id = deleteCustomerId;
      }
      await postCustomerMutation(
        deleteHref,
        body,
        `${deleteLabel} could not be deleted.`,
      );
      toast.success(successTitle ?? `${deleteLabel} deleted`, {
        description: `${refId} has been removed.`,
      });
      router.push(listHref);
      router.refresh();
    } catch (error) {
      toastApiError(error, `${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.
          </>
        )
      }
    />
  );
}
