// Hands-On tutorial — RELATED-LIST Header Action.
//
// Renders inside the toolbar of the "Hands-On Assets" related-list
// on the movie edit page. Visibility is gated by a single config
// row in MIB3UX_PAGE_COMPONENT_CONFIGURATIONS keyed `refreshAllAssets`
// on the movies-edit page's assets template-component. Drop the
// config row and the button disappears — the React shell never knows
// the export exists.
//
// Props (delivered by the core RelatedList renderer):
//   - events  — the related-list's lifecycle callbacks. After we
//               hit the backend re-scan endpoint, call events.refresh()
//               so the underlying SimpleRelatedListComponent reloads
//               its data without a full page reload.
//   - componentKey — the template-component key (passed through for
//               action handlers that need to know which related list
//               they were invoked against).

import React, { useState } from "react";
import { SecondaryButton, successMessage, errorMessage } from "@agilecontent/ui";
import { ReloadOutlined } from "@agilecontent/ui/icons";
import { type Decorators } from "@agilecontent/mib-modules";
import { publishAssetEvent } from "../hooks/useAssetEvents";

type Props = {
  events?: Decorators["relatedList"]["events"];
  componentKey?: string;
};

export default function RefreshAllAssetsAction({ events }: Props) {
  const [busy, setBusy] = useState(false);

  const onClick = async (e: React.MouseEvent) => {
    // Same form-submit guard as the per-row action — the toolbar
    // lives inside the host edit-page's <form>, so a stray submit
    // would POST the entire movie record instead of running our
    // re-scan call.
    e.preventDefault();
    e.stopPropagation();
    setBusy(true);
    try {
      // Use the shell's pre-configured axios instance so the
      // `Authorization: Bearer <jwt>` header gets attached
      // automatically. A bare `fetch` lands without auth and is
      // 302-redirected to /login. The shell exposes the instance on
      // `window.cms.instance` for exactly this reason.
      const res = await (window as any).cms.instance.post(
        "/api/v2/handson/assets/reindex",
      );
      const { affected } = res.data as { affected: number };
      successMessage(`Re-scanned ${affected} assets`);
      // Reload the related-list so any backend-side changes show up.
      events?.refresh?.();
      // Broadcast to any other component on the page that cares —
      // e.g. the Movie Dashboard widget re-computes its asset stats.
      publishAssetEvent("reindexed", { affected });
    } catch (e: any) {
      errorMessage(`Re-scan failed: ${e.message}`);
    } finally {
      setBusy(false);
    }
  };

  return (
    <SecondaryButton
      // Same form-submit guard as the per-row action — the toolbar
      // sits inside the host edit-page's <form>, so an implicit
      // submit type would post the movie record.
      htmlType="button"
      loading={busy}
      icon={<ReloadOutlined />}
      onClick={onClick}
    >
      Re-scan all assets
    </SecondaryButton>
  );
}
