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

export type FavoriteCell = CustomCell<{ kind: 'favorite'; isFavorite: boolean; isSelected?: boolean }>

export const favoriteDataTableRenderer: CustomRenderer<FavoriteCell> = {
  kind: GridCellKind.Custom,
  isMatch: (cell): cell is FavoriteCell => (cell.data as { kind?: string }).kind === 'favorite',
  draw: ({ ctx, rect, theme }, { data: { isFavorite, isSelected } }) => {
    const size = Math.min(rect.width, rect.height) - theme.cellVerticalPadding * 2
    const centerX = rect.x + rect.width / 2
    const centerY = rect.y + rect.height / 2
    const scale = size / 24 // Lucide icons are typically designed on a 24x24 grid

    // Save the current context state
    ctx.save()

    // Center and scale the coordinate system
    ctx.translate(centerX, centerY)
    ctx.scale(scale, scale)

    // Draw the star path following Lucide.dev's star shape
    ctx.beginPath()

    // These points create a star path similar to Lucide's design
    // Star points in a 24x24 grid centered at 0,0
    const points = [
      [0, -10], // Top point
      [2.9, -3.1], // Upper right connecting point
      [10, -3.1], // Right point
      [3.8, 1.2], // Lower right connecting point
      [6.2, 8.2], // Lower right point
      [0, 4.4], // Bottom connecting point
      [-6.2, 8.2], // Lower left point
      [-3.8, 1.2], // Lower left connecting point
      [-10, -3.1], // Left point
      [-2.9, -3.1], // Upper left connecting point
    ]

    // Draw the star path
    ctx.moveTo(points[0][0], points[0][1])
    for (let i = 1; i < points.length; i++) {
      ctx.lineTo(points[i][0], points[i][1])
    }
    ctx.closePath()

    // Fill or just stroke based on favourite state
    if (isFavorite) {
      // Lucide uses a yellow/gold fill when active
      ctx.fillStyle = '#FFD700' // Gold color for filled star
      ctx.fill()
      ctx.lineWidth = 2
      ctx.strokeStyle = isSelected ? '#fb4b28' : '#D4AF37'
    } else {
      // When not favorited, only draw the outline
      ctx.lineWidth = isSelected ? 2 : 1 // Thinner line for cleaner look
      ctx.strokeStyle = isSelected ? '#fb4b28' : theme.textMedium
    }

    // Always draw the stroke
    ctx.stroke()

    // Restore the context state
    ctx.restore()

    return true
  },
}
