"use client";

import { useCallback, useEffect, useState } from "react";

import { getAdminIntegrationSites } from "@/api/admin-integration-sites";
import { adminHasAnyPermission } from "@/lib/admin-permissions";
import { PRD_INTEGRATION_ACCESS_ANY } from "@/lib/admin-prd";
import { useAdminProfile } from "@/stores/admin-session";

export type AdminSiteCodeOption = {
  code: string;
  name: string;
};

/**
 * 接入站点下拉（已按当前管理员站点权限过滤）。
 */
export function useAdminSiteCodeOptions(): {
  sites: AdminSiteCodeOption[];
  loading: boolean;
  canChooseSite: boolean;
  reload: () => Promise<void>;
} {
  const profile = useAdminProfile();
  const canLoad = adminHasAnyPermission(profile?.permissions, PRD_INTEGRATION_ACCESS_ANY);

  const [sites, setSites] = useState<AdminSiteCodeOption[]>([]);
  const [loading, setLoading] = useState(false);

  const reload = useCallback(async () => {
    if (!canLoad) {
      setSites([]);
      return;
    }

    setLoading(true);
    try {
      const data = await getAdminIntegrationSites();
      setSites(
        data.items.map((row) => ({
          code: row.code,
          name: row.name,
        })),
      );
    } catch {
      setSites([]);
    } finally {
      setLoading(false);
    }
  }, [canLoad]);

  useEffect(() => {
    queueMicrotask(() => {
      void reload();
    });
  }, [reload]);

  return {
    sites,
    loading,
    canChooseSite: canLoad && sites.length > 0,
    reload,
  };
}
