import { useState, useEffect, useCallback } from "react";

const API_BASE = "/api/daily-analysis";

export function useDailyAnalysis(date = null, limit = 30) {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const fetchData = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);

      let url = API_BASE;
      if (date) {
        url = `${API_BASE}/${date}`;
      } else {
        url = `${API_BASE}?limit=${limit}`;
      }

      const response = await fetch(url);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const result = await response.json();
      if (result.success) {
        // Handle single date vs array
        const analysisData = date ? [result.data] : result.data || [];
        setData(analysisData);
      } else {
        throw new Error(result.error || "Failed to fetch data");
      }
    } catch (err) {
      setError(err.message);
      console.error("Error fetching daily analysis:", err);
    } finally {
      setLoading(false);
    }
  }, [date, limit]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  return {
    data,
    loading,
    error,
    refetch: fetchData,
  };
}

