'use client'
// src/components/projects/ProjectCard.tsx
// Input: project: Project, index for stagger delay
// Output: animated card with type visual, stats, sparkline, and link to detail
// Rationale: primary unit of the projects grid

import Link from 'next/link'
import { motion } from 'framer-motion'
import { Waypoints, Building2, ArrowRight, Radio, TriangleAlert } from 'lucide-react'
import { Badge } from '@/components/ui/Badge'
import { StatusDot } from '@/components/ui/StatusDot'
import { SparkLine } from '@/components/charts/SparkLine'
import { relativeTime } from '@/lib/utils'
import { generateAmplitudeEnvelope, getSensorsForProject } from '@/lib/mock'
import { cn } from '@/lib/utils'
import type { Project } from '@/types'

// ── Helpers ──────────────────────────────────────────────────────────────────

const typeLabel: Record<Project['type'], string> = {
  bridge: 'Pont',
  building: 'Bâtiment',
}

const statusLabel: Record<Project['status'], string> = {
  active: 'Actif',
  monitoring: 'Surveillance',
  alert: 'Alerte',
  archived: 'Archivé',
}

const statusVariant: Record<Project['status'], 'success' | 'info' | 'danger' | 'neutral'> = {
  active: 'success',
  monitoring: 'info',
  alert: 'danger',
  archived: 'neutral',
}

const statusDot: Record<Project['status'], 'online' | 'info' | 'critical' | 'offline'> = {
  active: 'online',
  monitoring: 'info',
  alert: 'critical',
  archived: 'offline',
}

const criticalityVariant: Record<Project['criticality'], 'success' | 'info' | 'warning' | 'danger'> = {
  low: 'success',
  medium: 'info',
  high: 'warning',
  critical: 'danger',
}

const criticalityLabel: Record<Project['criticality'], string> = {
  low: 'Faible',
  medium: 'Modérée',
  high: 'Haute',
  critical: 'Critique',
}

// Gradient backgrounds by type (fallback when no coverImage)
const typeGradient: Record<Project['type'], string> = {
  bridge: 'from-[#0F2A4A] via-[#0F2035] to-[#080C12]',
  building: 'from-[#1A2F1A] via-[#122012] to-[#080C12]',
}

// ── Sparkline data (30 points from amplitude envelope) ────────────────────────

function getSparkPoints(project: Project): number[] {
  const sensors = getSensorsForProject(project.id)
  if (sensors.length === 0) {
    // Fallback: seeded pattern from project id
    return Array.from({ length: 30 }, (_, i) => {
      const t = i / 29
      return 0.3 + Math.sin(t * Math.PI * 4 + project.id.charCodeAt(5) * 0.1) * 0.15 + Math.random() * 0.05
    })
  }
  const sensor = sensors[0]
  const envelope = generateAmplitudeEnvelope(sensor.id, sensor.kind, 1)
  // Sample 30 evenly-spaced points
  const pts = envelope.points
  const step = Math.max(1, Math.floor(pts.length / 30))
  return Array.from({ length: 30 }, (_, i) => pts[Math.min(i * step, pts.length - 1)].y)
}

// ── SparkLine color by status ────────────────────────────────────────────────

const sparkColor: Record<Project['status'], string> = {
  active: '#34D399',
  monitoring: '#60A5FA',
  alert: '#F87171',
  archived: '#4E6070',
}

// ── Card component ───────────────────────────────────────────────────────────

interface ProjectCardProps {
  project: Project
  index?: number
}

