import { FormEvent, useState } from 'react'
import { Link } from 'react-router-dom'
import axios from 'axios'
import { authService } from '@/services/auth'
import logoImg from '@/assets/logo.png'

export function ForgotPasswordPage() {
  const [email, setEmail] = useState('')
  const [loading, setLoading] = useState(false)
  const [successMessage, setSuccessMessage] = useState<string | null>(null)
  const [errorMessage, setErrorMessage] = useState<string | null>(null)
  const [submitted, setSubmitted] = useState(false)

  const onSubmit = async (event: FormEvent) => {
    event.preventDefault()
    setLoading(true)
    setErrorMessage(null)

    try {
      await authService.forgotPassword({ email })
      setSuccessMessage('Um link de recuperação foi enviado para seu e-mail. Verifique sua caixa de entrada.')
      setSubmitted(true)
      setEmail('')
    } catch (error) {
      const fallback = 'Não foi possível enviar o link de recuperação. Tente novamente.'
      if (axios.isAxiosError(error)) {
        setErrorMessage(error.response?.data?.error ?? fallback)
      } else if (error instanceof Error) {
        setErrorMessage(error.message)
      } else {
        setErrorMessage(fallback)
      }
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="flex min-h-screen items-center justify-center bg-gray-100 p-4">
      <div className="w-full max-w-[400px] overflow-hidden rounded-2xl bg-white shadow-xl">
        {/* Blue Header with Logo */}
        <div className="flex flex-col items-center bg-blue-600 pb-8 pt-10 text-white">
          <div className="mb-4 flex h-16 w-16 items-center justify-center rounded-2xl bg-white/10 backdrop-blur-sm">
            <img src={logoImg} alt="Logo" className="h-10 w-auto brightness-0 invert" />
          </div>
          <h1 className="text-2xl font-bold">SaveInMed</h1>
          <p className="text-blue-100 text-sm">Recuperar Acesso</p>
        </div>

        {/* Form Content */}
        <form onSubmit={onSubmit} className="p-8 space-y-5">
          {successMessage && !submitted && (
            <div className="flex items-center gap-2 rounded-lg bg-green-50 px-4 py-3 text-sm text-green-600 border border-green-100">
              <svg className="h-5 w-5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              <span>{successMessage}</span>
            </div>
          )}

          {errorMessage && (
            <div className="flex items-center gap-2 rounded-lg bg-red-50 px-4 py-3 text-sm text-red-600 border border-red-100">
              <svg className="h-5 w-5 shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
              <span>{errorMessage}</span>
            </div>
          )}

          {submitted ? (
            <div className="text-center space-y-4">
              <div className="flex justify-center">
                <svg className="h-12 w-12 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
              </div>
              <h2 className="text-lg font-bold text-gray-900">E-mail enviado com sucesso!</h2>
              <p className="text-sm text-gray-600">
                Um link de recuperação foi enviado para <strong>{email}</strong>. Clique no link para redefinir sua senha.
              </p>
              <div className="pt-4 space-y-2">
                <button
                  type="button"
                  onClick={() => setSubmitted(false)}
                  className="w-full rounded-xl bg-blue-600 py-3 font-semibold text-white shadow-lg shadow-blue-200 hover:bg-blue-700 hover:shadow-xl active:translate-y-0.5 focus:ring-2 focus:ring-blue-200 transition-all"
                >
                  Enviar para outro e-mail
                </button>
                <Link
                  to="/login"
                  className="w-full block text-center rounded-xl border border-gray-300 py-3 font-semibold text-gray-700 hover:bg-gray-50 transition-all"
                >
                  Voltar para login
                </Link>
              </div>
            </div>
          ) : (
            <>
              <div>
                <p className="text-sm text-gray-600 mb-4">
                  Digite o e-mail associado à sua conta e enviaremos um link para recuperar sua senha.
                </p>
              </div>

              <div className="space-y-1.5">
                <label className="text-sm font-medium text-gray-700 ml-1">Email</label>
                <div className="relative">
                  <div className="absolute inset-y-0 left-0 flex items-center pl-3 pointer-events-none text-gray-400">
                    <span className="text-lg">@</span>
                  </div>
                  <input
                    type="email"
                    placeholder="seu@email.com"
                    className="w-full rounded-xl border border-gray-200 py-2.5 pl-10 pr-3 text-gray-800 placeholder-gray-400 focus:border-blue-500 focus:ring-2 focus:ring-blue-100 transition-all outline-none"
                    value={email}
                    onChange={(e) => setEmail(e.target.value)}
                    required
                  />
                </div>
              </div>

              <div className="pt-2">
                <button
                  type="submit"
                  className="w-full rounded-xl bg-blue-600 py-3 font-semibold text-white shadow-lg shadow-blue-200 hover:bg-blue-700 hover:shadow-xl active:translate-y-0.5 focus:ring-2 focus:ring-blue-200 transition-all disabled:opacity-70 flex items-center justify-center gap-2"
                  disabled={loading}
                >
                  {loading ? (
                    <>
                      <svg className="animate-spin h-5 w-5 text-white" fill="none" viewBox="0 0 24 24"><circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle><path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>
                      Enviando...
                    </>
                  ) : (
                    <>
                      <svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" /></svg>
                      Enviar Link de Recuperação
                    </>
                  )}
                </button>
              </div>

              <div className="text-center">
                <Link
                  to="/login"
                  className="text-sm text-blue-600 hover:underline"
                >
                  Voltar para login
                </Link>
              </div>
            </>
          )}
        </form>
      </div>
    </div>
  )
}
