'use client';

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

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

export function useGuildChannels(guildId: string): {
  channels: DiscordChannelOption[];
  loading: boolean;
} {
  const [channels, setChannels] = useState<DiscordChannelOption[]>(() => cache.get(guildId) ?? []);
  const [loading, setLoading] = useState(!cache.has(guildId));

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

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

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

  return { channels, loading };
}
