import React, { createContext, useContext, useReducer, useEffect } from "react";
import { setDispatch } from "./streamManager";

const AppContext = createContext(null);

const initialState = {
  token: localStorage.getItem("token") || null,
  user: null,
  chats: [],
  activeChatId: null,
  chatMessages: {},
  activeStreams: {},
};

function reducer(state, action) {
  switch (action.type) {
    case "SET_AUTH":
      localStorage.setItem("token", action.token);
      return { ...state, token: action.token, user: action.user };
    case "LOGOUT":
      localStorage.removeItem("token");
      return { ...initialState, token: null };
    case "SET_USER":
      return { ...state, user: action.user };
    case "SET_CHATS":
      return { ...state, chats: action.chats };
    case "SET_ACTIVE_CHAT":
      return { ...state, activeChatId: action.chatId };
    case "ADD_CHAT":
      return { ...state, chats: [action.chat, ...state.chats] };
    case "UPDATE_CHAT": {
      const updated = state.chats.map((c) =>
        c.id === action.chat.id ? { ...c, ...action.chat } : c
      );
      return { ...state, chats: updated };
    }
    case "REMOVE_CHAT":
      return {
        ...state,
        chats: state.chats.filter((c) => c.id !== action.chatId),
        activeChatId: state.activeChatId === action.chatId ? null : state.activeChatId,
        chatMessages: { ...state.chatMessages, [action.chatId]: undefined },
      };
    case "SET_MESSAGES":
      return {
        ...state,
        chatMessages: { ...state.chatMessages, [action.chatId]: action.messages },
      };
    case "ADD_MESSAGE": {
      const prev = state.chatMessages[action.chatId] || [];
      return {
        ...state,
        chatMessages: { ...state.chatMessages, [action.chatId]: [...prev, action.message] },
      };
    }
    case "SET_STREAMING":
      return {
        ...state,
        activeStreams: { ...state.activeStreams, [action.chatId]: action.streaming },
      };
    default:
      return state;
  }
}

export function AppProvider({ children }) {
  const [state, dispatch] = useReducer(reducer, initialState);

  useEffect(() => {
    setDispatch(dispatch);
  }, [dispatch]);

  return (
    <AppContext.Provider value={{ state, dispatch }}>
      {children}
    </AppContext.Provider>
  );
}

export function useApp() {
  const ctx = useContext(AppContext);
  if (!ctx) throw new Error("useApp must be used within AppProvider");
  return ctx;
}

export function usePermissions() {
  const { state } = useApp();
  return state.user?.permissions || {
    can_use_knowledge_base: true,
    can_use_gitlab: true,
  };
}