"use client";

import { useState, useCallback, useEffect, useRef } from "react";
import {
  getSMTPStatus,
  getHealth,
  getStorageStats,
  getSystemStats,
  getMailTimeseries,
  type SMTPStatus,
  type StorageStats,
  type SystemStats,
  type TimeseriesPoint,
} from "@/lib/api";

export function useAdminDashboard(active: boolean) {
  const [smtpStatus, setSmtpStatus] = useState<SMTPStatus | null>(null);
  const [storageStats, setStorageStats] = useState<StorageStats | null>(null);
  const [systemStats, setSystemStats] = useState<SystemStats | null>(null);
  const [timeseries, setTimeseries] = useState<TimeseriesPoint[]>([]);
  const [apiOnline, setApiOnline] = useState<boolean | null>(null);
  const [dashLoading, setDashLoading] = useState(true);
  const [dashRefreshed, setDashRefreshed] = useState<Date | null>(null);
  const [countdown, setCountdown] = useState(30);

  const dashIntervalRef = useRef<ReturnType<typeof setInterval> | null>(null);

  const loadDashboard = useCallback(async () => {
    setDashLoading(true);
    try {
      const [smtp, health, storage, sysStats, ts] = await Promise.allSettled([
        getSMTPStatus(),
        getHealth(),
        getStorageStats(),
        getSystemStats(),
        getMailTimeseries(30),
      ]);
      setSmtpStatus(smtp.status === "fulfilled" ? smtp.value : null);
      setApiOnline(health.status === "fulfilled" && health.value.status === "ok");
      setStorageStats(storage.status === "fulfilled" ? storage.value : null);
      setSystemStats(sysStats.status === "fulfilled" ? sysStats.value : null);
      setTimeseries(ts.status === "fulfilled" ? ts.value.points : []);
      setDashRefreshed(new Date());
    } finally {
      setDashLoading(false);
    }
  }, []);

  useEffect(() => {
    if (!active) return;
    loadDashboard();

    setCountdown(30);
    dashIntervalRef.current = setInterval(() => {
      loadDashboard();
      setCountdown(30);
    }, 30_000);

    const ticker = setInterval(() => {
      setCountdown((c) => (c > 0 ? c - 1 : 0));
    }, 1_000);

    return () => {
      if (dashIntervalRef.current) clearInterval(dashIntervalRef.current);
      clearInterval(ticker);
    };
  }, [active, loadDashboard]);

  const refresh = useCallback(() => {
    loadDashboard();
    setCountdown(30);
  }, [loadDashboard]);

  return {
    smtpStatus,
    storageStats,
    systemStats,
    timeseries,
    apiOnline,
    dashLoading,
    dashRefreshed,
    countdown,
    loadDashboard,
    refresh,
  };
}
