'use client'
// src/components/analyses/TimelinePanel.tsx
// Input: project: Project
// Output: vertical timeline of events with stagger animation
// Rationale: US15 — chronological event history with severity, label, timestamp

import { useMemo } from 'react'
import { motion } from 'framer-motion'
import { getAnomaliesForProject, getAnalysesForProject } from '@/lib/mock'
import { StatusDot } from '@/components/ui/StatusDot'
import { Badge } from '@/components/ui/Badge'
import { Button } from '@/components/ui/Button'
import { relativeTime } from '@/lib/utils'
import { ChevronRight, Wrench, RefreshCw, Cpu } from 'lucide-react'
import type { Project, TimelineEvent } from '@/types'
import type { DotStatus } from '@/components/ui/StatusDot'
import type { BadgeVariant } from '@/components/ui/Badge'

interface TimelinePanelProps {
  project: Project
}

interface EnrichedEvent {
  ts: string
  severity: 'info' | 'warning' | 'critical'
  label: string
  sensorId?: string
  source: 'anomaly' | 'system'
}

function severityToDotStatus(s: EnrichedEvent['severity']): DotStatus {
  if (s === 'critical') return 'critical'
  if (s === 'warning') return 'warning'
  return 'info'
}

function severityToBadge(s: EnrichedEvent['severity']): BadgeVariant {
  if (s === 'critical') return 'danger'
  if (s === 'warning') return 'warning'
  return 'info'
}

// Synthetic system events injected per project
const SYSTEM_EVENTS: Record<string, EnrichedEvent[]> = {
  'proj-001': [
    { ts: '2026-04-03T09:15:00Z', severity: 'info', label: 'Mise à jour firmware capteurs v3.1.2', source: 'system' },
    { ts: '2026-03-28T14:00:00Z', severity: 'info', label: 'Reset capteur sens-001-03 — recalibration', source: 'system' },
  ],
  'proj-002': [
    { ts: '2026-04-05T11:00:00Z', severity: 'info', label: 'Inspection terrain — technicien J.Morin', source: 'system' },
    { ts: '2026-03-30T08:00:00Z', severity: 'info', label: 'Mise à jour firmware capteurs v3.0.9', source: 'system' },
  ],
  'proj-005': [
    { ts: '2026-04-06T09:30:00Z', severity: 'info', label: 'Inspection bâtiment — technicien C.Dubois', source: 'system' },
    { ts: '2026-04-02T16:00:00Z', severity: 'info', label: 'Reset baseline après travaux intérieurs', source: 'system' },
  ],
  'proj-007': [
    { ts: '2026-04-01T10:00:00Z', severity: 'info', label: 'Mise à jour firmware capteurs v3.1.0', source: 'system' },
  ],
  'proj-009': [
    { ts: '2026-04-04T13:00:00Z', severity: 'info', label: 'Vérification capteurs après crue — OK', source: 'system' },
    { ts: '2026-03-31T09:00:00Z', severity: 'info', label: 'Mise à jour firmware capteurs v3.1.1', source: 'system' },
  ],
}

function getSystemEvents(projectId: string): EnrichedEvent[] {
  return SYSTEM_EVENTS[projectId] ?? []
}

