import { createContext, useContext, type ReactNode } from 'react';
import { RechargeModal } from '../components/RechargeModal';
import { useTKMindChat } from '../hooks/useTKMindChat';
import type { CapabilityMap, PortalUser } from '../types';

type ChatContextValue = ReturnType<typeof useTKMindChat>;

const ChatContext = createContext<ChatContextValue | null>(null);

export function ChatProvider({
  user,
  capabilities,
  onUserUpdate,
  children,
}: {
  user?: PortalUser | null;
  capabilities?: CapabilityMap | null;
  onUserUpdate?: (user: PortalUser) => void;
  children: ReactNode;
}) {
  const chat = useTKMindChat(user, onUserUpdate, capabilities);

  return (
    <ChatContext.Provider value={chat}>
      {children}
      {typeof chat.balanceCents === 'number' && chat.rechargePrompt && (
        <RechargeModal
          open={chat.rechargePrompt}
          force={chat.rechargeForced}
          balanceCents={chat.balanceCents}
          onClose={chat.dismissRecharge}
          onSuccess={(nextBalance) => {
            chat.completeRecharge(nextBalance);
          }}
        />
      )}
    </ChatContext.Provider>
  );
}

export function useChat(): ChatContextValue {
  const value = useContext(ChatContext);
  if (!value) {
    throw new Error('useChat must be used within ChatProvider');
  }
  return value;
}
