import { useCallback, useEffect, useRef, useState } from 'react';
import { useSuperAdminAuth } from '../store/auth';

export interface DashboardMetrics {
  total_schools?: number;
  active_schools?: number;
  total_learners?: number;
  termly_revenue_usd?: number;
  active_licenses?: number;
  expired_licenses?: number;
  supabase_sync?: {
    configured?: boolean;
    synced_count?: number;
    local_only_count?: number;
    mismatched_count?: number;
    status_label?: string;
    [key: string]: any;
  };
  cloud_synced_licenses?: number;
  cloud_pending_licenses?: number;
  cloud_drift_licenses?: number;
  cloud_unconfigured?: boolean;
  [key: string]: unknown;
}

export interface UseDashboardDataOptions {
  onError?: (message: string) => void;
}

export interface UseDashboardData {
  metrics: DashboardMetrics | null;
  tenants: any[];
  instances: any[];
  loading: boolean;
  refetch: () => Promise<void>;
}

export function useDashboardData(api: any, options: UseDashboardDataOptions = {}): UseDashboardData {
  const { onError } = options;
  const onErrorRef = useRef(onError);

  useEffect(() => {
    onErrorRef.current = onError;
  }, [onError]);

  const token = useSuperAdminAuth((state) => state.token);
  const [metrics, setMetrics] = useState<DashboardMetrics | null>(null);
  const [tenants, setTenants] = useState<any[]>([]);
  const [instances, setInstances] = useState<any[]>([]);
  const [loading, setLoading] = useState(!!token);

  const refetch = useCallback(async () => {
    if (!useSuperAdminAuth.getState().token) {
      setLoading(false);
      return;
    }
    setLoading(true);
    try {
      const [mRes, tRes, iRes] = await Promise.all([
        api.get('/metrics').catch(() => ({ data: null })),
        api.get('/tenants').catch(() => ({ data: [] })),
        api.get('/instances').catch(() => ({ data: [] })),
      ]);
      if (mRes.data) setMetrics(mRes.data);
      if (tRes.data) setTenants(tRes.data);
      if (iRes.data) setInstances(iRes.data);
    } catch (err: any) {
      console.error('Failed to load SuperAdmin telemetry:', err);
      onErrorRef.current?.('Failed to connect to SuperAdmin backend server');
    } finally {
      setLoading(false);
    }
  }, [api]);

  useEffect(() => {
    if (!token) {
      setMetrics(null);
      setTenants([]);
      setInstances([]);
      setLoading(false);
      return;
    }
    refetch();
  }, [token, refetch]);

  return { metrics, tenants, instances, loading, refetch };
}
