"use client"

import axios from "axios";
import { useState } from "react";


export default function Home() {


  const [messages, setMessages] = useState([]);
  const [inputValue, setInputValue] = useState('');
  const [isLoading, setIsLoading] = useState(false);

  const handleInputChange = (e) => {

    setInputValue(e.target.value);
  };

  const handleSendMessage = async () => {
    if (inputValue.trim() !== '') {
      const data = {
        text: inputValue,
        sender: 'user',
      };

      setMessages(prevMessages => [...prevMessages, data]);
      setInputValue('');

      try {
        setIsLoading(true);
        await getServerResponse(inputValue)
        setIsLoading(false);
      } catch (error) {
        setIsLoading(false);
        console.log(error)
      }
    }
  };

  const getServerResponse = async (text) => {
    try {

      var bodyFormData = new FormData();
      bodyFormData.append('question', text);

      const response = await axios.post('http://127.0.0.1:5000/chat', bodyFormData);

      const newMessage = {
        text: response.data,
        sender: 'bot',
      };

      setMessages(prevMessages => [...prevMessages, newMessage]);
      setInputValue('');
      console.log(messages)
    } catch (error) {
      console.error('Error:', error);
    }
  }


  return (
    <main className="flex min-h-screen flex-col items-center  p-24">

      <h1 className='text-[50px]'>Aet-Mart Assistant</h1>



      <div className='h-full w-full'>
        <div id="messages" className="flex flex-col w-full h-96	 mb-4 space-y-4 p-3 overflow-y-auto scrollbar-thumb-blue scrollbar-thumb-rounded scrollbar-track-blue-lighter scrollbar-w-2 scrolling-touch  ">

          {messages.map((message, index) => {




            if (message.sender === 'bot') {

              const productIdRegex = /ProductID:\s*([A-Z0-9-]+)/i;
              const match = message.text.match(productIdRegex);
              var productId = null;
              if (match) {
                productId = match[1];
                console.log("ProductID:", productId);
              } else {
                console.log("No ProductID found.");
              }

              return (

                <div key={index} className="rounded-lg inline-block rounded-br-none bg-gray-400 text-white text-xl p-2">
                  {message.text}

                  {productId !== null && (
                    <div className="w-full items-center p-2">
                      <img className="h-[200px] " src={"https://demo.sirv.com/trainer-grey.jpg?text=" + productId + "&text.size=50%&text.color=000000&text.position.x=52&text.position.y=36&text.position.gravity=northwest"} />


                      <div className="p-2 flex flex-row w-full">
                      <button className="text-white bg-yellow-400 hover:bg-yellow-500 focus:outline-none focus:ring-4 focus:ring-yellow-300 font-medium rounded-full text-sm px-5 py-2.5 text-center mr-2 mb-2 dark:focus:ring-yellow-900"
                        onClick={() => {
                          window.open(`https://aet-mart.com/addToCart/${productId}`, '_blank');
                        }}>
                        Add to Cart
                      </button>

                      <button className="text-white bg-teal-400 hover:bg-yellow-500 focus:outline-none focus:ring-4 focus:ring-yellow-300 font-medium rounded-full text-sm px-5 py-2.5 text-center mr-2 mb-2 dark:focus:ring-yellow-900"
                        onClick={ getServerResponse('I need more details on Product ' + productId)}>
                        Details
                      </button>

                      </div>

                    </div>
                  )}


                </div>
              );
            } else {
              return (
                <div key={index} className="rounded-lg inline-block rounded-br-none bg-orange-400 text-white text-xl p-2">
                  {message.text}
                </div>
              );
            }
          })}

        </div>
      </div>



      <div className='block w-full'>
        <p className='p-4 text-lg'>Hi 👋🏻, How may I help you today?</p>
        <input disabled={isLoading} className="block w-full h-12 rounded-lg border-0 py-2 pl-7 pr-7 text-gray-900 ring-2 ring-inset ring-orange-300  placeholder:text-gray-400 text-lg sm:text-sm sm:leading-6 focus:outline-orange-400" placeholder="I want some ..." value={inputValue}
          onChange={handleInputChange} />

        <div className='block w-full mt-4 items-center'>
          <button disabled={isLoading}  type="submit" className="py-2.5 px-5 mr-2 mb-2 text-sm font-medium text-gray-900 focus:outline-none bg-white rounded-lg border border-gray-200 hover:bg-gray-100 hover:text-blue-700 focus:z-10 focus:ring-4 focus:ring-gray-200 dark:focus:ring-gray-700 dark:bg-gray-800 dark:text-gray-400 dark:border-gray-600 dark:hover:text-white dark:hover:bg-gray-700" onClick={handleSendMessage}>Submit</button>
        </div>

      </div>


    </main>
  )
}


fix errors  on onClick={ getServerResponse('I need more details on Product ' + productId)}>