"use client";

import * as React from "react";

import { fetchAssetWidgetCatalogClient } from "@/app/customer/[tenant]/settings/asset-widget/_lib/asset-widget-api";
import type { AssetWidgetCatalogItem } from "@/app/customer/[tenant]/settings/asset-widget/_lib/asset-widget-server-api";

export type HoldingsWidgetEntry = {
  kind: "ch" | "diy" | "aa";
  widget: AssetWidgetCatalogItem;
  layoutId: string;
};

export function holdingsWidgetLayoutId(kind: "ch" | "diy" | "aa", widgetId: number): string {
  if (kind === "ch") return `chw-${widgetId}`;
  if (kind === "diy") return `diyw-${widgetId}`;
  return `aaw-${widgetId}`;
}

export function useHoldingsWidgetCatalog(tenant: string) {
  const [entries, setEntries] = React.useState<HoldingsWidgetEntry[]>([]);
  const [loading, setLoading] = React.useState(true);
  const [error, setError] = React.useState<string | null>(null);

  React.useEffect(() => {
    if (!tenant) return;
    let cancelled = false;

    void (async () => {
      setLoading(true);
      setError(null);
      const result = await fetchAssetWidgetCatalogClient(tenant);
      if (cancelled) return;

      if (result.errorMessage) {
        setError(result.errorMessage);
        setEntries([]);
      } else {
        const next: HoldingsWidgetEntry[] = [
          ...(result.data?.ch_widgets_list ?? []).map((widget) => ({
            kind: "ch" as const,
            widget,
            layoutId: holdingsWidgetLayoutId("ch", widget.widget_id),
          })),
          ...(result.data?.diy_widgets_list ?? []).map((widget) => ({
            kind: "diy" as const,
            widget,
            layoutId: holdingsWidgetLayoutId("diy", widget.widget_id),
          })),
          ...(result.data?.asset_widgets_list ?? []).map((widget) => ({
            kind: "aa" as const,
            widget,
            layoutId: holdingsWidgetLayoutId("aa", widget.widget_id),
          })),
        ];
        setEntries(next);
      }
      setLoading(false);
    })();

    return () => {
      cancelled = true;
    };
  }, [tenant]);

  return { entries, loading, error };
}
