'use client'

import { useRouter } from 'next/navigation'
import { useState } from 'react'
import { getApiBase, setToken, clearToken } from '../lib/auth'
import BrandingLogo from '../ui/BrandingLogo'

export default function LoginPage() {
  const router = useRouter()
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [error, setError] = useState<string | null>(null)
  const [loading, setLoading] = useState(false)

  const submit = async (event: React.FormEvent, mode: 'local' | 'jellyfin') => {
    event.preventDefault()
    setError(null)
    setLoading(true)
    try {
      clearToken()
      const baseUrl = getApiBase()
      const endpoint = mode === 'jellyfin' ? '/auth/jellyfin/login' : '/auth/login'
      const body = new URLSearchParams({ username, password })
      const response = await fetch(`${baseUrl}${endpoint}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body,
      })
      if (!response.ok) {
        throw new Error('Login failed')
      }
      const data = await response.json()
      if (data?.access_token) {
        setToken(data.access_token)
        if (typeof window !== 'undefined') {
          window.location.href = '/'
          return
        }
        router.push('/')
        return
      }
      throw new Error('Login failed')
    } catch (err) {
      console.error(err)
      setError('Invalid username or password.')
    } finally {
      setLoading(false)
    }
  }

  return (
    <main className="card auth-card">
      <BrandingLogo className="brand-logo brand-logo--login" />
      <h1>Sign in</h1>
      <p className="lede">Use your Jellyfin account, or sign in with Magent instead.</p>
      <form onSubmit={(event) => submit(event, 'jellyfin')} className="auth-form">
        <label>
          Username
          <input
            value={username}
            onChange={(event) => setUsername(event.target.value)}
            autoComplete="username"
          />
        </label>
        <label>
          Password
          <input
            type="password"
            value={password}
            onChange={(event) => setPassword(event.target.value)}
            autoComplete="current-password"
          />
        </label>
        {error && <div className="error-banner">{error}</div>}
        <div className="auth-actions">
          <button type="submit" disabled={loading}>
            {loading ? 'Signing in...' : 'Login with Jellyfin account'}
          </button>
        </div>
        <button
          type="button"
          className="ghost-button"
          disabled={loading}
          onClick={(event) => submit(event, 'local')}
        >
          Sign in with Magent account
        </button>
      </form>
      <div className="status-banner">
        Have an invite? <a href="/register">Create an account</a>
      </div>
    </main>
  )
}
