import { html, TemplateResult, LitElement } from 'lit'
import { property, state } from 'lit/decorators.js'
import type { IUser } from '@api-client/core/models/store/User.js'
import '@material/web/focus/md-focus-ring.js'
import '@material/web/ripple/ripple.js'

export default class UserAvatar extends LitElement {
  private _user?: IUser

  /**
   * Set with the user. The computed user initials.
   */
  @state() protected accessor userInitials: string | undefined

  /**
   * The URL to the user picture.
   */
  @state() protected accessor userPicture: string | undefined

  get user(): IUser | undefined {
    return this._user
  }

  /**
   * @attribute
   */
  @property({ type: Object })
  set user(value: IUser | undefined) {
    const old = this._user
    if (old === value) {
      return
    }
    if (old && value && old.key === value.key) {
      return
    }
    this._user = value
    this.requestUpdate('user', old)
    this._processUser(value)
  }

  protected _processUser(user?: IUser): void {
    if (user) {
      this.userInitials = this._readUserInitials(user)
      this.userPicture = user.picture && user.picture.url
    } else {
      this.userInitials = undefined
      this.userPicture = undefined
    }
  }

  protected _readUserInitials(user: IUser): string | undefined {
    const { name } = user
    if (!name) {
      return undefined
    }
    const max = 2
    const parts = name
      .split(/[\s-]/)
      .slice(0, max)
      .filter((i) => !!i)
      .map((i) => i[0])
    return parts.join('')
  }

  protected _pictureError(): void {
    this.userPicture = undefined
  }

  /**
   * @return Template result for an icon
   */
  override render(): TemplateResult {
    const { user, userPicture } = this
    if (!user || user.key === 'default') {
      return html``
    }
    let content: TemplateResult
    if (userPicture) {
      content = this.pictureTemplate(userPicture)
    } else if (this.userInitials) {
      content = this.nameTemplate(this.userInitials)
    } else {
      content = this.nameTemplate('')
    }
    return html`
      <button id="button" class="icon-button">
        <md-focus-ring part="focus-ring" for="button"></md-focus-ring>
        <md-ripple></md-ripple>
        <span role="presentation" class="icon">${content}</span>
        <span class="touch"></span>
      </button>
    `
  }

  protected pictureTemplate(url: string): TemplateResult {
    return html`
      <img
        src="${url}"
        alt="${this.userInitials || 'Thumb'}"
        class="user-picture user-icon"
        @error="${this._pictureError}"
      />
    `
  }

  /**
   * Renders a bubble with user initials
   * @param initials The user initials
   */
  protected nameTemplate(initials: string): TemplateResult {
    return html` <span class="avatar-initials user-icon">${initials}</span> `
  }
}
