import { useState } from "react";
import { useChatCompletion } from "../hooks/useChatCompletion";
import { useChatSettings } from "../hooks/useChatSettings";
import { useUISettings } from "../hooks/useUISettings";
import ChatSettings from "./ChatSettings";
import LoadingIndicator from "./LoadingIndicator";
import MessageInput from "./MessageInput";
import MessagePair from "./MessagePair";
import OAuthLogin from "./OAuthLogin";
import TypingMessage from "./TypingMessage";
import UISettings from "./UISettings";

export default function ChatInterface() {
  const [hfClient, setHFClient] = useState(null);
  const [chatHistory, setChatHistory] = useState([]);
  const [chatSettings, setChatSettings] = useChatSettings();
  const [uiSettings, setUISettings] = useUISettings();

  const { sendMessage, isLoading, typingMessage, error } = useChatCompletion(
    hfClient,
    chatSettings,
    uiSettings,
    (newPair) => setChatHistory([newPair, ...chatHistory])
  );

  const handleMessageSend = async (message) => {
    sendMessage(message);
  };

  const handleHFClientReady = (client) => {
    setHFClient(client);
  };

  return (
    <div
      style={{
        padding: "20px",
        maxWidth: "600px",
        margin: "auto",
        display: "flex",
        flexDirection: "column",
        gap: "24px",
      }}
    >
      {/* Token input */}
      <div>
        <OAuthLogin onHFClientReady={handleHFClientReady} />
      </div>

      {/* Chat settings */}
      <div>
        <ChatSettings settings={chatSettings} setSettings={setChatSettings} />
      </div>

      {/* UI behavior settings */}
      <div>
        <UISettings settings={uiSettings} setSettings={setUISettings} />
      </div>

      {/* Input area */}
      <div>
        <MessageInput onSend={handleMessageSend} />
      </div>

      {/* Chat history */}
      <div>
        {isLoading && <LoadingIndicator type={uiSettings.loadingStyle} />}
        {typingMessage && <TypingMessage text={typingMessage} />}
        {error && <div style={{ color: "red" }}>{error.message}</div>}

        {chatHistory.map((pair, index) => (
          <MessagePair
            key={index}
            userMessage={pair.user}
            assistantMessage={pair.assistant}
          />
        ))}
      </div>
    </div>
  );
}
