import { LoadingSpinner } from "@ui/components/LoadingSpinner";
import { Chat, useCreateChatClient } from "stream-chat-react";
import { useUser } from "./UserStoreProvider";

export default function ChatProvider({ children }: { children: React.ReactNode }) {
  const apiKey = import.meta.env.VITE_STREAM_CHAT_API_KEY as string;
  const user = useUser();
  const client = useCreateChatClient({
    apiKey,
    options: { timeout: 5000 },
    tokenOrProvider: user.streamToken,
    userData: {
      id: user.id,
      name: user.name ?? "",
    },
  });

  if (!user.streamToken) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <h2 className="text-xl font-semibold text-red-600 mb-2">Chat Indisponible</h2>
          <p className="text-gray-600">
            Impossible de se connecter au service de chat. Veuillez essayer de rafraîchir la page.
          </p>
        </div>
      </div>
    );
  }

  if (!client) {
    return <LoadingSpinner />;
  }

  return (
    <Chat client={client} theme="team light">
      {children}
    </Chat>
  );
}