export function ProjectCard({ project, index = 0 }: ProjectCardProps) {
  const sparkPoints = getSparkPoints(project)
  const isAlert = project.status === 'alert'

  return (
    <motion.div
      initial={{ opacity: 0, y: 16 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{
        duration: 0.4,
        delay: index * 0.05,
        ease: [0.16, 1, 0.3, 1],
      }}
      whileHover={{ y: -2 }}
    >
      <Link href={`/projects/${project.id}`} className="block h-full group">
        <div
          className={cn(
            'relative h-full flex flex-col rounded-lg border overflow-hidden',
            'bg-bg-elevated shadow-md',
            'transition-all duration-[150ms]',
            'group-hover:border-accent-border group-hover:shadow-[0_4px_20px_rgba(0,0,0,0.5),0_0_12px_rgba(61,184,232,0.12)]',
            isAlert ? 'border-l-[3px] border-l-status-danger border-bg-border' : 'border-bg-border',
          )}
        >
          {/* Visual header — gradient + type icon */}
          <div className={cn('relative h-[72px] bg-gradient-to-br flex items-center px-4 gap-3 shrink-0', typeGradient[project.type])}>
            <span className="p-2 rounded-md bg-bg-overlay/60 border border-bg-border/60">
              {project.type === 'bridge' ? (
                <Waypoints size={18} strokeWidth={1.5} className="text-accent" />
              ) : (
                <Building2 size={18} strokeWidth={1.5} className="text-[#34D399]" />
              )}
            </span>
            <div className="flex-1 min-w-0">
              <h2 className="text-[14px] font-semibold leading-snug text-text-primary truncate">
                {project.name}
              </h2>
              <p className="text-caption text-text-muted truncate">{project.location}</p>
            </div>
            {/* Alert indicator pulse */}
            {isAlert && (
              <span className="shrink-0">
                <TriangleAlert size={14} strokeWidth={1.5} className="text-status-danger" />
              </span>
            )}
          </div>

          {/* Body */}
          <div className="flex flex-col flex-1 p-4 gap-3">
            {/* Badges row */}
            <div className="flex items-center gap-1.5 flex-wrap">
              <Badge variant="accent" size="xs">
                {typeLabel[project.type]}
              </Badge>
              <Badge variant={statusVariant[project.status]} size="xs">
                <StatusDot status={statusDot[project.status]} size="sm" />
                <span className="ml-0.5">{statusLabel[project.status]}</span>
              </Badge>
              <Badge variant={criticalityVariant[project.criticality]} size="xs">
                {criticalityLabel[project.criticality]}
              </Badge>
            </div>

            {/* Mini-stats row */}
            <div className="grid grid-cols-3 gap-2">
              {/* Sensors */}
              <div className="flex flex-col gap-0.5">
                <span className="text-label text-text-muted uppercase tracking-[0.05em]">
                  Capteurs
                </span>
                <span className="font-mono text-[13px] text-text-primary leading-5">
                  <span className={cn(
                    project.sensorsOnline < project.sensorsCount ? 'text-status-warning' : 'text-status-success'
                  )}>
                    {project.sensorsOnline}
                  </span>
                  <span className="text-text-muted">/{project.sensorsCount}</span>
                </span>
              </div>

              {/* Anomalies */}
              <div className="flex flex-col gap-0.5">
                <span className="text-label text-text-muted uppercase tracking-[0.05em]">
                  Anomalies
                </span>
                <span className={cn(
                  'font-mono text-[13px] leading-5',
                  project.anomaliesCount > 0 ? 'text-status-danger' : 'text-status-success'
                )}>
                  {project.anomaliesCount}
                </span>
              </div>

              {/* Last measurement */}
              <div className="flex flex-col gap-0.5">
                <span className="text-label text-text-muted uppercase tracking-[0.05em]">
                  Dernière mesure
                </span>
                <span className="font-mono text-[11px] text-text-secondary leading-5">
                  {relativeTime(project.lastMeasurementAt)}
                </span>
              </div>
            </div>

            {/* SparkLine */}
            <div className="flex items-center justify-between gap-2 pt-1 border-t border-bg-border">
              <div className="flex items-center gap-1.5">
                <Radio size={11} strokeWidth={1.5} className="text-text-muted" />
                <span className="text-[10px] text-text-muted">Activité 24h</span>
              </div>
              <SparkLine
                points={sparkPoints}
                width={96}
                height={22}
                color={sparkColor[project.status]}
              />
            </div>
          </div>

          {/* Footer */}
          <div className="flex items-center justify-end px-4 py-2.5 border-t border-bg-border bg-bg-base/40">
            <span className="flex items-center gap-1 text-caption text-text-muted group-hover:text-accent transition-colors duration-fast">
              Voir le projet
              <ArrowRight size={12} strokeWidth={1.5} />
            </span>
          </div>
        </div>
      </Link>
    </motion.div>
  )
}
