"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 { 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)
  const sessionUser = session?.user
  const userId = sessionUser?.id ?? null
  const normalizedRole = sessionUser?.role ? sessionUser.role.toLowerCase() : null
  const persona = typeof sessionUser?.machinePersona === "string" ? sessionUser.machinePersona.toLowerCase() : null

  useEffect(() => {
    if (isPending) return
    if (!userId) return
    const defaultDest =
      normalizedRole === "machine"
        ? persona === "manager"
          ? "/dashboard"
          : "/portal/tickets"
        : "/dashboard"
    const destination = callbackUrl ?? defaultDest
    router.replace(destination)
  }, [
    callbackUrl,
    isPending,
    normalizedRole,
    persona,
    router,
    userId,
  ])

  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-2 text-center">
          <Link href="/" className="group flex flex-col items-center gap-2">
            <div className="flex items-center gap-2">
              <span className="text-2xl font-bold tracking-tight text-neutral-900">
                Raven
              </span>
              <span className="rounded-full bg-neutral-900 px-2.5 py-0.5 text-xs font-medium text-white">
                Helpdesk
              </span>
            </div>
            <span className="text-sm text-neutral-500">
              Por Rever Tecnologia
            </span>
          </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="/logo-raven.png"
            alt="Logotipo Raven"
            width={160}
            height={160}
            className="h-16 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 bg-gradient-to-br from-neutral-800 via-neutral-700 to-neutral-600 lg:flex">
        <ShaderBackground className="h-full w-full opacity-50" />
        <div className="absolute inset-0 flex items-center justify-center px-8">
          <div className="text-center text-white">
            <h2 className="text-5xl font-bold tracking-tight leading-tight">Bem-vindo de volta</h2>
            <p className="mt-4 text-xl text-neutral-300">
              Gerencie seus chamados e tickets de forma simples
            </p>
          </div>
        </div>
      </div>
    </div>
  )
}
