import React, { useState } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { getAdminToken, setAdminToken, verifyAdminToken } from '../../utils/api'

export default function AdminLogin() {
  const [token, setToken] = useState(() => getAdminToken())
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const location = useLocation()
  const navigate = useNavigate()

  const handleSubmit = async (event) => {
    event.preventDefault()
    setError('')
    if (!token) {
      setError('Please provide the admin access token.')
      return
    }

    setLoading(true)
    try {
      await verifyAdminToken(token)
      setAdminToken(token)
      const redirectTo = location.state?.from?.pathname || '/admin/events'
      navigate(redirectTo, { replace: true })
    } catch (err) {
      console.error('Admin login failed', err)
      setError(err.message || 'Unable to verify token. Please try again.')
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="max-w-lg mx-auto bg-white border border-subtle rounded-xl shadow-sm p-8">
      <h1 className="text-2xl font-semibold mb-6 text-slate-900">Admin Login</h1>
      <p className="text-body text-muted mb-6">
        Enter the admin access token provided to your team to manage events.
      </p>
      <form onSubmit={handleSubmit} className="space-y-4">
        <div>
          <label htmlFor="admin-token" className="block text-sm font-medium text-slate-700 mb-2">
            Access Token
          </label>
          <input
            id="admin-token"
            type="password"
            value={token}
            onChange={(event) => setToken(event.target.value)}
            className="w-full border border-subtle rounded-md px-4 py-2 outline-none focus:ring-2 focus:ring-primary"
            placeholder="Enter secure token"
            autoComplete="off"
          />
        </div>
        {error && <p className="text-sm text-red-600">{error}</p>}
        <div className="flex items-center justify-between">
          <button type="submit" className="btn" disabled={loading}>
            {loading ? 'Verifying...' : 'Log in'}
          </button>
          <span className="text-sm text-muted">Need access? Contact the site administrator.</span>
        </div>
      </form>
    </div>
  )
}
