import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { useParams } from 'react-router-dom';

const API_BASE_URL = import.meta.env.VITE_API_BASE_URL;

const QueryAssistantPage = () => {
  const { assistantId } = useParams(); // The assistant's ID from the URL
  const [assistantName, setAssistantName] = useState('');
  const [query, setQuery] = useState('');
  const [conversation, setConversation] = useState('');
  const [loading, setLoading] = useState(false);

  // Fetch the assistant's details when the component mounts
  useEffect(() => {
    const fetchAssistantDetails = async () => {
      try {
        const res = await axios.get(`${API_BASE_URL}/api/assistants/${assistantId}`, {
          headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
        });
        setAssistantName(res.data.assistant_name);
      } catch (error) {
        console.error('Error fetching assistant details:', error);
      }
    };

    fetchAssistantDetails();
  }, [assistantId]);

  const handleSubmit = async (e) => {
    setConversation('');
    e.preventDefault();
    setLoading(true);
    try {
      const res = await axios.post(
        `${API_BASE_URL}/api/ollama/query`,
        {
          prompt: query,
          assistantId: assistantId // assistantId comes from useParams()
        },
        { headers: { Authorization: `Bearer ${localStorage.getItem('token')}` } }
      );

      console.log('Backend response:', res.data);

      // Extract just the assistant's text message from the JSON response
      const assistantResponse =
        res.data.response && res.data.response.message && res.data.response.message.content
          ? res.data.response.message.content
          : JSON.stringify(res.data.response);

      // Append the new conversation to the existing text
      setConversation((prev) =>
        prev + `User: ${query}\n\n ${assistantResponse}\n`
      );
      setQuery('');
    } catch (error) {
      console.error('Error querying assistant:', error);
      setConversation((prev) =>
        prev + `\nUser: ${query}\n Error obtaining response\n`
      );
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="container mt-4">
      <h2>
        Chat with your {assistantName ? assistantName : `#${assistantId}`} Assistant
      </h2>
      <form onSubmit={handleSubmit}>
        <div className="mb-3">
          <label htmlFor="assistantQuery" className="form-label">
            Ask me anything:
          </label>
          <input
            type="text"
            className="form-control"
            id="assistantQuery"
            value={query}
            onChange={(e) => setQuery(e.target.value)}
            required
          />
        </div>
        <button type="submit" className="btn btn-primary" disabled={loading}>
          {loading ? 'Thinking...' : 'Send'}
        </button>
      </form>
      <div className="mt-4">
        <label className="form-label">Conversation:</label>
        <textarea
          className="form-control"
          rows="10"
          readOnly
          value={conversation}
        ></textarea>
      </div>
    </div>
  );
};

export default QueryAssistantPage;

