'use client'
import React, { useState } from 'react'
import type { SessionCompletion } from '@/types'

interface HeatmapProps {
  completions: SessionCompletion[]
  totalWeeks?: number
}

function getHeatLevel(count: number): 0 | 1 | 2 | 3 {
  if (count === 0) return 0
  if (count === 1) return 1
  if (count <= 3) return 2
  return 3
}

const HEAT_COLORS = [
  'var(--heatmap-0)',
  'var(--heatmap-1)',
  'var(--heatmap-2)',
  'var(--heatmap-3)',
]

export function Heatmap({ completions, totalWeeks = 26 }: HeatmapProps) {
  const [tooltip, setTooltip] = useState<{ week: number; count: number } | null>(null)

  // Group completions by week_number
  const weekMap = new Map<number, number>()
  for (const c of completions) {
    weekMap.set(c.week_number, (weekMap.get(c.week_number) ?? 0) + 1)
  }

  const weeks = Array.from({ length: totalWeeks }, (_, i) => i + 1)

  return (
    <div>
      <div
        style={{
          fontSize: 'var(--t-label)',
          fontFamily: 'var(--font-mono)',
          textTransform: 'uppercase',
          letterSpacing: 'var(--label-ls)',
          color: 'var(--fg-muted)',
          marginBottom: 'var(--s-3)',
        }}
      >
        26-week activity
      </div>
      <div
        style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(13, 1fr)',
          gap: '4px',
          position: 'relative',
        }}
      >
        {weeks.map((week) => {
          const count = weekMap.get(week) ?? 0
          const level = getHeatLevel(count)
          return (
            <div
              key={week}
              onMouseEnter={() => setTooltip({ week, count })}
              onMouseLeave={() => setTooltip(null)}
              onFocus={() => setTooltip({ week, count })}
              onBlur={() => setTooltip(null)}
              tabIndex={0}
              role="gridcell"
              aria-label={`Week ${week}: ${count} completion${count !== 1 ? 's' : ''}`}
              style={{
                aspectRatio: '1',
                borderRadius: 'var(--r-sm)',
                background: HEAT_COLORS[level],
                cursor: 'pointer',
                transition: 'transform 100ms',
                outline: 'none',
              }}
              onMouseDown={(e) => {
                e.currentTarget.style.transform = 'scale(0.9)'
              }}
              onMouseUp={(e) => {
                e.currentTarget.style.transform = 'scale(1)'
              }}
            />
          )
        })}
      </div>

      {tooltip && (
        <div
          style={{
            marginTop: 'var(--s-2)',
            fontSize: 'var(--t-small)',
            color: 'var(--fg-muted)',
            textAlign: 'center',
          }}
        >
          Week {tooltip.week}: {tooltip.count} completion{tooltip.count !== 1 ? 's' : ''}
        </div>
      )}

      <div
        style={{
          display: 'flex',
          alignItems: 'center',
          gap: 'var(--s-2)',
          marginTop: 'var(--s-3)',
          justifyContent: 'flex-end',
        }}
      >
        <span style={{ fontSize: 'var(--t-label)', fontFamily: 'var(--font-mono)', color: 'var(--fg-subtle)' }}>
          Less
        </span>
        {HEAT_COLORS.map((color, i) => (
          <div
            key={i}
            style={{
              width: '12px',
              height: '12px',
              borderRadius: '3px',
              background: color,
            }}
          />
        ))}
        <span style={{ fontSize: 'var(--t-label)', fontFamily: 'var(--font-mono)', color: 'var(--fg-subtle)' }}>
          More
        </span>
      </div>
    </div>
  )
}
