import { useEffect, useState } from 'react'
import type { ReactNode } from 'react'

import type { Employee } from '../../../entities/employee/model/types'
import { LoginPage } from '../../../pages/LoginPage/LoginPage'
import { authService } from '../api/authService'

type AuthGateProps = {
  children: ReactNode
}

export function AuthGate({ children }: AuthGateProps) {
  const [currentUser, setCurrentUser] = useState<Employee | null>(null)
  const [isCheckingAuth, setIsCheckingAuth] = useState(true)

  useEffect(() => {
    let isMounted = true

    async function syncCurrentUser() {
      const user = await authService.getCurrentUser()

      if (!isMounted) return

      setCurrentUser(user)
      setIsCheckingAuth(false)
    }

    syncCurrentUser()

    function handleAuthChange() {
      setIsCheckingAuth(true)
      syncCurrentUser()
    }

    function handleLogout() {
      setCurrentUser(null)
      setIsCheckingAuth(false)
    }

    window.addEventListener('auth:change', handleAuthChange)
    window.addEventListener('auth:logout', handleLogout)
    window.addEventListener('users:change', handleAuthChange)

    return () => {
      isMounted = false
      window.removeEventListener('auth:change', handleAuthChange)
      window.removeEventListener('auth:logout', handleLogout)
      window.removeEventListener('users:change', handleAuthChange)
    }
  }, [])

  if (isCheckingAuth) {
    return <div style={{ padding: 24 }}>Проверка авторизации...</div>
  }

  if (!currentUser) {
    return (
      <LoginPage
        onSuccess={async () => {
          setCurrentUser(await authService.getCurrentUser())
        }}
      />
    )
  }

  return children
}
