import { createContext, useContext, type ReactNode } from 'react';
import { RechargeModal } from '../components/RechargeModal';
import { SubscribeModal } from '../components/SubscribeModal';
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,
  grantedSkills,
  goalRunEnabled,
  onUserUpdate,
  children,
}: {
  user?: PortalUser | null;
  capabilities?: CapabilityMap | null;
  grantedSkills?: string[];
  goalRunEnabled?: boolean;
  onUserUpdate?: (user: PortalUser) => void;
  children: ReactNode;
}) {
  const chat = useTKMindChat(user, onUserUpdate, capabilities, grantedSkills);

  return (
    <ChatContext.Provider value={{ ...chat, goalRunEnabled }}>
      {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);
          }}
        />
      )}
      <SubscribeModal
        open={chat.subscribePrompt}
        onClose={chat.dismissSubscribe}
        onSuccess={(subscription, balanceCents) => {
          chat.completeSubscribe(balanceCents, subscription);
        }}
        onRechargeNeeded={() => {
          chat.dismissSubscribe();
          chat.openRecharge(false);
        }}
      />
    </ChatContext.Provider>
  );
}

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