"use client"

import { useEffect, useState } from "react"
import Image from "next/image"
import Link from "next/link"
import { useRouter, useSearchParams } from "next/navigation"
import dynamic from "next/dynamic"
import { GalleryVerticalEnd } from "lucide-react"

import { LoginForm } from "@/components/login-form"
import { useSession } from "@/lib/auth-client"

const ShaderBackground = dynamic(
  () => import("@/components/background-paper-shaders-wrapper"),
  { ssr: false }
)

export function LoginPageClient() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const { data: session, isPending } = useSession()
  const callbackUrl = searchParams?.get("callbackUrl") ?? undefined
  const [isHydrated, setIsHydrated] = useState(false)

  useEffect(() => {
    if (isPending) return
    if (!session?.user) return
    const destination = callbackUrl ?? "/dashboard"
    router.replace(destination)
  }, [callbackUrl, isPending, router, session?.user])

  useEffect(() => {
    setIsHydrated(true)
  }, [])

  const shouldDisable = !isHydrated || isPending

  return (
    <div className="grid min-h-svh lg:grid-cols-2">
      <div className="flex flex-col gap-6 p-6 md:p-10">
        <div className="flex flex-col items-center gap-1.5 text-center">
          <Link href="/" className="flex items-center gap-2 text-xl font-semibold text-neutral-900">
            <div className="bg-primary text-primary-foreground flex size-6 items-center justify-center rounded-md">
              <GalleryVerticalEnd className="size-4" />
            </div>
            Sistema de chamados
          </Link>
        </div>
        <div className="flex flex-1 items-center justify-center">
          <div className="w-full max-w-sm rounded-2xl border border-slate-200 bg-white p-6 shadow-sm">
            <LoginForm callbackUrl={callbackUrl} disabled={shouldDisable} />
          </div>
        </div>
        <div className="flex justify-center">
          <Image
            src="/rever-8.png"
            alt="Logotipo Rever Tecnologia"
            width={110}
            height={110}
            className="h-[3.45rem] w-auto"
            priority
          />
        </div>
        <footer className="flex justify-center text-sm text-neutral-500">
          Desenvolvido por Esdras Renan
        </footer>
      </div>
      <div className="relative hidden overflow-hidden lg:flex">
        <ShaderBackground className="h-full w-full" />
      </div>
    </div>
  )
}
