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); // To handle loading state
  const [apiResponse, setApiResponse] = useState(null); // Declare apiResponse in the state

  // Handle user message input
  const handleUserMessage = (e) => {
    setUserMessage(e.target.value);
  };

  // Save messages to local storage whenever they change
  useEffect(() => {
    localStorage.setItem("chatMessages", JSON.stringify(messages));
  }, [messages]);

  // Send message to API and handle response
  const handleSendMessage = async () => {
    if (userMessage.trim()) {
      // Add the user message to the chat
      setMessages((prevMessages) => [
        ...prevMessages,
        { text: userMessage, isUser: true },
      ]);
      setUserMessage("");
      setLoading(true); // Start loading animation

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

        const botResponse = response.data;

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

        // Store the full response in state to render references and additional data
        setApiResponse(botResponse);

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

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

  // Function to extract website name from a URL
  const getWebsiteName = (url) => {
    try {
      const parsedUrl = new URL(url);
      return parsedUrl.hostname.replace("www.", "");
    } catch (e) {
      return "Unknown Website";
    }
  };

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

  // Function to render dynamic content based on the format `**text**`
  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")} {/* Remove the ** around the text */}
          </h3>
        );
      }

      if (line.match(/^\d+\.\s/)) {
        const numberPart = line.split(" ")[0]; // Extract the number (1.)
        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>;
    });
  };

  // Render references with website name and favicon
  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(() => {
    // Scroll to the bottom when a new message is added
    const chatContainer = document.querySelector(".messages-container");
    chatContainer.scrollTop = chatContainer.scrollHeight;
  }, [messages]);

  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>

      {/* Circular Loading Spinner */}
      {loading && (
        <div className="flex justify-center mt-4">
          <div className="w-12 h-12 border-4 border-t-4 border-blue-500 rounded-full animate-spin"></div>
        </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} // Disable the input box while waiting for the API response
        />
        <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} // Disable the button while waiting for the API response
        >
          {loading ? (
            <div className="w-8 h-8 border-4 border-t-4 border-white rounded-full animate-spin"></div>
          ) : (
            "Send"
          )}
        </button>
      </div>
    </div>
  );
};

export default Chatbot;
 - i want different process bar when api fetch data