"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 { ArrowLeft, CheckCircle, Loader2, XCircle } from "lucide-react"
import { toast } from "sonner"

import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import {
  Field,
  FieldDescription,
  FieldGroup,
  FieldLabel,
} from "@/components/ui/field"
import { Input } from "@/components/ui/input"

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

type PageState = "loading" | "invalid" | "form" | "success"

export function ResetPasswordPageClient() {
  const router = useRouter()
  const searchParams = useSearchParams()
  const token = searchParams?.get("token") ?? ""

  const [pageState, setPageState] = useState<PageState>("loading")
  const [password, setPassword] = useState("")
  const [confirmPassword, setConfirmPassword] = useState("")
  const [isSubmitting, setIsSubmitting] = useState(false)

  useEffect(() => {
    if (!token) {
      setPageState("invalid")
      return
    }

    async function validateToken() {
      try {
        const response = await fetch(`/api/auth/reset-password?token=${token}`)
        const data = await response.json()
        setPageState(data.valid ? "form" : "invalid")
      } catch {
        setPageState("invalid")
      }
    }

    validateToken()
  }, [token])

  async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault()
    if (isSubmitting) return

    if (password.length < 6) {
      toast.error("A senha deve ter pelo menos 6 caracteres")
      return
    }

    if (password !== confirmPassword) {
      toast.error("As senhas não conferem")
      return
    }

    setIsSubmitting(true)
    try {
      const response = await fetch("/api/auth/reset-password", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ token, password }),
      })

      const data = await response.json()

      if (!response.ok) {
        toast.error(data.error ?? "Erro ao redefinir senha")
        return
      }

      setPageState("success")
      toast.success("Senha redefinida com sucesso!")
    } catch (error) {
      console.error("Erro ao redefinir senha", error)
      toast.error("Não foi possível redefinir a senha. Tente novamente")
    } finally {
      setIsSubmitting(false)
    }
  }

  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">
            {pageState === "loading" && <LoadingState />}
            {pageState === "invalid" && <InvalidTokenState />}
            {pageState === "form" && (
              <ResetPasswordForm
                password={password}
                setPassword={setPassword}
                confirmPassword={confirmPassword}
                setConfirmPassword={setConfirmPassword}
                isSubmitting={isSubmitting}
                onSubmit={handleSubmit}
              />
            )}
            {pageState === "success" && <SuccessState />}
          </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">Nova senha</h2>
            <p className="mt-4 text-xl text-neutral-300">
              Crie uma senha segura para sua conta
            </p>
          </div>
        </div>
      </div>
    </div>
  )
}

function LoadingState() {
  return (
    <FieldGroup>
      <div className="flex flex-col items-center gap-4 text-center py-8">
        <Loader2 className="size-10 animate-spin text-muted-foreground" />
        <p className="text-muted-foreground text-sm">Validando seu link...</p>
      </div>
    </FieldGroup>
  )
}

function InvalidTokenState() {
  return (
    <FieldGroup>
      <div className="flex flex-col items-center gap-4 text-center">
        <div className="flex size-14 items-center justify-center rounded-full bg-red-100">
          <XCircle className="size-7 text-red-600" />
        </div>
        <h1 className="text-2xl font-bold">Link inválido</h1>
        <p className="text-muted-foreground text-sm text-balance">
          Este link de redefinição de senha é inválido ou já expirou.
        </p>
        <FieldDescription className="text-sm">
          Solicite um novo link na página de recuperação de senha.
        </FieldDescription>
      </div>
      <div className="mt-6 flex flex-col gap-3">
        <Button asChild>
          <Link href="/recuperar">Solicitar novo link</Link>
        </Button>
        <Link
          href="/login"
          className="flex items-center justify-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors"
        >
          <ArrowLeft className="size-4" />
          Voltar para o login
        </Link>
      </div>
    </FieldGroup>
  )
}

function ResetPasswordForm({
  password,
  setPassword,
  confirmPassword,
  setConfirmPassword,
  isSubmitting,
  onSubmit,
}: {
  password: string
  setPassword: (value: string) => void
  confirmPassword: string
  setConfirmPassword: (value: string) => void
  isSubmitting: boolean
  onSubmit: (event: React.FormEvent<HTMLFormElement>) => void
}) {
  return (
    <form onSubmit={onSubmit} className={cn("flex flex-col gap-6", isSubmitting && "pointer-events-none opacity-70")}>
      <FieldGroup>
        <div className="flex flex-col items-center gap-1 text-center">
          <h1 className="text-2xl font-bold">Nova senha</h1>
          <p className="text-muted-foreground text-sm text-balance">
            Digite sua nova senha abaixo. Escolha uma senha segura com pelo menos 6 caracteres.
          </p>
        </div>
        <Field>
          <FieldLabel htmlFor="password">Nova senha</FieldLabel>
          <Input
            id="password"
            type="password"
            placeholder="Digite sua nova senha"
            autoComplete="new-password"
            value={password}
            onChange={(event) => setPassword(event.target.value)}
            disabled={isSubmitting}
            required
            minLength={6}
          />
        </Field>
        <Field>
          <FieldLabel htmlFor="confirmPassword">Confirmar senha</FieldLabel>
          <Input
            id="confirmPassword"
            type="password"
            placeholder="Digite novamente"
            autoComplete="new-password"
            value={confirmPassword}
            onChange={(event) => setConfirmPassword(event.target.value)}
            disabled={isSubmitting}
            required
            minLength={6}
          />
        </Field>
        <Field>
          <Button type="submit" disabled={isSubmitting} className="gap-2">
            {isSubmitting && <Loader2 className="size-4 animate-spin" />}
            Redefinir senha
          </Button>
        </Field>
        <Field>
          <Link
            href="/login"
            className="flex items-center justify-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors"
          >
            <ArrowLeft className="size-4" />
            Voltar para o login
          </Link>
        </Field>
      </FieldGroup>
    </form>
  )
}

function SuccessState() {
  return (
    <FieldGroup>
      <div className="flex flex-col items-center gap-4 text-center">
        <div className="flex size-14 items-center justify-center rounded-full bg-green-100">
          <CheckCircle className="size-7 text-green-600" />
        </div>
        <h1 className="text-2xl font-bold">Senha redefinida!</h1>
        <p className="text-muted-foreground text-sm text-balance">
          Sua senha foi alterada com sucesso. Você já pode fazer login com sua nova senha.
        </p>
      </div>
      <div className="mt-6">
        <Button asChild className="w-full">
          <Link href="/login">Ir para o login</Link>
        </Button>
      </div>
    </FieldGroup>
  )
}
