import React, { useState, useEffect } from 'react';
import { useAuthUser } from "react-auth-kit";
import axios from "axios";
import { getItemsByOwner } from "../UniversalCrud/UniversalCrudHelpers";
import Spinner2 from "../../../components/Loaders/Spinner2";
import { LeumasBaseStyle } from "../../../styles/baseStyles";
import { runEndpoint } from './Helpers/runEndpoint';

const SingleEndpointBuilder = ({ onResult , hideResult , hideButton , block}) => {
    const auth = useAuthUser();
    const [endpoint, setEndpoint] = useState(block.data.endpoint || {
        method: block.data.method || 'POST',
        endpoint: block.data.endpoint || 'https://api.openai.com/v1/chat/completions',
        body: JSON.stringify({
          model: block.data.body.model || "gpt-3.5-turbo",
          messages: [
            { role: "user", content: "Hello, who are you?" },
            { role: "assistant", content: "I am an AI created by OpenAI." }
          ]
        }, null, 2), // null, 2 for pretty JSON format in textarea
        headers: block.data.headers || JSON.stringify({
          'Content-Type': 'application/json',
          'Authorization': `Bearer YOUR_OPENAI_API_KEY` // Replace with actual API key
        }, null, 2),
        params: block.data.params || '{}',
      });
    const [isLoading, setIsLoading] = useState(false);
    const [result, setResult] = useState(null);

    const handleChange = (field, value) => {
        setEndpoint(prev => ({
            ...prev,
            [field]: value
        }));
    };

    const handleRunEndpoint = () => {
        setIsLoading(true);
        runEndpoint(
            `${import.meta.env.VITE_REACT_APP_LEUMAS_API_ENDPOINT}/wildcards/bulk-request`, 
            endpoint, 
            (data) => {
                if (Array.isArray(data) && data.length > 0) {
                    const result = data[0];
                    setResult(result);
                    onResult(result); // Calling the callback with the result
                } else {
                    console.log("Unexpected server response format:", data);
                }
                setIsLoading(false);
            }, 
            (error) => {
                console.error(error);
                setIsLoading(false);
            }
        );
    };


    
    // You can include additional functionality like fetching saved endpoints if required.

    const inputStyle = "border border-gray-300 rounded-lg px-3 py-2 w-full focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition bg-transparent";

    return (
        <div className="flex flex-col space-y-4 max-w-[400px]">
            <div className="flex space-x-2">
                <select
                    value={endpoint.method}
                    onChange={(e) => handleChange('method', e.target.value)}
                    className={inputStyle}
                >
                    <option value="GET">GET</option>
                    <option value="POST">POST</option>
                    <option value="PUT">PUT</option>
                    <option value="DELETE">DELETE</option>
                </select>
                <input
                    type="text"
                    value={endpoint.endpoint}
                    onChange={(e) => handleChange('endpoint', e.target.value)}
                    className={inputStyle}
                    placeholder="Enter endpoint URL"
                />
            </div>
            <label>Body (JSON)</label>
            <textarea
                value={endpoint.body}
                onChange={(e) => handleChange('body', e.target.value)}
                className={inputStyle}
                placeholder="Body (JSON)"
                rows="3"
            />
            <label>Headers (JSON)</label>
            <textarea
                value={endpoint.headers}
                onChange={(e) => handleChange('headers', e.target.value)}
                className={inputStyle}
                placeholder="Headers (JSON)"
                rows="2"
            />
            <label>Params (JSON)</label>
            <textarea
                value={endpoint.params}
                onChange={(e) => handleChange('params', e.target.value)}
                className={inputStyle}
                placeholder="Params (JSON)"
                rows="2"
            />
    {!hideButton && (
        <button onClick={handleRunEndpoint} className={LeumasBaseStyle}>
                Run Endpoint
        </button>
    )}
            

            {isLoading && <Spinner2 loading={isLoading} />}

            {result && hideResult && (
                <div className="w-full border rounded-lg p-4 overflow-auto ">
                    <p>Result:</p>
                    <pre className='border-blue-300 rounded-lg text-[12px]'>{JSON.stringify(result, null, 2)}</pre>
                </div>
            )}
        </div>
    );
};

export default SingleEndpointBuilder;
