/**
 * useCommcoachDashboard Hook
 * 
 * Loads and manages dashboard data for the CommCoach feature.
 */

import { useState, useEffect, useCallback, useRef } from 'react';
import { useApiRequest } from './useApi';
import { useInstanceId } from './useCurrentInstance';
import { getDashboardApi, getProfileApi, type DashboardData, type CoachingUserProfile } from '../api/commcoachApi';

export interface CommcoachDashboardReturn {
  dashboard: DashboardData | null;
  profile: CoachingUserProfile | null;
  loading: boolean;
  error: string | null;
  refresh: () => Promise<void>;
}

export function useCommcoachDashboard(): CommcoachDashboardReturn {
  const { request } = useApiRequest();
  const instanceId = useInstanceId();

  const [dashboard, setDashboard] = useState<DashboardData | null>(null);
  const [profile, setProfile] = useState<CoachingUserProfile | null>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const isMountedRef = useRef(true);
  useEffect(() => { isMountedRef.current = true; return () => { isMountedRef.current = false; }; }, []);

  const refresh = useCallback(async () => {
    if (!instanceId) return;
    setLoading(true);
    setError(null);
    try {
      const [dashData, profileData] = await Promise.all([
        getDashboardApi(request, instanceId),
        getProfileApi(request, instanceId),
      ]);
      if (isMountedRef.current) {
        setDashboard(dashData);
        setProfile(profileData);
      }
    } catch (err: any) {
      if (isMountedRef.current) setError(err.message || 'Fehler beim Laden des Dashboards');
    } finally {
      if (isMountedRef.current) setLoading(false);
    }
  }, [request, instanceId]);

  useEffect(() => { if (instanceId) refresh(); }, [instanceId, refresh]);

  return { dashboard, profile, loading, error, refresh };
}
