import type { StoryGroup } from '../types/jira'
import type { DashboardConfig } from '../lib/dashboardConfig'
import type { LandingEstimate } from '../lib/executiveLanding'
import { computeMacroPipelineHealth } from '../lib/macroTrafficLight'
import { assigneeOpenLoadRadar } from '../lib/assigneeRadar'
import { countOpenGapsByBadge } from '../lib/functionalGaps'
import { calendarDelayVsLastMilestone } from '../lib/scheduleDelay'
import { resolveWorkBucketFromIssue } from '../lib/statusBuckets'

type Props = {
  groups: StoryGroup[]
  dashboardCfg: DashboardConfig
  landing: LandingEstimate
  finalMilestoneIso: string | null
}

function trafficLightClasses(light: 'green' | 'amber' | 'red'): { ring: string; bg: string; dot: string } {
  switch (light) {
    case 'green':
      return {
        ring: 'ring-emerald-400/50',
        bg: 'bg-emerald-500/20',
        dot: 'bg-emerald-400 shadow-[0_0_14px_rgba(52,211,153,0.7)]',
      }
    case 'amber':
      return {
        ring: 'ring-amber-400/55',
        bg: 'bg-amber-500/20',
        dot: 'bg-amber-400 shadow-[0_0_14px_rgba(251,191,36,0.65)]',
      }
    case 'red':
      return {
        ring: 'ring-rose-500/60',
        bg: 'bg-rose-600/25',
        dot: 'bg-rose-500 shadow-[0_0_16px_rgba(244,63,94,0.75)]',
      }
  }
}

