import { useEffect, useState, useCallback, useRef } from 'react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { tokenManager } from '@/lib/api';

const AUTO_REDIRECT_SECONDS = 5;

export default function SessionTimeoutModal() {
  const [open, setOpen] = useState(false);
  const [secondsLeft, setSecondsLeft] = useState(AUTO_REDIRECT_SECONDS);
  const timerRef = useRef<ReturnType<typeof setInterval>>();
  const wasOpenRef = useRef(false);

  const redirectToLogin = useCallback(() => {
    tokenManager.clearToken();
    window.location.href = '/login';
  }, []);

  useEffect(() => {
    const onSessionExpired = () => {
      setOpen(true);
      // Only reset the countdown when the modal transitions from closed → open
      if (!wasOpenRef.current) {
        setSecondsLeft(AUTO_REDIRECT_SECONDS);
      }
      wasOpenRef.current = true;
    };
    window.addEventListener('session:expired', onSessionExpired);
    return () => window.removeEventListener('session:expired', onSessionExpired);
  }, []);

  useEffect(() => {
    if (open) {
      timerRef.current = setInterval(() => {
        setSecondsLeft((prev) => {
          if (prev <= 1) {
            clearInterval(timerRef.current);
            redirectToLogin();
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    }
    return () => clearInterval(timerRef.current);
  }, [open, redirectToLogin]);

  const handleOpenChange = useCallback((isOpen: boolean) => {
    if (!isOpen) {
      clearInterval(timerRef.current);
      redirectToLogin();
    }
  }, [redirectToLogin]);

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogContent
        onPointerDownOutside={(e) => e.preventDefault()}
        onEscapeKeyDown={(e) => e.preventDefault()}
      >
        <DialogHeader>
          <DialogTitle>Session Expired</DialogTitle>
          <DialogDescription>
            Your session has timed out. Please sign in again to continue.
          </DialogDescription>
        </DialogHeader>
        <div className="flex items-center justify-between">
          <p className="text-sm text-muted-foreground">
            Redirecting in {secondsLeft}s...
          </p>
          <Button onClick={redirectToLogin}>
            Sign In
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
}