export function TimelinePanel({ project }: TimelinePanelProps) {
  const events = useMemo((): EnrichedEvent[] => {
    const analyses = getAnalysesForProject(project.id)
    const timelineAnalysis = analyses.find((a) => a.kind === 'timeline')
    const analysisEvents: EnrichedEvent[] = (timelineAnalysis?.events ?? []).map((e: TimelineEvent) => ({
      ...e,
      source: 'anomaly' as const,
    }))

    const anomalies = getAnomaliesForProject(project.id)
    const anomalyEvents: EnrichedEvent[] = anomalies.map((a) => ({
      ts: a.detectedAt,
      severity: a.severity,
      label: a.description,
      sensorId: a.sensorId,
      source: 'anomaly' as const,
    }))

    const systemEvents = getSystemEvents(project.id)

    const allEvents = [...analysisEvents, ...anomalyEvents, ...systemEvents]

    // Deduplicate by ts + label
    const seen = new Set<string>()
    const deduped = allEvents.filter((e) => {
      const key = `${e.ts}::${e.label}`
      if (seen.has(key)) return false
      seen.add(key)
      return true
    })

    return deduped.sort((a, b) => new Date(b.ts).getTime() - new Date(a.ts).getTime())
  }, [project.id])

  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"
    >
      {/* Timeline list */}
      <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">
            Historique des événements
          </span>
          <span className="text-caption text-text-muted">{events.length} événements</span>
        </div>

        <div className="relative">
          {/* Vertical line */}
          <div className="absolute left-[15px] top-0 bottom-0 w-px bg-bg-border" />

          <div className="flex flex-col gap-0">
            {events.map((event, i) => (
              <motion.div
                key={`${event.ts}-${i}`}
                initial={{ opacity: 0, x: -8 }}
                animate={{ opacity: 1, x: 0 }}
                transition={{
                  duration: 0.3,
                  delay: i * 0.05,
                  ease: [0.16, 1, 0.3, 1],
                }}
                className="relative flex items-start gap-4 pl-10 pb-5 last:pb-0"
              >
                {/* Dot on timeline */}
                <div className="absolute left-[11px] top-[3px]">
                  <StatusDot status={severityToDotStatus(event.severity)} size="sm" />
                </div>

                {/* Content */}
                <div className="flex-1 flex items-start justify-between gap-3 min-w-0">
                  <div className="flex flex-col gap-1 min-w-0">
                    <div className="flex items-center gap-2 flex-wrap">
                      <Badge variant={severityToBadge(event.severity)} size="xs">
                        {event.severity === 'critical' ? 'Critique' : event.severity === 'warning' ? 'Alerte' : 'Info'}
                      </Badge>
                      {event.source === 'system' && (
                        <Badge variant="neutral" size="xs">Système</Badge>
                      )}
                    </div>
                    <span className="text-body text-text-primary leading-snug">{event.label}</span>
                    {event.sensorId && (
                      <span className="font-mono-small text-text-muted">{event.sensorId}</span>
                    )}
                  </div>
                  <div className="flex items-center gap-2 flex-shrink-0">
                    <span className="font-mono-small text-text-muted whitespace-nowrap">
                      {relativeTime(event.ts)}
                    </span>
                    <button className="text-text-muted hover:text-text-secondary transition-colors duration-fast">
                      <ChevronRight size={14} strokeWidth={1.5} />
                    </button>
                  </div>
                </div>
              </motion.div>
            ))}
          </div>
        </div>

        {events.length === 0 && (
          <div className="flex items-center justify-center h-40 text-text-muted text-caption">
            Aucun événement enregistré
          </div>
        )}
      </div>

      {/* Side legend */}
      <div className="w-56 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">
            Légende
          </div>
          <div className="flex flex-col gap-2">
            {[
              { status: 'critical' as const, label: 'Critique', variant: 'danger' as const },
              { status: 'warning' as const, label: 'Alerte', variant: 'warning' as const },
              { status: 'info' as const, label: 'Information', variant: 'info' as const },
            ].map(({ status, label }) => (
              <div key={status} className="flex items-center gap-2">
                <StatusDot status={status} size="sm" />
                <span className="text-caption text-text-secondary">{label}</span>
              </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">
            Sources
          </div>
          <div className="flex flex-col gap-2">
            <div className="flex items-center gap-2">
              <Wrench size={12} strokeWidth={1.5} className="text-text-muted" />
              <span className="text-caption text-text-secondary">Anomalies capteurs</span>
            </div>
            <div className="flex items-center gap-2">
              <RefreshCw size={12} strokeWidth={1.5} className="text-text-muted" />
              <span className="text-caption text-text-secondary">Resets &amp; calibrations</span>
            </div>
            <div className="flex items-center gap-2">
              <Cpu size={12} strokeWidth={1.5} className="text-text-muted" />
              <span className="text-caption text-text-secondary">Mises à jour firmware</span>
            </div>
          </div>
        </div>

        <div className="mt-auto">
          <Button variant="secondary" size="sm" className="w-full" disabled>
            Exporter rapport PDF
          </Button>
        </div>
      </div>
    </motion.div>
  )
}
