"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="mt-6 flex flex-col items-center gap-3 text-center">
          <Link href="/" className="group flex flex-col items-center gap-2">
            <div className="flex items-center gap-2.5">
              <span className="text-3xl font-bold tracking-tight text-neutral-900">
                Raven
              </span>
              <span className="rounded-full bg-neutral-900 px-3 py-1 text-sm font-medium text-white">
                Helpdesk
              </span>
            </div>
            <span className="text-base 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 items-center justify-center p-6 lg:flex">
        <div className="relative h-[calc(100%-0px)] w-full overflow-hidden rounded-3xl bg-gradient-to-br from-neutral-800 via-neutral-700 to-neutral-600 shadow-2xl">
          <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>
    </div>
  )
}
