import React from 'react'
import { createRoot, Root } from 'react-dom/client'
import SessionExpiredModal from '../components/modals/SessionExpiredModal'

let modalContainer: HTMLDivElement | null = null
let modalRoot: Root | null = null

/**
 * Shows a session expired modal and redirects to login page
 * @param currentPath - Current page path to redirect back to after login
 */
export function showSessionExpiredModal(currentPath?: string) {
  // Prevent multiple modals from being shown
  if (modalContainer) return

  // Create container for the modal
  modalContainer = document.createElement('div')
  modalContainer.id = 'session-expired-modal'
  document.body.appendChild(modalContainer)

  // Create React root for the modal
  modalRoot = createRoot(modalContainer)

  const handleConfirm = () => {
    cleanup()

    // Build redirect URL
    const loginUrl = '/login'
    const redirectUrl =
      currentPath && currentPath !== '/login'
        ? `${loginUrl}?redirect=${encodeURIComponent(currentPath)}`
        : loginUrl

    // Redirect to login page
    window.location.href = redirectUrl
  }

  const cleanup = () => {
    if (modalRoot) {
      modalRoot.unmount()
      modalRoot = null
    }
    if (modalContainer) {
      document.body.removeChild(modalContainer)
      modalContainer = null
    }
  }

  // Render the modal
  modalRoot.render(
    React.createElement(SessionExpiredModal, {
      show: true,
      onConfirm: handleConfirm,
    }),
  )
}
