import React, { useState, useEffect } from "react";
import axios from "axios";

const Chatbot = () => {
  const [messages, setMessages] = useState(() => {
    const savedMessages = localStorage.getItem("chatMessages");
    return savedMessages ? JSON.parse(savedMessages) : [];
  });
  const [userMessage, setUserMessage] = useState("");
  const [loading, setLoading] = useState(false);
  const [loadingProgress, setLoadingProgress] = useState(0);
  const [apiResponse, setApiResponse] = useState(null);

  const handleUserMessage = (e) => {
    setUserMessage(e.target.value);
  };

  useEffect(() => {
    localStorage.setItem("chatMessages", JSON.stringify(messages));
  }, [messages]);

  const handleSendMessage = async () => {
    if (userMessage.trim()) {
      setMessages((prevMessages) => [
        ...prevMessages,
        { text: userMessage, isUser: true },
      ]);
      setUserMessage("");
      setLoading(true);

      try {
        const response = await axios.post("http://127.0.0.1:5000/analyze_query", {
          query: userMessage,
        });

        const botResponse = response.data;

        setMessages((prevMessages) => [
          ...prevMessages,
          { text: `Here's the information about: ${userMessage}`, isUser: false },
          { text: botResponse.summary, isUser: false },
        ]);

        setApiResponse(botResponse);
        setLoading(false);
      } catch (error) {
        console.error("Error sending message:", error);
        setMessages((prevMessages) => [
          ...prevMessages,
          { text: "Sorry, something went wrong. Please try again later.", isUser: false },
        ]);
        setLoading(false);
      }
    }
  };

  const handleKeyDown = (e) => {
    if (e.key === "Enter") {
      handleSendMessage();
    }
  };

  const getWebsiteName = (url) => {
    try {
      const parsedUrl = new URL(url);
      return parsedUrl.hostname.replace("www.", "");
    } catch (e) {
      return "Unknown Website";
    }
  };

  const getFaviconUrl = (url) => {
    try {
      const parsedUrl = new URL(url);
      return `${parsedUrl.protocol}//${parsedUrl.hostname}/favicon.ico`;
    } catch (e) {
      return "";
    }
  };

  const renderContent = (content) => {
    if (!content) return null;

    const lines = content.split("\n");

    return lines.map((line, index) => {
      if (line.match(/^\*\*[^*]+\*\*$/)) {
        return (
          <h3 key={index} className="text-xl font-semibold mb-4 text-white">
            {line.replace(/\*\*(.*)\*\*/g, "$1")}
          </h3>
        );
      }

      if (line.match(/^\d+\.\s/)) {
        const numberPart = line.split(" ")[0];
        const restOfLine = line.slice(line.indexOf(" ") + 1);
        const boldTextMatch = restOfLine.match(/\*\*(.*?)\*\*/);

        return (
          <div key={index} className="mb-4">
            <p className="text-gray-300">
              {numberPart} <strong>{boldTextMatch ? boldTextMatch[1] : restOfLine}</strong>
            </p>
            {restOfLine.includes(":") && (
              <p className="text-gray-300">{restOfLine.slice(restOfLine.indexOf(":") + 1).trim()}</p>
            )}
          </div>
        );
      }

      if (line.match(/^\d+\.\s.*-\s/)) {
        return <p key={index} className="text-gray-300 mb-4">{line}</p>;
      }

      return <p key={index} className="text-gray-300 mb-4">{line}</p>;
    });
  };

  const renderReferences = (references) => {
    if (!references || references.length === 0) return null;
    return (
      <div className="mt-6">
        <h3 className="text-xl font-semibold mb-4 text-white">References</h3>
        <div className="flex flex-wrap gap-4">
          {references.map((url, index) => {
            const websiteName = getWebsiteName(url);
            const faviconUrl = getFaviconUrl(url);
            return (
              <a
                key={index}
                href={url}
                target="_blank"
                rel="noopener noreferrer"
                className="flex items-center text-blue-400 bg-gray-700 p-3 rounded-lg hover:bg-blue-500 transition duration-300 transform hover:scale-105"
              >
                {faviconUrl && <img src={faviconUrl} alt={`${websiteName} favicon`} className="w-6 h-6 mr-3" />}
                {websiteName}
              </a>
            );
          })}
        </div>
      </div>
    );
  };

  useEffect(() => {
    const chatContainer = document.querySelector(".messages-container");
    chatContainer.scrollTop = chatContainer.scrollHeight;
  }, [messages]);

  useEffect(() => {
    let timeout;
    if (loading) {
      const simulateLoading = () => {
        setLoadingProgress((oldProgress) => {
          const incrementedProgress = Math.min(oldProgress + 5, 100);
          timeout = setTimeout(simulateLoading, 100);
          return incrementedProgress;
        });
      };
      simulateLoading();
    } else {
      setLoadingProgress(0);
    }
    return () => clearTimeout(timeout);
  }, [loading]);

  return (
    <div className="w-full h-screen flex flex-col bg-black text-white">
      {/* Header */}
      <div className="bg-gray-800 p-5 text-white font-bold text-2xl shadow-md">
        Chatbot
      </div>

      {/* Loading Progress Bar */}
      {loading && (
        <div className="relative w-full h-2 bg-gray-300">
          <div
            className="absolute h-full bg-blue-500 transition-all duration-100"
            style={{ width: `${loadingProgress}%` }}
          />
        </div>
      )}

      {/* Chat Messages */}
      <div className="messages-container flex-grow p-5 overflow-y-auto space-y-6 scroll-smooth">
        {messages.map((message, index) => (
          <div key={index} className={`flex ${message.isUser ? "justify-end" : "justify-start"}`}>
            <div
              className={`${
                message.isUser ? "bg-blue-500" : "bg-gray-700"
              } p-4 max-w-[80%] rounded-xl text-white mb-4`}
            >
              {message.text}
            </div>
          </div>
        ))}

        {/* Render API Response */}
        {apiResponse && (
          <div className="bg-gray-900 p-5 text-white mt-4 mx-10 rounded-lg shadow-lg max-w-full">
            <h2 className="text-2xl font-semibold mb-4 text-white">Analysis</h2>

            {/* Render the dynamic content */}
            {renderContent(apiResponse.summary)}

            {/* Render references */}
            {renderReferences(apiResponse.references)}
          </div>
        )}
      </div>

      {/* Input Section */}
      <div className="flex items-center p-4 bg-gray-800 border-t border-gray-600">
        <input
          type="text"
          value={userMessage}
          onChange={handleUserMessage}
          onKeyDown={handleKeyDown}
          className="flex-grow p-4 bg-gray-700 text-white rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 placeholder-gray-400"
          placeholder="Ask me anything..."
          disabled={loading}
        />
        <button
          onClick={handleSendMessage}
          className="ml-4 p-6 bg-blue-500 text-white rounded-full hover:bg-blue-400 transition duration-300 transform hover:scale-110"
          disabled={loading}
        >
          Send
        </button>
      </div>
    </div>
  );
};

export default Chatbot;- update process bar to cricle in this code