'use client';

import type { DiscordRoleOption } from '@nexumi/shared';
import { useEffect, useState } from 'react';

const cache = new Map<string, DiscordRoleOption[]>();

export function useGuildRoles(guildId: string): {
  roles: DiscordRoleOption[];
  loading: boolean;
} {
  const [roles, setRoles] = useState<DiscordRoleOption[]>(() => cache.get(guildId) ?? []);
  const [loading, setLoading] = useState(!cache.has(guildId));

  useEffect(() => {
    let cancelled = false;
    const cached = cache.get(guildId);
    if (cached) {
      setRoles(cached);
      setLoading(false);
      return;
    }

    setLoading(true);
    void fetch(`/api/guilds/${guildId}/roles`)
      .then(async (response) => {
        if (!response.ok) {
          return [] as DiscordRoleOption[];
        }
        return (await response.json()) as DiscordRoleOption[];
      })
      .then((data) => {
        if (cancelled) {
          return;
        }
        cache.set(guildId, data);
        setRoles(data);
      })
      .catch(() => {
        if (!cancelled) {
          setRoles([]);
        }
      })
      .finally(() => {
        if (!cancelled) {
          setLoading(false);
        }
      });

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

  return { roles, loading };
}
