'use client';

/**
 * Sales Performance — Stage velocity (Report 01 Chart 2).
 *
 * Median days spent in each pipeline stage with a faint p90 marker.
 * Same horizontal-bar pattern as the Pipeline funnel so the two charts
 * read as a pair on the page.
 */

import { cn } from '@/lib/utils';
import { STAGE_LABELS, type PipelineStage } from '@/lib/constants';

interface StageVelocityRow {
  stage: PipelineStage;
  medianDays: number | null;
  p90Days: number | null;
  transitions: number;
}

interface Props {
  rows: StageVelocityRow[];
}

const STAGE_BAR_COLOR: Record<PipelineStage, string> = {
  enquiry: 'bg-slate-400',
  qualified: 'bg-brand-300',
  nurturing: 'bg-brand-300/70',
  eoi: 'bg-brand-400',
  reservation: 'bg-brand-500',
  deposit_paid: 'bg-brand-600',
  contract: 'bg-brand-700',
};

export function SalesStageVelocity({ rows }: Props) {
  const hasData = rows.some((r) => r.medianDays !== null);
  if (!hasData) {
    return (
      <div className="py-12 flex flex-col items-center justify-center text-center space-y-2">
        <p className="text-sm text-muted-foreground max-w-xs">
          No stage transitions captured yet. Velocity appears here once deals start moving between
          stages.
        </p>
      </div>
    );
  }

  // Scale all bars + p90 markers against the highest p90 we observed so
  // a tail outlier doesn't crush the rest of the bars to nothing.
  const max = Math.max(1, ...rows.map((r) => r.p90Days ?? r.medianDays ?? 0));

  return (
    <div className="space-y-2.5">
      {rows.map((row) => {
        const median = row.medianDays;
        const p90 = row.p90Days;
        const medianPct = median !== null ? (median / max) * 100 : 0;
        const p90Pct = p90 !== null ? (p90 / max) * 100 : 0;
        const isMissing = median === null;
        return (
          <div
            key={row.stage}
            className="grid items-center gap-3"
            style={{ gridTemplateColumns: '140px 1fr 120px' }}
          >
            <div className="text-sm font-medium text-foreground">{STAGE_LABELS[row.stage]}</div>

            <div className="relative h-6 rounded-sm bg-muted/40 overflow-hidden">
              {/* Median bar */}
              {!isMissing && (
                <div
                  className={cn(
                    'h-full rounded-sm transition-[width] duration-500 ease-out',
                    STAGE_BAR_COLOR[row.stage],
                  )}
                  style={{ width: `${Math.max(medianPct, 1.5)}%` }}
                  aria-hidden
                />
              )}
              {/* p90 marker (vertical line) */}
              {p90 !== null && p90 > 0 && p90Pct > 0 && (
                <div
                  className="absolute top-0 bottom-0 w-px bg-foreground/60"
                  style={{ left: `calc(${p90Pct}% - 0.5px)` }}
                  title={`p90: ${formatDays(p90)}`}
                  aria-hidden
                />
              )}
              {/* Label inside or outside the bar */}
              <div
                className={cn(
                  'absolute inset-y-0 left-2 flex items-center text-xs font-semibold tabular-nums',
                  isMissing
                    ? 'text-muted-foreground'
                    : medianPct > 18
                      ? 'text-white'
                      : 'text-foreground',
                )}
                style={
                  isMissing || medianPct > 18 ? undefined : { left: `calc(${medianPct}% + 8px)` }
                }
              >
                {isMissing ? '—' : formatDays(median!)}
              </div>
            </div>

            {/* Sample size + p90 chip on the right */}
            <span className="text-[11px] text-muted-foreground tabular-nums">
              {isMissing ? (
                'no data'
              ) : (
                <>
                  {row.transitions} {row.transitions === 1 ? 'transition' : 'transitions'}
                  {p90 !== null && p90 > 0 ? ` · p90 ${formatDays(p90)}` : ''}
                </>
              )}
            </span>
          </div>
        );
      })}
    </div>
  );
}

function formatDays(days: number): string {
  if (days < 1) return `<1d`;
  if (days < 10) return `${days.toFixed(1)}d`;
  if (days < 60) return `${Math.round(days)}d`;
  const weeks = days / 7;
  if (weeks < 24) return `${Math.round(weeks)}w`;
  return `${(days / 30.44).toFixed(1)}mo`;
}
