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

export const useApiRequest = (addToHistory) => {
  const [response, setResponse] = useState(null);
  const [responseHeaders, setResponseHeaders] = useState(null);
  const [responseSize, setResponseSize] = useState(0);
  const [responseTime, setResponseTime] = useState(0);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  const executeRequest = async (requestUrl) => {
    if (!requestUrl) return;

    setLoading(true);
    setError(null);
    setResponse(null);
    setResponseHeaders(null);
    setResponseSize(0);
    setResponseTime(0);

    try {
      const startTime = performance.now();

      // Use default headers - browser will automatically include cookies for authentication
      const headers = {
        'Accept': 'application/vnd.api+json'
      };

      const response = await axios.get(requestUrl, { headers });

      const endTime = performance.now();
      setResponseTime(endTime - startTime);

      if (response.data) {
        setResponse(response.data);

        try {
          // Calculate response size
          const jsonSize = JSON.stringify(response.data).length;
          setResponseSize(jsonSize);
        } catch (error) {
          console.error('Error calculating response size:', error);
          setResponseSize(0);
        }

        // Add to request history
        if (addToHistory) {
          addToHistory(requestUrl, response.data);
        }
      } else {
        setResponse({});
      }

      if (response.headers) {
        setResponseHeaders(response.headers);
      }

    } catch (err) {
      console.error('Error executing request:', err);
      setError(`Error executing request: ${err.message}`);

      if (err.response) {
        if (err.response.data) {
          setResponse(err.response.data);
        }

        if (err.response.headers) {
          setResponseHeaders(err.response.headers);
        }
      } else {
        // If no response object at all, provide an empty object
        setResponse({
          error: {
            message: err.message,
            name: err.name
          }
        });
      }
    } finally {
      setLoading(false);
    }
  };

  return {
    response,
    responseHeaders,
    responseSize,
    responseTime,
    loading,
    error,
    executeRequest,
    setError
  };
};
