'use client'

import Link from 'next/link'
import { CheckCircle2, AlertTriangle } from 'lucide-react'
import { cn } from '@/lib/utils'
import type { BacklogHealth, StuckTask } from '@/lib/insights/backlog-health'

interface Props {
  data: BacklogHealth
}

function Counter({ count, label }: { count: number; label: string }) {
  const ok = count === 0
  return (
    <div className="flex items-center gap-2 rounded-md border border-border px-3 py-2 text-sm">
      {ok ? (
        <CheckCircle2 className="size-4 text-status-done shrink-0" />
      ) : (
        <AlertTriangle className="size-4 text-priority-medium shrink-0" />
      )}
      <span className={cn('font-semibold', ok && 'text-status-done')}>{count}</span>
      <span className="text-muted-foreground">{label}</span>
    </div>
  )
}

function StuckRow({ task }: { task: StuckTask }) {
  const severity =
    task.daysStuck >= 14
      ? 'bg-priority-critical/10 text-priority-critical'
      : task.daysStuck >= 7
        ? 'bg-priority-high/10 text-priority-high'
        : ''
  return (
    <tr className="border-b border-border last:border-0">
      <td className="py-1 pr-2">
        <Link
          href={`/products/${task.productId}/solo?task=${task.taskId}`}
          className="text-primary underline line-clamp-1"
        >
          {task.title}
        </Link>
      </td>
      <td className="py-1 pr-2 text-muted-foreground whitespace-nowrap">
        {task.productName}
      </td>
      <td className={cn('py-1 px-2 text-right whitespace-nowrap rounded font-medium', severity)}>
        {task.daysStuck}d
      </td>
      <td className="py-1 pl-2 text-muted-foreground whitespace-nowrap">
        {task.sprintGoal ?? '—'}
      </td>
    </tr>
  )
}

export function BacklogHealthCard({ data }: Props) {
  const { storiesWithoutAc, tasksWithoutPlan, stuckTasks } = data
  const allClear =
    storiesWithoutAc === 0 && tasksWithoutPlan === 0 && stuckTasks.length === 0

  return (
    <div className="rounded-lg border border-border p-4 space-y-3">
      <h2 className="text-sm font-medium">Backlog health</h2>

      <div className="flex flex-wrap gap-2">
        <Counter count={storiesWithoutAc} label="stories zonder AC" />
        <Counter count={tasksWithoutPlan} label="tasks zonder plan" />
        <Counter count={stuckTasks.length} label="stuck > 7d" />
      </div>

      {allClear ? (
        <p className="text-sm text-status-done">Geen stuck tasks 🎉</p>
      ) : stuckTasks.length > 0 ? (
        <div>
          <p className="text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-1">
            Stuck tasks (top {stuckTasks.length})
          </p>
          <table className="w-full text-sm">
            <tbody>
              {stuckTasks.map(t => (
                <StuckRow key={t.taskId} task={t} />
              ))}
            </tbody>
          </table>
        </div>
      ) : null}
    </div>
  )
}
