"use client";
import { Checkbox, Stack } from "@mantine/core";
import { useState, useEffect, useRef, KeyboardEvent, ChangeEvent } from "react";

// TypeScript interfaces
interface Message {
  role: "user" | "assistant" | "system";
  content: string;
  displayLines?: string[];
}

interface ChatResponse {
  message: {
    role: string;
    content: string;
  };
  done: boolean;
}

interface RetrieveData {
  article_number: string;
  article_title: string;
  text: string;
}

// interface OllamaModel {
//   name: string;
//   modified_at: string;
//   size: number;
//   digest: string;
//   details: object;
// }

// interface ModelsResponse {
//   models: OllamaModel[];
// }

export default function OllamaChat() {
  const [messages, setMessages] = useState<Message[]>([
    {
      role: "system",
      content:
        "You are a helpful and professional Vietnamese Law assistant chatbot. A user will ask a question about the portfolio owner, and provide context about the owner's background, skills, projects, and achievements as part of their prompt. Please answer the following question in the same language it was asked.",
    },
  ]);

  const [input, setInput] = useState<string>("");
  const [isGenerating, setIsGenerating] = useState<boolean>(false);
  // const [model, setModel] = useState<string>("q3q4");
  const model = "q14b";
  const [isReasoning, setIsReasoning] = useState<boolean>(false);
  const [isWeb, setIsWeb] = useState<boolean>(false);

  const messagesEndRef = useRef<HTMLDivElement>(null);
  const abortControllerRef = useRef<AbortController | null>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  const scrollToBottom = (): void => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  const handleSubmit = async (): Promise<void> => {
    if (!input.trim() || isGenerating) return;
    const inp = input;
    setInput("");

    const userMessage: Message = { role: "user", content: inp };
    setMessages((msgs) => [...msgs, userMessage]);

    // Create a new AbortController for this request
    abortControllerRef.current = new AbortController();

    try {
      setIsGenerating(true);
      await generateResponse(inp);
    } catch (error) {
      if (error instanceof Error && error.name !== "AbortError") {
        console.error("Error generating response:", error);
        setMessages((msgs) => [
          ...msgs,
          {
            role: "assistant",
            content:
              "Sorry, there was an error connecting to Ollama. Please check if the service is running on localhost:11434.",
          },
        ]);
      }
    } finally {
      setIsGenerating(false);
    }
  };

  const handleKeyPress = (e: KeyboardEvent<HTMLInputElement>): void => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      handleSubmit();
    }
  };

  const generateResponse = async (prompt: string): Promise<void> => {
    try {
      // Format all previous messages for the chat API
      const original_prompt = prompt;
      if (isReasoning === false) {
        prompt += "/no_think";
      }

      const retrieve_response = await fetch(
        "http://103.98.161.94:3030/search",
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            query: original_prompt,
          }),
          signal: abortControllerRef.current?.signal,
        }
      );

      if (!retrieve_response.ok) {
        throw new Error(`HTTP error! Status: ${retrieve_response.status}`);
      }

      const retrieveData: RetrieveData[] = await retrieve_response.json();
      let retrievePrompt =
        "Dựa vào những thông tin sau đây, hãy trả lời câu hỏi của người dùng. Nếu thông tin được cho không thể cung cấp thông tin cho câu trả lời của người dùng, hãy hỏi thêm người dùng một số thông tin để hiểu thêm về câu hỏi trước\nSau đây là thông tin được cung cấp:\n\n";
      retrieveData.forEach((data) => {
        retrievePrompt += `Điều ${data["article_number"]}. ${data["article_title"]}\n${data["text"]}\n\n`;
      });

      retrievePrompt += "Sau đây là câu hỏi của người dùng: \n";

      const chatMessages = [
        ...messages.map((msg) => ({
          role: msg.role,
          content: msg.content,
        })),
        {
          role: "user",
          content: retrievePrompt + prompt,
        },
      ];

      const response = await fetch("http://103.98.161.94:11434/api/chat", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          model: model,
          messages: chatMessages,
          stream: true,
          keep_alive: "1440m",
        }),
        signal: abortControllerRef.current?.signal,
      });

      if (!response.body) {
        throw new Error("Response body is null");
      }

      const reader = response.body.getReader();
      const decoder = new TextDecoder("utf-8");

      let buffer = "";
      const assistantMessage: Message = { role: "assistant", content: "" };
      let contentLines: string[] = [];

      setMessages((msgs) => [...msgs, assistantMessage]);

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        buffer += decoder.decode(value, { stream: true });

        // Process complete JSON objects in the buffer
        while (buffer.includes("\n")) {
          const lineEnd = buffer.indexOf("\n");
          const line = buffer.slice(0, lineEnd);
          buffer = buffer.slice(lineEnd + 1);

          if (line.trim() === "") continue;

          try {
            const data = JSON.parse(line) as ChatResponse;
            if (data.message && data.message.content) {
              const newContent = data.message.content;
              if (newContent.indexOf("think") != -1) {
                assistantMessage.content += "";
              } else {
                assistantMessage.content += newContent;
              }

              // Update lines array when we get a new line
              if (newContent.includes("\n")) {
                const parts = assistantMessage.content.split("\n");
                // The last part is the beginning of a new line or empty
                contentLines = parts.slice(0, -1);
                const lastPart = parts[parts.length - 1];

                setMessages((msgs) => {
                  const newMsgs = [...msgs.slice(0, -1)];
                  return [
                    ...newMsgs,
                    {
                      role: "assistant",
                      content: assistantMessage.content,
                      displayLines: [...contentLines, lastPart],
                    },
                  ];
                });
              } else {
                setMessages((msgs) => {
                  const newMsgs = [...msgs.slice(0, -1)];
                  if (contentLines.length > 0) {
                    return [
                      ...newMsgs,
                      {
                        role: "assistant",
                        content: assistantMessage.content,
                        displayLines: [
                          ...contentLines,
                          assistantMessage.content.split("\n").pop() || "",
                        ],
                      },
                    ];
                  } else {
                    return [
                      ...newMsgs,
                      {
                        role: "assistant",
                        content: assistantMessage.content,
                      },
                    ];
                  }
                });
              }
            }
          } catch (e) {
            console.error("Error parsing JSON:", e);
          }
        }
      }
    } catch (error) {
      throw error;
    }
  };

  const stopGeneration = (): void => {
    if (abortControllerRef.current) {
      abortControllerRef.current.abort();
      setIsGenerating(false);
    }
  };

  // Format the message content for display
  const formatMessageContent = (message: Message) => {
    if (message.displayLines) {
      return message.displayLines.map((line, idx) => (
        <p key={idx} className="mb-2">
          {line || " "}
        </p>
      ));
    } else {
      return message.content.split("\n").map((line, idx) => (
        <p key={idx} className="mb-2">
          {line || " "}
        </p>
      ));
    }
  };

  return (
    <div className="flex flex-col h-screen bg-gray-100">
      <header className="bg-black text-white p-4 shadow">
        <div className="container mx-auto flex justify-between items-center">
          <h1 className="text-2xl font-bold">LawBot</h1>
        </div>
      </header>

      <div className="flex-1 overflow-auto p-4">
        <div className="container mx-auto max-w-4xl">
          {messages.length === 1 ? (
            <div className="text-center text-gray-500 mt-10">
              <p className="text-xl mb-2">Welcome to LawBot Chat!</p>
              <p>Start a conversation with our latest model.</p>
              <p>
                I am sorry, my Google Search API is under maintainance, this
                feature will be back soon
              </p>
            </div>
          ) : (
            messages.map((message, index) => {
              if (message.role == "system") {
                return <div key={index}></div>;
              } else {
                return (
                  <div
                    key={index}
                    className={`mb-4 p-4 rounded-lg ${
                      message.role === "user"
                        ? "bg-blue-100 ml-12"
                        : "bg-white mr-12 shadow"
                    }`}
                  >
                    <div className="font-bold mb-1">
                      {message.role === "user" ? "You" : "Assistant"}
                    </div>
                    <div className="text-gray-800">
                      {formatMessageContent(message)}
                    </div>
                  </div>
                );
              }
            })
          )}
          <div ref={messagesEndRef} />
        </div>
      </div>

      <div className="border-t border-gray-300 p-4 bg-white">
        <div className="container mx-auto max-w-4xl">
          <div className="flex gap-2">
            <Stack className="px-4 py-2">
              <Checkbox
                checked={isReasoning}
                onChange={(event) =>
                  setIsReasoning(event.currentTarget.checked)
                }
                label="Reasoning"
              />
              <Checkbox
                checked={isWeb}
                onChange={(event) => setIsWeb(event.currentTarget.checked)}
                label="Search Web"
                disabled
              />
            </Stack>
            <input
              type="text"
              value={input}
              onChange={(e: ChangeEvent<HTMLInputElement>) =>
                setInput(e.target.value)
              }
              onKeyPress={handleKeyPress}
              placeholder="Type your message..."
              className="flex-1 p-2 border border-gray-300 rounded"
              disabled={isGenerating}
              ref={inputRef}
            />
            {isGenerating ? (
              <button
                type="button"
                onClick={stopGeneration}
                className="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600"
              >
                Stop
              </button>
            ) : (
              <button
                type="button"
                onClick={handleSubmit}
                className="px-4 py-2 bg-black text-white rounded hover:bg-gray-700"
              >
                Send
              </button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}
