"use client"

import type { IUnderMaintenancePageProps } from "./UnderMaintenancePage.d"
import type { JSX } from "react"

import { FunctionComponent, useEffect } from "react"
import { useRouter, useSearchParams } from "next/navigation"
import { Construction } from "lucide-react"

import api from "@shared/api"

import styles from "./UnderMaintenancePage.module.scss"

const PING_INTERVAL_MS = 5000

export const UnderMaintenancePage: FunctionComponent<IUnderMaintenancePageProps> = (): JSX.Element => {
	const router = useRouter()
	const searchParams = useSearchParams()
	const redirectPath = searchParams?.get("path") || "/"

	const { isSuccess } = api.useQuery("get", "/api/ping/", {}, {
		refetchInterval: PING_INTERVAL_MS,
		retry: false,
	})

	useEffect(() => {
		if (isSuccess) {
			router.replace(redirectPath)
		}
	}, [isSuccess, redirectPath, router])

	return (
		<div className={styles.root} data-testid="UnderMaintenancePage">
			<div className={styles.card}>
				<div className={styles.icon}>
					<Construction size={48} strokeWidth={1.5} />
				</div>
				<h1 className={styles.title}>Платформа недоступна</h1>
				<p className={styles.description}>Попробуйте зайти позже.</p>
			</div>
		</div>
	)
}
