import { useState, useEffect } from 'react';
import axios from 'axios';
import { DateRange } from 'react-day-picker';
import { formatDate } from 'date-fns';
import { apiConfig } from '@/config/api.config';

const API_URL = apiConfig.service_dashboard;

interface UseFetchChartDataResult {
  chartData: any[];
  isChartLoading: boolean;
  chartError: any;
}

const useFetchChartData = (
  start_date: string,
  end_date: string,
  count: string
): UseFetchChartDataResult => {
  const [chartData, setChartData] = useState<any[]>([]);
  const [isChartLoading, setIsChartLoading] = useState<boolean>(false);
  const [chartError, setChartError] = useState<any>(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        setIsChartLoading(true);
        const response = await axios.get(`${API_URL}/dashboard/chart`, {
          params: {
            start_date: start_date,
            end_date: end_date,
            aggregate: count
          }
        });
        setChartData(response.data.data);
      } catch (err) {
        setChartError(err);
      } finally {
        setIsChartLoading(false);
      }
    };

    fetchData();
  }, [start_date, end_date, count]); // Dependensi pada from dan to

  return { chartData, isChartLoading, chartError };
};

export { useFetchChartData };
