'use client'

import { useState } from 'react'
import { createBrowserClient } from '@supabase/ssr'
import { useRouter } from 'next/navigation'

type Mode = 'login' | 'reset' | 'reset-sent'

export default function LoginPage() {
  const [mode, setMode] = useState<Mode>('login')
  const [isPending, setIsPending] = useState(false)
  const [error, setError] = useState<string | null>(null)
  const [showPassword, setShowPassword] = useState(false)
  const [resetEmail, setResetEmail] = useState('')
  const router = useRouter()

  const supabase = createBrowserClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
  )

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    setIsPending(true)
    setError(null)

    const fd = new FormData(e.currentTarget)
    const { error: authError } = await supabase.auth.signInWithPassword({
      email: fd.get('email') as string,
      password: fd.get('password') as string,
    })

    if (authError) {
      setError('Email o contraseña incorrectos')
      setIsPending(false)
      return
    }

    router.push('/admin/responses')
    router.refresh()
  }

  // Reusa /auth/confirm: ya escucha PASSWORD_RECOVERY (lo armamos para el
  // flujo de invitación, pero Supabase emite el mismo evento acá).
  async function handleReset(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault()
    setIsPending(true)
    setError(null)

    const fd = new FormData(e.currentTarget)
    const email = String(fd.get('email') ?? '')

    const { error: resetError } = await supabase.auth.resetPasswordForEmail(email, {
      redirectTo: `${process.env.NEXT_PUBLIC_SITE_URL}/auth/confirm`,
    })

    setIsPending(false)

    if (resetError) {
      setError('No pudimos enviar el link. Probá de nuevo.')
      return
    }

    setResetEmail(email)
    setMode('reset-sent')
  }

  if (mode === 'reset-sent') {
    return (
      <div className="login-page">
        <div className="login-card">
          <h1 className="login-title">Revisá tu email</h1>
          <p className="admin-subtitle">
            Si <strong>{resetEmail}</strong> tiene una cuenta, te enviamos un link para crear una
            contraseña nueva.
          </p>
          <button
            type="button"
            className="login-submit login-back-button"
            onClick={() => { setMode('login'); setError(null) }}
          >
            Volver al login
          </button>
        </div>
      </div>
    )
  }

  if (mode === 'reset') {
    return (
      <div className="login-page">
        <div className="login-card">
          <h1 className="login-title">Recuperar contraseña</h1>
          <form onSubmit={handleReset} className="login-form" noValidate>
            <div className="login-field">
              <label htmlFor="reset-email" className="login-label">Email</label>
              <input
                id="reset-email"
                name="email"
                type="email"
                autoComplete="email"
                required
                disabled={isPending}
                className="text-short-input"
              />
            </div>
            {error && (
              <p role="alert" className="field-error login-error">{error}</p>
            )}
            <button type="submit" disabled={isPending} className="login-submit">
              {isPending ? 'Enviando…' : 'Enviar link de recuperación'}
            </button>
            <button
              type="button"
              className="login-forgot-link"
              onClick={() => { setMode('login'); setError(null) }}
            >
              ← Volver al login
            </button>
          </form>
        </div>
      </div>
    )
  }

  return (
    <div className="login-page">
      <div className="login-card">
        <h1 className="login-title">Acceso interno</h1>
        <form onSubmit={handleSubmit} className="login-form" noValidate>
          <div className="login-field">
            <label htmlFor="email" className="login-label">Email</label>
            <input
              id="email"
              name="email"
              type="email"
              autoComplete="email"
              required
              disabled={isPending}
              className="text-short-input"
            />
          </div>
          <div className="login-field">
            <label htmlFor="password" className="login-label">Contraseña</label>
            <div className="login-password-wrapper">
              <input
                id="password"
                name="password"
                type={showPassword ? 'text' : 'password'}
                autoComplete="current-password"
                required
                disabled={isPending}
                className="text-short-input"
              />
              <button
                type="button"
                className="login-password-toggle"
                onClick={() => setShowPassword((v) => !v)}
                aria-label={showPassword ? 'Ocultar contraseña' : 'Mostrar contraseña'}
              >
                {showPassword ? (
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                    <path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7Z" />
                    <circle cx="12" cy="12" r="3" />
                  </svg>
                ) : (
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                    <path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7Z" />
                    <circle cx="12" cy="12" r="3" />
                    <path d="M3 3l18 18" />
                  </svg>
                )}
              </button>
            </div>
          </div>
          {error && (
            <p role="alert" className="field-error login-error">{error}</p>
          )}
          <button
            type="submit"
            disabled={isPending}
            className="login-submit"
          >
            {isPending ? 'Ingresando…' : 'Ingresar'}
          </button>
          <button
            type="button"
            className="login-forgot-link"
            onClick={() => { setMode('reset'); setError(null) }}
          >
            ¿Olvidaste tu contraseña?
          </button>
        </form>
      </div>
    </div>
  )
}
