"use client"

import { useState } from "react"
import Image from "next/image"
import Link from "next/link"
import dynamic from "next/dynamic"
import { ArrowLeft, Loader2, Mail } 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 }
)

export function ForgotPasswordPageClient() {
  const [email, setEmail] = useState("")
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [isSuccess, setIsSuccess] = useState(false)

  async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault()
    if (isSubmitting) return
    if (!email) {
      toast.error("Informe seu e-mail")
      return
    }

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

      const data = await response.json()

      if (!response.ok) {
        toast.error(data.error ?? "Erro ao processar solicitação")
        return
      }

      setIsSuccess(true)
      toast.success("E-mail de recuperação enviado!")
    } catch (error) {
      console.error("Erro ao solicitar recuperação", error)
      toast.error("Não foi possível processar. 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">
            {isSuccess ? (
              <SuccessMessage email={email} />
            ) : (
              <ForgotPasswordForm
                email={email}
                setEmail={setEmail}
                isSubmitting={isSubmitting}
                onSubmit={handleSubmit}
              />
            )}
          </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">Recuperar acesso</h2>
            <p className="mt-4 text-xl text-neutral-300">
              Enviaremos as instruções para seu e-mail
            </p>
          </div>
        </div>
      </div>
    </div>
  )
}

function ForgotPasswordForm({
  email,
  setEmail,
  isSubmitting,
  onSubmit,
}: {
  email: string
  setEmail: (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">Recuperar senha</h1>
          <p className="text-muted-foreground text-sm text-balance">
            Informe seu e-mail para receber as instruções de redefinição de senha.
          </p>
        </div>
        <Field>
          <FieldLabel htmlFor="email">E-mail</FieldLabel>
          <Input
            id="email"
            type="email"
            placeholder="seu@email.com"
            autoComplete="email"
            value={email}
            onChange={(event) => setEmail(event.target.value)}
            disabled={isSubmitting}
            required
          />
        </Field>
        <Field>
          <Button type="submit" disabled={isSubmitting} className="gap-2">
            {isSubmitting && <Loader2 className="size-4 animate-spin" />}
            Enviar instruções
          </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 SuccessMessage({ email }: { email: string }) {
  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">
          <Mail className="size-7 text-green-600" />
        </div>
        <h1 className="text-2xl font-bold">Verifique seu e-mail</h1>
        <p className="text-muted-foreground text-sm text-balance">
          Se existir uma conta com o e-mail <strong>{email}</strong>, você receberá um link para redefinir sua senha.
        </p>
        <FieldDescription className="text-sm">
          O link expira em 1 hora. Verifique também sua caixa de spam.
        </FieldDescription>
      </div>
      <div className="mt-4">
        <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>
  )
}
