import React, { createContext, useContext, useEffect, useMemo } from 'react';
import type { PropsWithChildren } from 'react';
import { httpClient, setAuthToken, clearAuthToken } from '../lib/apiClient';

type HttpClient = typeof httpClient;

interface ApiContextValue {
  client: HttpClient;
  setAuthToken: (token: string) => void;
  clearAuthToken: () => void;
}

const ApiContext = createContext<ApiContextValue | null>(null);

export const ApiProvider: React.FC<PropsWithChildren<{ initialToken?: string | null }>> = ({
  initialToken = null,
  children,
}) => {
  useEffect(() => {
    if (initialToken) {
      setAuthToken(initialToken);
    }
  }, [initialToken]);

  const value = useMemo<ApiContextValue>(
    () => ({
      client: httpClient,
      setAuthToken,
      clearAuthToken,
    }),
    [],
  );

  return <ApiContext.Provider value={value}>{children}</ApiContext.Provider>;
};

export const useApi = (): ApiContextValue => {
  const ctx = useContext(ApiContext);
  if (!ctx) {
    throw new Error('useApi must be used within an ApiProvider');
  }
  return ctx;
};

export const getHttpClient = (): HttpClient => httpClient;
