import { useEffect, useState } from 'react'
import { Container } from 'react-bootstrap'
import { useParams } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { getUserProfile } from '../api/client'

export default function Profile() {
  const { id } = useParams()
  const { t } = useTranslation()
  const [profile, setProfile] = useState(null)
  const [error, setError] = useState('')
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    let active = true
    setLoading(true)
    setError('')

    getUserProfile(id)
      .then((data) => {
        if (!active) return
        setProfile(data)
      })
      .catch((err) => {
        if (!active) return
        setError(err.message)
      })
      .finally(() => {
        if (active) setLoading(false)
      })

    return () => {
      active = false
    }
  }, [id])

  return (
    <Container fluid className="py-5 bb-portal-shell">
      <div className="bb-portal-card">
        <div className="bb-portal-card-title">{t('profile.title')}</div>
        {loading && <p className="bb-muted">{t('profile.loading')}</p>}
        {error && <p className="text-danger">{error}</p>}
        {profile && (
          <div className="bb-profile">
            <div className="bb-profile-avatar">
              {profile.avatar_url ? (
                <img src={profile.avatar_url} alt="" />
              ) : (
                <i className="bi bi-person" aria-hidden="true" />
              )}
            </div>
            <div className="bb-profile-meta">
              <div className="bb-profile-name">{profile.name}</div>
              {profile.created_at && (
                <div className="bb-muted">
                  {t('profile.registered')} {profile.created_at.slice(0, 10)}
                </div>
              )}
            </div>
          </div>
        )}
      </div>
    </Container>
  )
}
