"use client"

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

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

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

export default function LoginPage() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const { data: session, isPending } = useSession()
  const callbackUrl = searchParams?.get("callbackUrl") ?? undefined

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

  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 justify-center gap-2">
          <Link href="/" className="flex items-center gap-2 font-medium">
            <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={isPending} />
          </div>
        </div>
      </div>
      <div className="relative hidden overflow-hidden lg:flex">
        <ShaderBackground className="h-full w-full" />
      </div>
    </div>
  )
}

