"use client";

import * as React from "react";
import { useParams } from "next/navigation";

import { customerUrl } from "@/lib/tenant";

import { holdingsWidgetLayoutId } from "@/app/customer/_components/holdings-widgets-grid";
import { useWidgetSettingsAction } from "@/app/customer/_components/dashboard-widget-configure-provider";
import { useBatchedWidgetLoader } from "@/app/customer/_lib/use-batched-widget-loader";
import { useDashboardWidgetConfigRefresh } from "@/app/customer/_lib/use-dashboard-widget-config-refresh";
import { configureParamForWidget } from "@/app/customer/[tenant]/settings/_components/widget-config";

import { fetchDiyHoldingsWidgetClient } from "@/app/customer/[tenant]/reports/diy-consolidated-holdings/_lib/diy-consolidated-holdings-widget-api";
import type { DiyHoldingsWidgetData } from "@/app/customer/[tenant]/reports/diy-consolidated-holdings/_lib/diy-consolidated-holdings-widget-server-api";

import { HoldingsDonutWidget, type HoldingsDonutSlice } from "./holdings-donut-widget";
import {
  diyBreadcrumb,
  diyLevelLabel,
  isHoldingsDrillPending,
  normalizeDiySliceName,
} from "./holdings-widget-utils";

type DiyConsolidatedHoldingsWidgetProps = {
  widgetId: number;
  title?: string;
  className?: string;
  layoutId?: string;
};

export function DiyConsolidatedHoldingsWidget({
  widgetId,
  title = "DIY Consolidated Holdings",
  className,
  layoutId: layoutIdProp,
}: DiyConsolidatedHoldingsWidgetProps) {
  const params = useParams<{ tenant: string }>();
  const tenant = params?.tenant ?? "";
  const layoutId = layoutIdProp ?? holdingsWidgetLayoutId("diy", widgetId);

  const [drillValue, setDrillValue] = React.useState<string | undefined>(undefined);
  const isDrilled = Boolean(drillValue);

  const fetchIndividual = React.useCallback(async () => {
    if (!tenant || widgetId <= 0) {
      return { data: null, errorMessage: null };
    }
    const result = await fetchDiyHoldingsWidgetClient(tenant, { widgetId, drillValue });
    return { data: result.data, errorMessage: result.errorMessage };
  }, [tenant, widgetId, drillValue]);

  const { data, loading, refreshing, error, refresh } = useBatchedWidgetLoader<DiyHoldingsWidgetData>({
    layoutId,
    fetchIndividual,
    skipBatch: isDrilled,
  });

  useDashboardWidgetConfigRefresh(widgetId, refresh);

  const slices: HoldingsDonutSlice[] = React.useMemo(() => {
    if (!data?.classes) return [];
    return data.classes.map((row) => ({
      name: normalizeDiySliceName(row.name),
      mv: row.mv,
      mv_fmt: row.mv_fmt,
      pct: row.pct,
      // Disable while drilled or pending; HoldingsDonutWidget also gates on drillPending.
      drillable: Boolean(row.drill_key) && !isDrilled,
    }));
  }, [data, isDrilled]);

  const handleDrill = React.useCallback(
    (slice: HoldingsDonutSlice) => {
      if (!data || isDrilled || data.drill_active) return;
      const row = data.classes.find(
        (item) => normalizeDiySliceName(item.name) === slice.name || item.name === slice.name,
      );
      const key = row?.drill_key ?? slice.name;
      if (!key || key === "Unknown") return;
      setDrillValue(key);
    },
    [data, isDrilled],
  );

  const settingsHrefFallback = customerUrl(
    tenant,
    `/settings?section=dashboard&configure=${configureParamForWidget("diy", widgetId)}`,
  );
  const { settingsHref, onSettingsClick } = useWidgetSettingsAction(widgetId, settingsHrefFallback);
  const reportHref = customerUrl(tenant, "/reports/consolidated-holdings-report");
  const drillPending = isHoldingsDrillPending(isDrilled, data?.drill_active);
  const subtitle = data
    ? diyBreadcrumb({
        drillActive: isDrilled || data.drill_active,
        drillValue: drillValue ?? data.drill_value,
        level1: data.level1,
        level2: data.level2,
      })
    : "TOTAL";
  const drillHint =
    data && !isDrilled && !data.drill_active
      ? `Click: drill into ${diyLevelLabel(data.level2)}`
      : null;

  return (
    <HoldingsDonutWidget
      title={title}
      subtitle={subtitle}
      currency={data?.currency ?? "USD"}
      totalMv={data?.total_mv ?? 0}
      totalMvFmt={data?.total_mv_fmt ?? "0.00"}
      slices={slices}
      loading={loading}
      refreshing={refreshing}
      drillPending={drillPending}
      error={error}
      settingsHref={settingsHref}
      onSettingsClick={onSettingsClick}
      reportHref={reportHref}
      drillHint={drillHint}
      canDrillUp={isDrilled}
      onRefresh={() => void refresh()}
      onDrill={handleDrill}
      onDrillUp={() => setDrillValue(undefined)}
      className={className}
    />
  );
}
