import { UserOutlined } from '@ant-design/icons'
import { Avatar } from 'antd'
import { useEffect, useState } from 'react'
import api from '../api/client'
import type { Student } from '../types'

interface Props {
  student: Pick<Student, 'id' | 'name' | 'has_avatar'>
  size?: number
}

export default function StudentAvatar({ student, size = 40 }: Props) {
  const [src, setSrc] = useState<string | null>(null)

  useEffect(() => {
    if (!student.has_avatar) {
      setSrc(null)
      return
    }
    let objectUrl: string | null = null
    let cancelled = false
    api
      .get(`/students/${student.id}/avatar`, { responseType: 'blob' })
      .then((res) => {
        if (cancelled) return
        objectUrl = URL.createObjectURL(res.data)
        setSrc(objectUrl)
      })
      .catch(() => {
        if (!cancelled) setSrc(null)
      })
    return () => {
      cancelled = true
      if (objectUrl) URL.revokeObjectURL(objectUrl)
    }
  }, [student.id, student.has_avatar])

  return (
    <Avatar
      size={size}
      src={src || undefined}
      icon={!src ? <UserOutlined /> : undefined}
      style={{ backgroundColor: src ? undefined : '#1677ff', flexShrink: 0 }}
    >
      {!src ? student.name.slice(0, 1) : null}
    </Avatar>
  )
}
