import React, { createContext, useCallback, useContext, useMemo } from 'react';
import { useAtomValue } from 'jotai';
import { cdnUrlAtom } from '../../atoms/envive/enviveConfig';

interface CdnContextType {
  cdnUrl: string;
  getCdnBasePath: () => string;
  getAssetURL: (assetName: string, orgShortName: string) => string;
}

const CdnContext = createContext<CdnContextType | null>(null);

export const CdnProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const cdnUrlAtomValue = useAtomValue(cdnUrlAtom);
  const cdnUrl = cdnUrlAtomValue || 'https://cdn.spiffy.ai/other';

  const getCdnBasePath = useCallback(() => {
    return cdnUrl;
  }, [cdnUrl]);

  const getAssetURL = useCallback(
    (assetName: string, orgShortName: string) => {
      return `${getCdnBasePath()}/assets/${orgShortName}/${assetName}`;
    },
    [getCdnBasePath],
  );

  const value = useMemo(
    () => ({
      cdnUrl,
      getCdnBasePath,
      getAssetURL,
    }),
    [cdnUrl, getCdnBasePath, getAssetURL],
  );

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

export const useCdn = () => {
  const context = useContext(CdnContext);
  if (!context) {
    throw new Error('useCdn must be used within a CdnProvider');
  }
  return context;
};
