import { useEffect, useState } from 'react';
import { ApiError } from './client';
import { getChannels, type ChannelSummary } from './channels';

type ChannelsQueryState =
  | { channels: ChannelSummary[]; error: null; status: 'success' }
  | { channels: null; error: string; status: 'error' }
  | { channels: null; error: null; status: 'loading' };

export function useChannelsQuery(): ChannelsQueryState {
  const [state, setState] = useState<ChannelsQueryState>({
    channels: null,
    error: null,
    status: 'loading'
  });

  useEffect(() => {
    let active = true;

    getChannels()
      .then((channels) => {
        if (active) {
          setState({ channels, error: null, status: 'success' });
        }
      })
      .catch((error: unknown) => {
        if (active) {
          setState({ channels: null, error: messageFromError(error), status: 'error' });
        }
      });

    return () => {
      active = false;
    };
  }, []);

  return state;
}

function messageFromError(error: unknown): string {
  if (error instanceof ApiError) {
    return error.detail ?? error.message;
  }

  if (error instanceof Error) {
    return error.message;
  }

  return 'Unable to load channels';
}
