'use client';

import { Activity } from 'lucide-react';

import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { computeDealHealth, type DealHealthInput } from '@/lib/services/deal-health';
import { cn } from '@/lib/utils';

const PULSE_TINT: Record<'cold' | 'warm' | 'hot', string> = {
  hot: 'border-emerald-200 bg-emerald-50 text-emerald-800',
  warm: 'border-amber-200 bg-amber-50 text-amber-800',
  cold: 'border-rose-200 bg-rose-50 text-rose-800',
};

const PULSE_LABEL: Record<'cold' | 'warm' | 'hot', string> = {
  hot: 'Hot',
  warm: 'Warm',
  cold: 'Cold',
};

/**
 * Header chip surfacing the rule-based deal-health score. The tooltip
 * exposes every signal that contributed to the score so the calculation is
 * transparent — stakeholders averse to AI black boxes can read exactly
 * which dates / stages drove the verdict.
 */
export function DealPulseChip({ interest }: { interest: DealHealthInput }) {
  // Closed / archived deals don't get a pulse — UX would be confusing.
  if (interest.archivedAt || interest.outcome) return null;

  const health = computeDealHealth(interest);
  const tint = PULSE_TINT[health.pulse];
  const label = PULSE_LABEL[health.pulse];

  return (
    <TooltipProvider>
      <Tooltip>
        <TooltipTrigger asChild>
          <span
            className={cn(
              'inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] font-medium cursor-help',
              tint,
            )}
            aria-label={`Deal pulse: ${label}, score ${health.score}/100`}
          >
            <Activity className="size-3" aria-hidden />
            {label} · {health.score}
          </span>
        </TooltipTrigger>
        <TooltipContent side="bottom" className="max-w-xs">
          <p className="font-semibold mb-1.5">
            Deal pulse — {label} ({health.score}/100)
          </p>
          {health.signals.length === 0 ? (
            <p className="text-xs">
              Baseline score (50) — nothing notable yet. Log contact or progress the stage to move
              the dial.
            </p>
          ) : (
            <ul className="space-y-1 text-xs">
              {health.signals.map((s) => (
                <li key={s.id} className="flex gap-2">
                  <span className={s.delta > 0 ? 'text-emerald-300' : 'text-rose-300'}>
                    {s.delta > 0 ? `+${s.delta}` : s.delta}
                  </span>
                  <span>{s.detail}</span>
                </li>
              ))}
            </ul>
          )}
          <p className="mt-2 text-[10px] opacity-70">
            Rule-based. Every signal traces to a date or stage you can see — no AI.
          </p>
        </TooltipContent>
      </Tooltip>
    </TooltipProvider>
  );
}