export function MacroCockpitStrip({ groups, dashboardCfg, landing, finalMilestoneIso }: Props) {
  const macro = computeMacroPipelineHealth(
    groups,
    dashboardCfg.statusBuckets,
    dashboardCfg.laneLabels,
    dashboardCfg.functionalGaps,
  )
  const delay = calendarDelayVsLastMilestone(landing, finalMilestoneIso)
  const radar = assigneeOpenLoadRadar(
    groups,
    dashboardCfg.statusBuckets,
    dashboardCfg.wipSlotsPerDev,
  ).slice(0, 6)
  const gaps = countOpenGapsByBadge(groups, dashboardCfg.functionalGaps, dashboardCfg.statusBuckets)

  const openSamples = groups
    .flatMap((g) =>
      g.subtasks
        .filter((st) => {
          const b = resolveWorkBucketFromIssue(st, dashboardCfg.statusBuckets)
          return b === 'in_progress' || b === 'blocked'
        })
        .map((st) => ({
          key: st.key,
          who: st.fields.assignee?.displayName ?? '—',
          summary: st.fields.summary,
        })),
    )
    .slice(0, 5)

  const cls = trafficLightClasses(macro.light)

  return (
    <section className="rounded-2xl border border-white/[0.08] bg-gradient-to-br from-slate-950/90 to-slate-900/40 p-4 shadow-[0_12px_48px_rgba(0,0,0,0.35)] backdrop-blur-xl sm:p-5">
      <div className="mb-3 flex flex-wrap items-center justify-between gap-2">
        <h2 className="text-xs font-semibold uppercase tracking-[0.2em] text-slate-400">
          Cockpit macro — DSI · Projet · PO · Exécution
        </h2>
        <span className="text-[10px] text-slate-500">
          Données = instantané Jira au dernier chargement (Actualiser).
        </span>
      </div>

      <div className="grid gap-4 lg:grid-cols-12">
        <div
          className={`lg:col-span-4 rounded-xl border border-white/10 p-4 ring-2 ring-inset ${cls.ring} ${cls.bg}`}
        >
          <p className="text-[10px] font-semibold uppercase tracking-wide text-slate-400">
            Feux phases (DSI)
          </p>
          <div className="mt-2 flex items-start gap-3">
            <span
              className={`mt-0.5 h-4 w-4 shrink-0 rounded-full ${cls.dot}`}
              title={macro.title}
              aria-hidden
            />
            <div className="min-w-0">
              <p className="text-sm font-semibold text-white">{macro.title}</p>
              <p className="mt-1 text-xs leading-relaxed text-slate-300">{macro.detail}</p>
              {macro.violatingStoryKeys.length > 0 && (
                <p className="mt-2 font-mono text-[11px] text-rose-200/90">
                  {macro.violatingStoryKeys.join(', ')}
                </p>
              )}
            </div>
          </div>
        </div>

        <div className="lg:col-span-4 rounded-xl border border-white/10 bg-black/20 p-4">
          <p className="text-[10px] font-semibold uppercase tracking-wide text-slate-400">
            Jalons &amp; vélocité (Directeur de projet)
          </p>
          {delay ? (
            <p className="mt-2 text-sm font-medium text-amber-100">{delay.message}</p>
          ) : (
            <p className="mt-2 text-sm text-slate-300">
              Aucun retard calendaire détecté par rapport au dernier jalon (ou date / vélocité
              indisponible).
            </p>
          )}
          <p className="mt-2 text-[11px] text-slate-500">
            {landing.businessDaysToFinish != null
              ? `~${landing.businessDaysToFinish} j. ouvrés restants (sous-tâches), vélocité ajustée effectif / baseline.`
              : 'Vélocité nulle ou données insuffisantes pour estimer la fin.'}
          </p>
        </div>

        <div className="lg:col-span-4 rounded-xl border border-white/10 bg-black/20 p-4">
          <p className="text-[10px] font-semibold uppercase tracking-wide text-slate-400">
            Écarts fonctionnels (PO)
          </p>
          <ul className="mt-2 flex flex-wrap gap-2">
            {gaps.map((g) => (
              <li
                key={g.id}
                className={`rounded-full px-2.5 py-1 text-[11px] font-medium ring-1 ring-inset ${
                  g.criticalFlow
                    ? 'bg-rose-500/15 text-rose-100 ring-rose-400/40'
                    : 'bg-slate-600/30 text-slate-200 ring-slate-500/35'
                }`}
                title="Sous-tâches encore ouvertes sur les stories correspondant aux termes configurés."
              >
                {g.label}
                <span className="ml-1 tabular-nums opacity-90">({g.openCount})</span>
              </li>
            ))}
          </ul>
        </div>

        <div className="lg:col-span-6 rounded-xl border border-white/10 bg-black/20 p-4">
          <p className="text-[10px] font-semibold uppercase tracking-wide text-slate-400">
            Radar de charge (Chef de projet)
          </p>
          <p className="mt-1 text-[10px] text-slate-500">
            Plafond WIP : {dashboardCfg.wipSlotsPerDev} sous-tâches ouvertes / personne.
          </p>
          <ul className="mt-2 space-y-1.5 text-xs">
            {radar.length === 0 ? (
              <li className="text-slate-500">Aucune sous-tâche ouverte.</li>
            ) : (
              radar.map((r) => (
                <li
                  key={r.name}
                  className={`flex justify-between gap-2 rounded-lg px-2 py-1 ${
                    r.overload ? 'bg-rose-500/15 text-rose-100' : 'bg-white/[0.04] text-slate-200'
                  }`}
                >
                  <span className="truncate">{r.name}</span>
                  <span className="shrink-0 tabular-nums font-semibold">
                    {r.openCount}
                    {r.overload ? ' ⚠' : ''}
                  </span>
                </li>
              ))
            )}
          </ul>
        </div>

        <div className="lg:col-span-6 rounded-xl border border-white/10 bg-black/20 p-4">
          <p className="text-[10px] font-semibold uppercase tracking-wide text-slate-400">
            En cours (aperçu)
          </p>
          <ul className="mt-2 space-y-1.5 text-[11px] text-slate-300">
            {openSamples.length === 0 ? (
              <li className="text-slate-500">Aucun ticket « en cours » ou « bloqué ».</li>
            ) : (
              openSamples.map((x) => (
                <li key={x.key} className="truncate" title={x.summary}>
                  <span className="font-mono text-cyan-300/90">{x.key}</span>{' '}
                  <span className="text-slate-500">·</span> {x.who}
                </li>
              ))
            )}
          </ul>
        </div>
      </div>
    </section>
  )
}
