'use client'

import { useMemo } from'react'
import { getISOWeek } from'@/lib/planning-config'
import type { Assignment, PlanningProject } from'@/lib/planning-types'

interface Props {
 assignments: Assignment[]
 projects: PlanningProject[]
 /** How many weeks to show (default 12) */
 weekCount?: number
}

function isoWeekKey(date: Date): string {
 const y = date.getFullYear()
 const w = getISOWeek(date)
 return `${y}-W${String(w).padStart(2,'0')}`
}

function weekLabel(key: string): string {
 const [, w] = key.split('-W')
 return `KW ${w}`
}

function hexToRgb(hex: string): [number, number, number] {
 const n = parseInt(hex.replace('#',''), 16)
 return [(n >> 16) & 255, (n >> 8) & 255, n & 255]
}

/** Interpolate between white and a target color. intensity 0..1 */
function interpolate(hex: string, intensity: number): string {
 const [r, g, b] = hexToRgb(hex)
 const ri = Math.round(255 + (r - 255) * intensity)
 const gi = Math.round(255 + (g - 255) * intensity)
 const bi = Math.round(255 + (b - 255) * intensity)
 return `rgb(${ri},${gi},${bi})`
}

export default function ProjectHeatmap({ assignments, projects, weekCount = 16 }: Props) {
 // Build sorted list of ISO week keys covering the last `weekCount` weeks
 const weeks = useMemo(() => {
 const result: string[] = []
 const today = new Date()
 for (let i = weekCount - 1; i >= 0; i--) {
 const d = new Date(today)
 d.setDate(d.getDate() - i * 7)
 const k = isoWeekKey(d)
 if (!result.includes(k)) result.push(k)
 }
 return result
 }, [weekCount])

 // Count assignments per (project, week)
 const heatData = useMemo(() => {
 const counts = new Map<string, number>() //"projectId:weekKey"→ count
 for (const a of assignments) {
 if (!a.project_id) continue
 const d = new Date(a.date +'T00:00:00')
 const key = `${a.project_id}:${isoWeekKey(d)}`
 counts.set(key, (counts.get(key) ?? 0) + 1)
 }
 return counts
 }, [assignments])

 // Only show projects that have at least one assignment
 const activeProjects = useMemo(() => {
 const ids = new Set(assignments.filter((a) => a.project_id).map((a) => a.project_id!))
 return projects.filter((p) => ids.has(p.id)).slice(0, 20) // cap at 20 rows
 }, [assignments, projects])

 // Max count for color scaling
 const maxCount = useMemo(() => {
 let m = 1
 for (const v of heatData.values()) m = Math.max(m, v)
 return m
 }, [heatData])

 if (activeProjects.length === 0) {
 return (
 <p className="text-[12px] text-muted-foreground italic py-6 text-center">
 Keine Projektbuchungen im gewählten Zeitraum.
 </p>
 )
 }

 return (
 <div className="overflow-x-auto">
 <div className="min-w-max">
 {/* Header row */}
 <div className="flex gap-px mb-px">
 <div className="w-36 shrink-0"/>
 {weeks.map((wk) => (
 <div
 key={wk}
 className="w-9 text-center text-[9px] text-muted-foreground font-medium truncate"
 >
 {weekLabel(wk)}
 </div>
 ))}
 </div>

 {/* Data rows */}
 {activeProjects.map((project) => (
 <div key={project.id} className="flex items-center gap-px mb-px">
 {/* Project label */}
 <div className="w-36 shrink-0 pr-2 flex items-center gap-1.5">
 <span className="font-mono text-[10px] text-primary font-semibold shrink-0">
 {project.code}
 </span>
 <span className="text-[10px] text-muted-foreground truncate">{project.name}</span>
 </div>

 {/* Heat cells */}
 {weeks.map((wk) => {
 const count = heatData.get(`${project.id}:${wk}`) ?? 0
 const intensity = count === 0 ? 0 : 0.15 + (count / maxCount) * 0.85
 const bg = count === 0 ?'#F0F0F0': interpolate('var(--primary)', intensity)
 return (
 <div
 key={wk}
 title={count > 0 ? `${project.code} · ${wk} · ${count} Einsatz${count !== 1 ?'e':''}` : undefined}
 className="w-9 h-6 rounded-sm flex items-center justify-center text-[9px] font-medium transition-colors"
 style={{
 backgroundColor: bg,
 color: intensity > 0.55 ?'white':'#666666',
 }}
 >
 {count > 0 ? count :''}
 </div>
 )
 })}
 </div>
 ))}

 {/* Legend */}
 <div className="flex items-center gap-2 mt-3 ml-36 pl-px">
 <span className="text-[10px] text-muted-foreground">weniger</span>
 {[0, 0.2, 0.4, 0.6, 0.8, 1].map((i) => (
 <div
 key={i}
 className="w-5 h-4 rounded-sm"
 style={{ backgroundColor: i === 0 ?'#F0F0F0': interpolate('var(--primary)', 0.15 + i * 0.85) }}
 />
 ))}
 <span className="text-[10px] text-muted-foreground">mehr</span>
 </div>
 </div>
 </div>
 )
}
