'use client';

import { useEffect, useId, useState } from 'react';
import { createPortal } from 'react-dom';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { LogIn, ShieldAlert } from 'lucide-react';
import { Button } from '@/components/ui/button';

interface SessionExpiredModalProps {
  open: boolean;
  onDismiss: () => void;
}

export function SessionExpiredModal({ open, onDismiss }: SessionExpiredModalProps) {
  const pathname = usePathname();
  const [mounted, setMounted] = useState(false);
  const titleId = useId();

  const loginHref = `/login?redirect=${encodeURIComponent(pathname || '/')}`;

  useEffect(() => {
    setMounted(true);
  }, []);

  useEffect(() => {
    if (!open) {
      document.body.style.overflow = '';
      document.body.classList.remove('modal-open');
      return;
    }
    document.body.style.overflow = 'hidden';
    document.body.classList.add('modal-open');
    return () => {
      document.body.style.overflow = '';
      document.body.classList.remove('modal-open');
    };
  }, [open]);

  if (!open || !mounted) return null;

  return createPortal(
    <div
      className="fixed inset-0 z-[200] flex items-center justify-center bg-slate-900/60 p-4 backdrop-blur-sm"
      role="dialog"
      aria-modal="true"
      aria-labelledby={titleId}
    >
      <div className="w-full max-w-md rounded-2xl border border-slate-200 bg-white p-6 shadow-xl">
        <div className="flex flex-col items-center text-center">
          <div className="mb-4 flex h-14 w-14 items-center justify-center rounded-2xl bg-amber-100 text-amber-700">
            <ShieldAlert className="h-7 w-7" />
          </div>
          <h2 id={titleId} className="text-xl font-bold text-slate-900">
            Session ended
          </h2>
          <p className="mt-2 text-sm leading-relaxed text-muted">
            Your session has expired or is no longer valid. Please sign in again to continue using
            your portal.
          </p>
          <Link href={loginHref} className="mt-6 w-full" onClick={onDismiss}>
            <Button className="w-full gap-2">
              <LogIn className="h-4 w-4" />
              Go to login
            </Button>
          </Link>
        </div>
      </div>
    </div>,
    document.body
  );
}
