import React, { createContext, useContext, useState } from 'react';
import axios from 'axios';

const DataContext = createContext();

export function useReportData() {
  const context = useContext(DataContext);
  if (!context) {
    throw new Error('useReportData must be used within DataProvider');
  }
  return context;
}

export function DataProvider({ children }) {
  const [reportData, setReportData] = useState(null);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);

  const fetchData = async (apiEndpoint) => {
    if (!apiEndpoint || apiEndpoint.trim() === '') {
      setError('API endpoint URL is required');
      return;
    }

    setIsLoading(true);
    setError(null);

    try {
      const response = await axios.get(apiEndpoint);
      setReportData(response.data);
      setError(null);
    } catch (err) {
      console.error('Error fetching report data:', err);
      setError(err.response?.data?.message || err.message || 'Failed to fetch data');
      setReportData(null);
    } finally {
      setIsLoading(false);
    }
  };

  const setData = (data) => {
    setReportData(data);
    setError(null);
  };

  const clearData = () => {
    setReportData(null);
    setError(null);
    setIsLoading(false);
  };

  const value = {
    reportData,
    isLoading,
    error,
    fetchData,
    setData,
    clearData
  };

  return (
    <DataContext.Provider value={value}>
      {children}
    </DataContext.Provider>
  );
}

export default DataContext;
