'use client';

import { useState, useTransition, useCallback } from 'react';
import { getJiraAnalytics } from '@/actions/jira-analytics';
import { JiraAnalytics } from '@/lib/types';

export function useJiraAnalytics(initialAnalytics?: JiraAnalytics | null) {
  const [analytics, setAnalytics] = useState<JiraAnalytics | null>(
    initialAnalytics || null
  );
  const [error, setError] = useState<string | null>(null);
  const [isPending, startTransition] = useTransition();

  const loadAnalytics = useCallback((forceRefresh = false) => {
    startTransition(async () => {
      try {
        setError(null);

        const result = await getJiraAnalytics(forceRefresh);

        if (result.success && result.data) {
          setAnalytics(result.data);
        } else {
          setError(result.error || 'Erreur lors du chargement des analytics');
        }
      } catch (err) {
        const errorMessage =
          err instanceof Error
            ? err.message
            : 'Erreur lors du chargement des analytics';
        setError(errorMessage);
        console.error('Erreur analytics Jira:', err);
      }
    });
  }, []);

  const refreshAnalytics = useCallback(() => {
    loadAnalytics(true); // Force refresh quand on actualise manuellement
  }, [loadAnalytics]);

  return {
    analytics,
    isLoading: isPending,
    error,
    loadAnalytics,
    refreshAnalytics,
  };
}
