import { useState } from 'react'
import { Link, useNavigate, useSearchParams } from 'react-router-dom'
import { Logo } from '@/components/Logo'
import { Button } from '@/components/Button'
import { Field, TextInput } from '@/components/Field'
import { validatePassword } from '@/lib/validation'
import axios from 'axios'

/** Anonymous-страница приёма ссылки восстановления. URL вида
 * /reset-password?email=...&token=...; токен короткоживущий (1 час),
 * сгенерирован Identity GeneratePasswordResetTokenAsync. */
export function ResetPasswordPage() {
  const [params] = useSearchParams()
  const navigate = useNavigate()
  const email = params.get('email') ?? ''
  const token = params.get('token') ?? ''
  const [password, setPassword] = useState('')
  const [confirm, setConfirm] = useState('')
  const [error, setError] = useState<string | null>(null)
  const [busy, setBusy] = useState(false)
  const [done, setDone] = useState(false)

  const submit = async (e: React.FormEvent) => {
    e.preventDefault()
    setError(null)
    if (!email || !token) {
      setError('Ссылка некорректна. Запросите новую.')
      return
    }
    const pwErr = validatePassword(password)
    if (pwErr) { setError(pwErr); return }
    if (password !== confirm) { setError('Пароли не совпадают.'); return }
    setBusy(true)
    try {
      await axios.post('/api/auth/reset-password', { email, token, newPassword: password })
      setDone(true)
      setTimeout(() => navigate('/login', { replace: true }), 2500)
    } catch (e2) {
      const err = e2 as { response?: { data?: { error?: string } } }
      setError(err.response?.data?.error ?? 'Не удалось обновить пароль.')
    } finally {
      setBusy(false)
    }
  }

  return (
    <div className="min-h-screen flex items-center justify-center bg-slate-50 dark:bg-slate-900 p-4">
      <div className="w-full max-w-md bg-white dark:bg-slate-800 rounded-xl shadow-lg p-8 space-y-5">
        <Logo />
        {!done ? (
          <form onSubmit={submit} noValidate className="space-y-4">
            <div>
              <h1 className="text-xl font-bold text-slate-900 dark:text-slate-50">Новый пароль</h1>
              <p className="text-sm text-slate-500 mt-1">
                Аккаунт {email ? <strong>{email}</strong> : 'не указан'}.
              </p>
            </div>
            <Field label="Новый пароль">
              <TextInput type="password" value={password}
                onChange={(e) => setPassword(e.target.value)} autoComplete="new-password" required />
            </Field>
            <Field label="Повторите пароль" error={error ?? undefined}>
              <TextInput type="password" value={confirm}
                onChange={(e) => setConfirm(e.target.value)} autoComplete="new-password" required />
            </Field>
            <Button onClick={() => {}} disabled={busy} className="w-full justify-center">
              {busy ? 'Сохраняю…' : 'Установить пароль'}
            </Button>
            <p className="text-xs text-center text-slate-500">
              <Link to="/login" className="text-[var(--color-brand)] hover:underline">← К входу</Link>
            </p>
          </form>
        ) : (
          <div className="space-y-3">
            <h1 className="text-xl font-bold text-emerald-700 dark:text-emerald-400">Пароль обновлён</h1>
            <p className="text-sm text-slate-600 dark:text-slate-400">
              Сейчас перенаправим на страницу входа…
            </p>
          </div>
        )}
      </div>
    </div>
  )
}
