import { Split } from "lucide-react";

import { ListPageCard } from "@/app/dashboard/_components";

import { BulkEditForm } from "./_components/bulk-edit-form";
import { fetchCorporateAction } from "./_lib/corporate-action-server-api";
import type { PreviewResult } from "./_lib/schema";

const LIST_HREF = "/dashboard/master-table/structure-master";

type PageProps = {
  searchParams: Promise<{ isin?: string; action?: string }>;
};

export default async function StructureBulkEditPage({ searchParams }: PageProps) {
  const { isin, action } = await searchParams;

  const actionId = Number(action);
  const isEdit = Number.isInteger(actionId) && actionId > 0;

  let initialPreview: PreviewResult | undefined;
  let loadError: string | undefined;

  if (isEdit) {
    const { result, errorMessage } = await fetchCorporateAction({ actionId });
    if (result) {
      // The backend owns this verdict; loading an uneditable action read-only
      // would let the operator fill in a form that can only fail on submit.
      if (result.action.isEditable) {
        initialPreview = result;
      } else {
        loadError =
          result.action.editBlockedReason ??
          "This corporate action can no longer be edited.";
      }
    } else {
      loadError = errorMessage ?? "Could not load the corporate action.";
    }
  }

  const editing = Boolean(initialPreview);

  return (
    <ListPageCard
      icon={Split}
      title={
        editing
          ? `Edit bulk edit — ${initialPreview?.action.underlyingIsin}`
          : "Bulk edit — stock split"
      }
      description={
        editing
          ? "Change the underlying, window or ratio and rebuild the preview. The existing draft is rewritten in place; nothing has been written to any transaction yet."
          : "Apply a split ratio to a structure underlying. Preview every affected record before saving — applying rewrites the structure master, the staged feed rows and live client holdings together."
      }
      breadcrumb={[
        { label: "Master Table" },
        { label: "Structure master", href: LIST_HREF },
        ...(editing
          ? [
              { label: "Corporate actions", href: `${LIST_HREF}/corporate-actions` },
              { label: "Edit" },
            ]
          : [{ label: "Bulk edit" }]),
      ]}
    >
      <BulkEditForm
        prefillIsin={isin?.trim() || undefined}
        initialPreview={initialPreview}
        loadError={loadError}
      />
    </ListPageCard>
  );
}
