import type { CustomCell, CustomRenderer } from '@glideapps/glide-data-grid'
import { GridCellKind } from '@glideapps/glide-data-grid'

import { APP_CONFIG } from '@lib/config'

export type CountryCell = CustomCell<{ kind: 'country'; name: string; code: string }>

const countryImageCache: Record<string, HTMLImageElement> = {}

export const countryDataTableRenderer: CustomRenderer<CountryCell> = {
  kind: GridCellKind.Custom,
  isMatch: (cell): cell is CountryCell => (cell.data as { kind?: string }).kind === 'country',
  draw: ({ ctx, rect, theme }, { data: { name, code } }) => {
    if (!code || code === '') {
      return false
    }
    const flagHeight = rect.height - theme.cellVerticalPadding * 2
    const flagWidth = flagHeight * 1.5 // flags are 3:2 aspect ratio

    const top = rect.y + theme.cellVerticalPadding
    const left = rect.x + theme.cellHorizontalPadding

    if (!countryImageCache[code]) {
      countryImageCache[code] = new Image()
      countryImageCache[code].src = `/flags/${code}.svg`
      countryImageCache[code].onload = () => {
        ctx.canvas.dispatchEvent(new Event('invalidate'))
      }
    }

    const image = countryImageCache[code]

    if (image.complete && image.naturalHeight !== 0 && !APP_CONFIG.useTestAssets) {
      const circlepath = new Path2D()
      circlepath.roundRect(left, top, flagWidth, flagHeight, 2)

      ctx.save()
      ctx.clip(circlepath)
      ctx.drawImage(image, left, top, flagWidth, flagHeight)
      ctx.restore()
    } else {
      ctx.save()
      ctx.fillStyle = theme.textLight
      ctx.fillRect(left, top, flagWidth, flagHeight)
      ctx.restore()
    }

    ctx.save()
    ctx.font = `${theme.baseFontFull} ${theme.fontFamily}`
    ctx.fillStyle = theme.textDark
    ctx.fillText(name, left + flagWidth + 5, top + flagHeight / 2)
    ctx.restore()

    return true
  },
}
