"use client";

import React, { createContext, useContext, useState } from "react";
import { useSearchParams } from "next/navigation";
import { useChatHistory } from "@/components/chat/useChatHistory";
import type { AssistantMessageUpdate, ChatMessage, Conversation } from "@/components/chat/types";

interface ChatShellContextValue {
  accessToken: string;
  userId: string;
  userEmail: string;
  userRole: string;
  premiumUser: boolean;
  selectedMCPServers: string[];
  setSelectedMCPServers: (servers: string[]) => void;
  conversations: Conversation[];
  activeConversation: Conversation | null;
  activeConversationId: string | null;
  storageUnavailable: boolean;
  staleId: boolean;
  createConversation: (model: string) => string;
  appendMessage: (conversationId: string, message: Omit<ChatMessage, "id" | "timestamp">) => void;
  updateLastAssistantMessage: (conversationId: string, updates: AssistantMessageUpdate) => void;
  truncateFromMessage: (conversationId: string, messageId: string) => void;
  deleteConversation: (id: string) => void;
  renameConversation: (id: string, newTitle: string) => void;
}

const ChatShellContext = createContext<ChatShellContextValue | null>(null);

export function useChatShell(): ChatShellContextValue {
  const ctx = useContext(ChatShellContext);
  if (!ctx) {
    throw new Error("useChatShell must be used within a ChatShellProvider");
  }
  return ctx;
}

interface ChatShellProviderProps {
  accessToken: string;
  userId: string;
  userEmail: string;
  userRole: string;
  premiumUser: boolean;
  children: React.ReactNode;
}

export function ChatShellProvider({
  accessToken,
  userId,
  userEmail,
  userRole,
  premiumUser,
  children,
}: ChatShellProviderProps) {
  const searchParams = useSearchParams();
  const urlConversationId = searchParams.get("id");
  const [selectedMCPServers, setSelectedMCPServers] = useState<string[]>([]);

  const {
    conversations,
    activeConversation,
    currentActiveId,
    storageUnavailable,
    staleId,
    createConversation,
    appendMessage,
    updateLastAssistantMessage,
    truncateFromMessage,
    deleteConversation,
    renameConversation,
  } = useChatHistory(urlConversationId, userId);

  return (
    <ChatShellContext.Provider
      value={{
        accessToken,
        userId,
        userEmail,
        userRole,
        premiumUser,
        selectedMCPServers,
        setSelectedMCPServers,
        conversations,
        activeConversation,
        activeConversationId: currentActiveId,
        storageUnavailable,
        staleId,
        createConversation,
        appendMessage,
        updateLastAssistantMessage,
        truncateFromMessage,
        deleteConversation,
        renameConversation,
      }}
    >
      {children}
    </ChatShellContext.Provider>
  );
}
