import { useEffect, useRef, useState } from "react";
import dayjs from "dayjs";
import { useMsal } from '@azure/msal-react';

const TOKEN_EXPIRY_BUFFER_MINUTES = 5;
const COUNTDOWN_SECONDS = TOKEN_EXPIRY_BUFFER_MINUTES * 60;

export const useTokenExpiryMonitor = ({ onRenew, onExpire }) => {
  const { instance } = useMsal();
  const [showDialog, setShowDialog] = useState(false);
  const [countdown, setCountdown] = useState(COUNTDOWN_SECONDS);
  const countdownIntervalRef = useRef(null);
  const tokenCheckIntervalRef = useRef(null);

  // Countdown handler
  const startCountdown = () => {
    clearInterval(countdownIntervalRef.current);
    setCountdown(COUNTDOWN_SECONDS);
    countdownIntervalRef.current = setInterval(() => {
      setCountdown(prev => {
        if (prev <= 1) {
          clearInterval(countdownIntervalRef.current);
          setShowDialog(false);
          onExpire?.(); // Auto logout
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
  };

  const stopCountdown = () => {
    clearInterval(countdownIntervalRef.current);
    setCountdown(COUNTDOWN_SECONDS);
  };

  // Token check handler
  useEffect(() => {
    const checkToken = () => {
      const account = instance.getActiveAccount();
      if (!account) return;

      instance.acquireTokenSilent({
        account,
        scopes: ["user.read"],
      }).then(response => {
        const expiry = dayjs.unix(response.expiresOn.getTime() / 1000);
        const now = dayjs();
        if (expiry.diff(now, "minute") <= TOKEN_EXPIRY_BUFFER_MINUTES) {
          setShowDialog(true);
          startCountdown();
        }
      }).catch(error => {
        console.error("Token check failed:", error);
        onExpire?.(); // Force logout
      });
    };

    tokenCheckIntervalRef.current = setInterval(checkToken, 60 * 1000); // every minute
    checkToken(); // run on mount

    return () => {
      clearInterval(tokenCheckIntervalRef.current);
      stopCountdown();
    };
  }, []);

  const handleRenew = () => {
    const account = instance.getActiveAccount();
    instance.acquireTokenSilent({
      account,
      scopes: ["user.read"],
      forceRefresh: true,
    }).then(() => {
      setShowDialog(false);
      stopCountdown();
      onRenew?.();
    }).catch(() => {
      onExpire?.();
    });
  };

  return {
    showDialog,
    countdown,
    handleRenew,
    handleExpire: onExpire,
    setDialog: setShowDialog,
  };
};
