import { useCallback, useMemo } from "react";
import { listRegions } from "@/shared/api/regions";
import { useAdminQuery } from "@/shared/hooks/useAdminQuery.js";

const emptyData = { items: [], total: 0 };

export function useRegionOptions() {
  const queryFn = useCallback(() => listRegions(), []);
  const { data = emptyData, loading: loadingRegions } = useAdminQuery(queryFn, {
    errorMessage: "加载区域选项失败",
    initialData: emptyData,
    queryKey: ["regions", "options"],
    staleTime: 5 * 60 * 1000
  });

  const regionOptions = useMemo(() => {
    return (data?.items || [])
      .filter((region) => region.regionCode !== "GLOBAL")
      .map((region) => ({
        label: formatRegionLabel(region),
        name: region.name,
        regionCode: region.regionCode,
        regionId: region.regionId,
        value: String(region.regionId)
      }));
  }, [data?.items]);

  return { loadingRegions, regionOptions };
}

function formatRegionLabel(region) {
  return [region.name, region.regionCode, region.regionId].filter(Boolean).join(" · ");
}
