import { useState } from 'react'
import { useNavigate, Link } from 'react-router-dom'
import { api } from '../api/client'

export function ResetPasswordPage() {
  // Token wird als URL-Fragment (#token) übergeben – landet nicht in Server-Logs oder Referer-Headern
  const token = window.location.hash.slice(1)
  const navigate = useNavigate()

  const [password, setPassword] = useState('')
  const [password2, setPassword2] = useState('')
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(false)

  const submit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (password !== password2) { setError('Passwörter stimmen nicht überein.'); return }
    if (password.length < 8) { setError('Mindestens 8 Zeichen erforderlich.'); return }
    setError('')
    setLoading(true)
    try {
      await api.post('/auth/password-reset/confirm', { token, new_password: password })
      navigate('/login', { state: { message: 'Passwort erfolgreich geändert. Bitte melde dich an.' } })
    } catch (err: unknown) {
      setError(err instanceof Error ? err.message : 'Fehler beim Zurücksetzen')
    } finally {
      setLoading(false)
    }
  }

  if (!token) return (
    <div className='min-h-screen flex items-center justify-center p-4'>
      <div className='text-center'>
        <p className='text-gray-600 mb-4'>Ungültiger oder fehlender Reset-Link.</p>
        <Link to='/login' className='text-blue-600 hover:underline'>Zurück zur Anmeldung</Link>
      </div>
    </div>
  )

  return (
    <div className='min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 flex items-center justify-center p-4'>
      <div className='w-full max-w-sm bg-white rounded-2xl shadow-lg p-8'>
        <div className='flex items-center gap-2 mb-6'>
          <div className='w-8 h-8 bg-blue-600 rounded-lg flex items-center justify-center'>
            <span className='text-white font-bold text-sm'>TM</span>
          </div>
          <span className='text-lg font-bold text-gray-800'>TimeMaster</span>
        </div>

        <h1 className='text-xl font-semibold text-gray-800 mb-1'>Neues Passwort</h1>
        <p className='text-sm text-gray-500 mb-6'>Wähle ein sicheres Passwort (min. 8 Zeichen, 1 Großbuchstabe, 1 Ziffer).</p>

        <form onSubmit={submit} className='space-y-4'>
          <label className='block'>
            <span className='text-sm font-medium text-gray-700'>Neues Passwort</span>
            <input
              type='password'
              value={password}
              onChange={e => setPassword(e.target.value)}
              required
              autoFocus
              className='mt-1 w-full border border-gray-300 rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-400'
            />
          </label>
          <label className='block'>
            <span className='text-sm font-medium text-gray-700'>Passwort wiederholen</span>
            <input
              type='password'
              value={password2}
              onChange={e => setPassword2(e.target.value)}
              required
              className='mt-1 w-full border border-gray-300 rounded-lg px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-400'
            />
          </label>

          {error && (
            <div className='text-sm text-red-700 bg-red-50 border border-red-200 rounded-lg px-3 py-2.5'>{error}</div>
          )}

          <button
            type='submit'
            disabled={loading}
            className='w-full py-2.5 text-sm font-semibold text-white bg-blue-600 rounded-lg hover:bg-blue-700 disabled:opacity-50'
          >
            {loading ? 'Speichern…' : 'Passwort speichern'}
          </button>
        </form>
      </div>
    </div>
  )
}
