'use client'
// src/components/analyses/AmplitudePanel.tsx
// Input: project: Project
// Output: amplitude envelope chart with multi-series + stats row + legend
// Rationale: US12 — 7-day amplitude per sensor with series visibility toggle

import { useMemo, useState } from 'react'
import { motion } from 'framer-motion'
import { Stat } from '@/components/ui/Stat'
import { LineChart } from '@/components/charts/LineChart'
import { getSensorsForProject, generateAmplitudeEnvelope } from '@/lib/mock'
import type { Project, DataSeries } from '@/types'

interface AmplitudePanelProps {
  project: Project
}

const SERIES_COLORS = ['#3DB8E8', '#2DD4BF', '#818CF8'] as const

export function AmplitudePanel({ project }: AmplitudePanelProps) {
  const sensors = useMemo(
    () => getSensorsForProject(project.id).filter((s) => s.kind === 'accelerometer').slice(0, 3),
    [project.id]
  )

  const allSeries: DataSeries[] = useMemo(
    () =>
      sensors.map((s, i) => ({
        name: s.label,
        color: SERIES_COLORS[i % SERIES_COLORS.length],
        points: generateAmplitudeEnvelope(s.id, s.kind, 7).points,
      })),
    [sensors]
  )

  const [hidden, setHidden] = useState<Set<string>>(new Set())

  const visibleSeries = useMemo(
    () => allSeries.filter((s) => !hidden.has(s.name)),
    [allSeries, hidden]
  )

  const stats = useMemo(() => {
    const allPoints = allSeries.flatMap((s) => s.points.map((p) => p.y))
    if (allPoints.length === 0) return { rms: 0, peak: 0, domFreq: 2.3, peaks: 0 }
    const rms = Math.sqrt(allPoints.reduce((acc, v) => acc + v * v, 0) / allPoints.length)
    const peak = Math.max(...allPoints)
    const threshold = rms * 2.5
    const peaks = allPoints.filter((v) => v > threshold).length
    return {
      rms: Math.round(rms * 1000) / 1000,
      peak: Math.round(peak * 1000) / 1000,
      domFreq: 2.3,
      peaks,
    }
  }, [allSeries])

  function toggleSeries(name: string) {
    setHidden((prev) => {
      const next = new Set(prev)
      if (next.has(name)) next.delete(name)
      else next.add(name)
      return next
    })
  }

  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 flex-col gap-4"
    >
      {/* Stats row */}
      <div className="grid grid-cols-4 gap-3">
        <div className="bg-bg-elevated border border-bg-border rounded-lg p-3">
          <Stat label="RMS moyen" value={stats.rms} unit="mm/s²" digits={3} />
        </div>
        <div className="bg-bg-elevated border border-bg-border rounded-lg p-3">
          <Stat label="Pic max" value={stats.peak} unit="mm/s²" digits={3} />
        </div>
        <div className="bg-bg-elevated border border-bg-border rounded-lg p-3">
          <Stat label="Fréq. dominante" value={stats.domFreq} unit="Hz" digits={2} />
        </div>
        <div className="bg-bg-elevated border border-bg-border rounded-lg p-3">
          <Stat label="Nb de pics" value={stats.peaks} digits={0} />
        </div>
      </div>

      {/* Chart */}
      <div className="bg-bg-elevated border border-bg-border rounded-lg p-4">
        <div className="mb-3 flex items-center justify-between">
          <span className="text-body-sm text-text-secondary font-medium">
            Amplitude vibratoire — 7 derniers jours
          </span>
          <span className="text-caption text-text-muted">mm/s²</span>
        </div>
        {visibleSeries.length > 0 ? (
          <LineChart
            series={visibleSeries}
            height={360}
            showGrid
            showAxis
          />
        ) : (
          <div className="flex items-center justify-center h-[360px] text-text-muted text-caption">
            Toutes les séries sont masquées
          </div>
        )}

        {/* Legend */}
        <div className="mt-4 flex items-center gap-4 flex-wrap">
          {allSeries.map((s) => {
            const isHidden = hidden.has(s.name)
            return (
              <button
                key={s.name}
                onClick={() => toggleSeries(s.name)}
                className="flex items-center gap-1.5 text-caption transition-opacity duration-fast"
                style={{ opacity: isHidden ? 0.4 : 1 }}
              >
                <span
                  className="w-2 h-2 rounded-full flex-shrink-0"
                  style={{ backgroundColor: s.color }}
                />
                <span className="text-text-secondary">{s.name}</span>
                <span className="text-text-muted text-[10px] ml-0.5">
                  {isHidden ? '(masqué)' : ''}
                </span>
              </button>
            )
          })}
        </div>
      </div>
    </motion.div>
  )
}
