'use client'

import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
import { authFetch, clearToken, getApiBase, getToken } from '../lib/auth'

type ProfileInfo = {
  username: string
  role: string
  auth_provider: string
}

export default function ProfilePage() {
  const router = useRouter()
  const [profile, setProfile] = useState<ProfileInfo | null>(null)
  const [currentPassword, setCurrentPassword] = useState('')
  const [newPassword, setNewPassword] = useState('')
  const [status, setStatus] = useState<string | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    if (!getToken()) {
      router.push('/login')
      return
    }
    const load = async () => {
      try {
        const baseUrl = getApiBase()
        const response = await authFetch(`${baseUrl}/auth/me`)
        if (!response.ok) {
          clearToken()
          router.push('/login')
          return
        }
        const data = await response.json()
        setProfile({
          username: data?.username ?? 'Unknown',
          role: data?.role ?? 'user',
          auth_provider: data?.auth_provider ?? 'local',
        })
      } catch (err) {
        console.error(err)
        setStatus('Could not load your profile.')
      } finally {
        setLoading(false)
      }
    }
    void load()
  }, [router])

  const submit = async (event: React.FormEvent) => {
    event.preventDefault()
    setStatus(null)
    if (!currentPassword || !newPassword) {
      setStatus('Enter your current password and a new password.')
      return
    }
    try {
      const baseUrl = getApiBase()
      const response = await authFetch(`${baseUrl}/auth/password`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          current_password: currentPassword,
          new_password: newPassword,
        }),
      })
      if (!response.ok) {
        const text = await response.text()
        throw new Error(text || 'Update failed')
      }
      setCurrentPassword('')
      setNewPassword('')
      setStatus('Password updated.')
    } catch (err) {
      console.error(err)
      setStatus('Could not update password. Check your current password.')
    }
  }

  if (loading) {
    return <main className="card">Loading profile...</main>
  }

  return (
    <main className="card">
      <h1>My profile</h1>
      {profile && (
        <div className="status-banner">
          Signed in as <strong>{profile.username}</strong> ({profile.role}). Login type:{' '}
          {profile.auth_provider}.
        </div>
      )}
      {profile?.auth_provider !== 'local' ? (
        <div className="status-banner">
          Password changes are only available for local Magent accounts.
        </div>
      ) : (
        <form onSubmit={submit} className="auth-form">
          <label>
            Current password
            <input
              type="password"
              value={currentPassword}
              onChange={(event) => setCurrentPassword(event.target.value)}
              autoComplete="current-password"
            />
          </label>
          <label>
            New password
            <input
              type="password"
              value={newPassword}
              onChange={(event) => setNewPassword(event.target.value)}
              autoComplete="new-password"
            />
          </label>
          {status && <div className="status-banner">{status}</div>}
          <div className="auth-actions">
            <button type="submit">Update password</button>
          </div>
        </form>
      )}
    </main>
  )
}
