'use client'
// src/components/analyses/HeatmapPanel.tsx
// Input: project: Project
// Output: heatmap of anomaly criticality over time + top anomalous sensors
// Rationale: US14 — 24h × 10 sensors grid seeded per project

import { useMemo } from 'react'
import { motion } from 'framer-motion'
import { Heatmap } from '@/components/charts/Heatmap'
import { Badge } from '@/components/ui/Badge'
import { StatusDot } from '@/components/ui/StatusDot'
import { getSensorsForProject } from '@/lib/mock'
import type { Project } from '@/types'

interface HeatmapPanelProps {
  project: Project
}

// Seedable LCG for reproducible matrix
function seededRng(seed: string) {
  let h = 2166136261
  for (let i = 0; i < seed.length; i++) {
    h ^= seed.charCodeAt(i)
    h = Math.imul(h, 16777619) >>> 0
  }
  return () => {
    h ^= h << 13
    h ^= h >> 17
    h ^= h << 5
    h = h >>> 0
    return h / 4294967296
  }
}

function generateMatrix(projectId: string, rows: number, cols: number): number[][] {
  const rng = seededRng(projectId + 'heatmap')

  // Decide hotspot positions (2-3 hotspots)
  const hotspots = [
    { r: Math.floor(rng() * rows), cStart: Math.floor(rng() * (cols - 6)) },
    { r: Math.floor(rng() * rows), cStart: Math.floor(rng() * (cols - 4)) },
  ]

  return Array.from({ length: rows }, (_, r) =>
    Array.from({ length: cols }, (_, c) => {
      const base = rng() * 25 // 0-25 baseline noise
      let hotVal = 0
      for (const hs of hotspots) {
        if (r === hs.r && c >= hs.cStart && c < hs.cStart + 5) {
          const dist = Math.abs(c - (hs.cStart + 2))
          hotVal = Math.max(hotVal, 60 + rng() * 40 - dist * 8)
        }
      }
      return Math.round(Math.min(100, base + hotVal))
    })
  )
}

const HOURS = Array.from({ length: 24 }, (_, i) => `${String(i).padStart(2, '0')}h`)

function scoreToSeverity(score: number): 'info' | 'warning' | 'critical' {
  if (score >= 70) return 'critical'
  if (score >= 40) return 'warning'
  return 'info'
}

export function HeatmapPanel({ project }: HeatmapPanelProps) {
  const sensors = useMemo(
    () => getSensorsForProject(project.id).slice(0, 10),
    [project.id]
  )

  const rows = useMemo(() => sensors.map((s) => s.label), [sensors])
  const cols = HOURS

  const matrix = useMemo(
    () => generateMatrix(project.id, rows.length, cols.length),
    [project.id, rows.length, cols.length]
  )

  // Normalize matrix to 0-1 for Heatmap component
  const normalizedMatrix = useMemo(
    () => matrix.map((row) => row.map((v) => v / 100)),
    [matrix]
  )

  // Top 5 anomalous sensors
  const topSensors = useMemo(() => {
    return rows
      .map((label, i) => {
        const rowData = matrix[i] ?? []
        const maxVal = Math.max(...rowData)
        const avgVal = rowData.reduce((a, b) => a + b, 0) / rowData.length
        return { label, maxVal, avgVal, sensorId: sensors[i]?.id ?? '' }
      })
      .sort((a, b) => b.maxVal - a.maxVal)
      .slice(0, 5)
  }, [rows, matrix, sensors])

  return (
    <motion.div
      initial={{ opacity: 0, y: 8 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.25, ease: [0.16, 1, 0.3, 1] }}
      className="flex gap-4"
    >
      {/* Heatmap main */}
      <div className="flex-1 bg-bg-elevated border border-bg-border rounded-lg p-4">
        <div className="mb-4 flex items-center justify-between">
          <span className="text-body-sm text-text-secondary font-medium">
            Anomalies — criticité par capteur × heure (24h)
          </span>
          <span className="text-caption text-text-muted">score 0–100</span>
        </div>

        {rows.length > 0 ? (
          <Heatmap
            matrix={normalizedMatrix}
            rows={rows}
            cols={cols}
            cellSize={28}
          />
        ) : (
          <div className="flex items-center justify-center h-64 text-text-muted text-caption">
            Aucun capteur disponible
          </div>
        )}

        {/* Legend */}
        <div className="mt-4 flex items-center gap-3">
          <span className="text-caption text-text-muted">Intensité :</span>
          <div className="flex items-center gap-1">
            {[0, 20, 40, 60, 80, 100].map((v) => (
              <div key={v} className="flex flex-col items-center gap-0.5">
                <div
                  className="w-5 h-3 rounded-sm"
                  style={{
                    backgroundColor: `hsl(${210 - v * 1.8}, ${30 + v * 0.7}%, ${55 - v * 0.25}%)`,
                  }}
                />
                <span className="text-[9px] text-text-muted">{v}</span>
              </div>
            ))}
          </div>
          <span className="text-caption text-text-muted ml-1">→ critique</span>
        </div>
      </div>

      {/* Side: top 5 sensors */}
      <div className="w-64 flex flex-col gap-3">
        <div className="bg-bg-elevated border border-bg-border rounded-lg p-4">
          <div className="text-caption text-text-muted uppercase tracking-[0.05em] mb-3">
            Top 5 capteurs anomaux
          </div>
          <div className="flex flex-col gap-2">
            {topSensors.map((s, i) => {
              const sev = scoreToSeverity(s.maxVal)
              return (
                <div
                  key={s.sensorId}
                  className="flex items-center justify-between py-1.5 border-b border-bg-border last:border-0"
                >
                  <div className="flex items-center gap-2 min-w-0">
                    <span className="text-caption text-text-muted flex-shrink-0">#{i + 1}</span>
                    <StatusDot
                      status={sev === 'critical' ? 'critical' : sev === 'warning' ? 'warning' : 'online'}
                      size="sm"
                    />
                    <span className="text-caption text-text-primary truncate">{s.label}</span>
                  </div>
                  <div className="flex items-center gap-1.5 flex-shrink-0">
                    <Badge
                      variant={sev === 'critical' ? 'danger' : sev === 'warning' ? 'warning' : 'info'}
                      size="xs"
                    >
                      {s.maxVal}
                    </Badge>
                  </div>
                </div>
              )
            })}
          </div>
        </div>

        <div className="bg-bg-elevated border border-bg-border rounded-lg p-4">
          <div className="text-caption text-text-muted uppercase tracking-[0.05em] mb-3">
            Distribution
          </div>
          {[
            { label: 'Normal (0–39)', count: matrix.flat().filter((v) => v < 40).length, variant: 'info' as const },
            { label: 'Alerte (40–69)', count: matrix.flat().filter((v) => v >= 40 && v < 70).length, variant: 'warning' as const },
            { label: 'Critique (70+)', count: matrix.flat().filter((v) => v >= 70).length, variant: 'danger' as const },
          ].map(({ label, count, variant }) => (
            <div key={label} className="flex items-center justify-between py-1 text-caption">
              <span className="text-text-secondary">{label}</span>
              <Badge variant={variant} size="xs">{count}</Badge>
            </div>
          ))}
        </div>
      </div>
    </motion.div>
  )
}
