import { useCallback, useMemo } from "react";
import { useAdminQuery } from "@/shared/hooks/useAdminQuery.js";
import { listCountries } from "@/features/host-org/api";

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

export function useCountryOptions() {
  const queryFn = useCallback(() => listCountries({ enabled: true }), []);
  const { data = emptyData, loading: loadingCountries } = useAdminQuery(queryFn, {
    errorMessage: "加载国家选项失败",
    initialData: emptyData,
    queryKey: ["host-org", "countries", "enabled-options"],
    staleTime: 5 * 60 * 1000
  });

  const countryOptions = useMemo(() => {
    return (data?.items || []).map((country) => ({
      label: formatCountryOptionLabel(country),
      value: country.countryCode
    }));
  }, [data?.items]);

  return { countryOptions, loadingCountries };
}

function formatCountryOptionLabel(country) {
  return [country.flag, country.countryDisplayName || country.countryName, country.countryCode].filter(Boolean).join(" · ");
}
