import { useState, useEffect, useTransition, useCallback } from 'react';
import { getWeeklyMetrics, getVelocityTrends } from '@/actions/metrics';
import {
  WeeklyMetricsOverview,
  VelocityTrend,
} from '@/services/analytics/metrics';

// Export des types pour les composants
export type WeeklyMetrics = WeeklyMetricsOverview;
export type { VelocityTrend };

export function useWeeklyMetrics(date?: Date) {
  const [metrics, setMetrics] = useState<WeeklyMetricsOverview | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [isPending, startTransition] = useTransition();

  const fetchMetrics = useCallback(() => {
    startTransition(async () => {
      setError(null);
      const result = await getWeeklyMetrics(date);

      if (result.success && result.data) {
        setMetrics(result.data);
      } else {
        setError(result.error || 'Failed to fetch metrics');
      }
    });
  }, [date, startTransition]);

  useEffect(() => {
    fetchMetrics();
  }, [date, fetchMetrics]);

  return {
    metrics,
    loading: isPending,
    error,
    refetch: fetchMetrics,
  };
}

export function useVelocityTrends(weeksBack: number = 4) {
  const [trends, setTrends] = useState<VelocityTrend[]>([]);
  const [error, setError] = useState<string | null>(null);
  const [isPending, startTransition] = useTransition();

  const fetchTrends = useCallback(() => {
    startTransition(async () => {
      setError(null);
      const result = await getVelocityTrends(weeksBack);

      if (result.success && result.data) {
        setTrends(result.data);
      } else {
        setError(result.error || 'Failed to fetch velocity trends');
      }
    });
  }, [weeksBack, startTransition]);

  useEffect(() => {
    fetchTrends();
  }, [weeksBack, fetchTrends]);

  return {
    trends,
    loading: isPending,
    error,
    refetch: fetchTrends,
  };
}
