'use client';

import * as React from 'react';
import { HoverCard, HoverCardTrigger, HoverCardContent } from '@/components/ui/hover-card';

/**
 * PriorityHover — 优先级数字旁悬停展示 6 因子拆解。
 *
 * 数据来源:plan.reasons[0].breakdown.priority(后端 priority-scorer 输出)
 *   raw = (clinicalBase × timeWindowFactor + valueBonus + likelihoodBonus + urgencyBonus) × confidenceFactor
 *
 * 列表 + 详情页共用。breakdown 缺失时回退最简文案。
 */
export interface PriorityBreakdown {
  raw?: number;
  main?: number;             // = clinicalBase × timeWindowFactor
  clinicalBase?: number;     // 临床基线(sub_scenario 类别)
  timeWindowFactor?: number; // 时间窗(0-1)
  valueBonus?: number;       // 价值(persona value)
  likelihoodBonus?: number;  // 转化(历史触达 + recall_risk)
  urgencyBonus?: number;     // 紧迫(超临界天)
  confidenceFactor?: number; // 信号置信(0-1)
}

export function PriorityHover({
  score,
  breakdown,
  children,
}: {
  score: number;
  breakdown?: PriorityBreakdown | null;
  children: React.ReactNode;
}) {
  return (
    <HoverCard openDelay={150} closeDelay={80}>
      {/* 直接把 children 作为 trigger,radix 锚定 children 本身(避免多包一层 span 错位)*/}
      <HoverCardTrigger asChild>{children}</HoverCardTrigger>
      <HoverCardContent align="end" sideOffset={6} className="w-72 p-3 text-[11.5px]">
        <PriorityBreakdownTable score={score} breakdown={breakdown} />
      </HoverCardContent>
    </HoverCard>
  );
}

function PriorityBreakdownTable({
  score,
  breakdown,
}: {
  score: number;
  breakdown?: PriorityBreakdown | null;
}) {
  const total = Math.round(score);
  if (!breakdown) {
    // 老数据 / 异常兜底
    return (
      <div className="space-y-1.5">
        <Header total={total} />
        <p className="text-slate-500 leading-relaxed">
          由 6 因子算分:临床基线 × 时间窗 + 价值 + 转化 + 紧迫,× 信号置信。
          <br />
          (此条召回缺明细 — 重新计算后可恢复)
        </p>
      </div>
    );
  }
  const base = breakdown.clinicalBase ?? 0;
  const tw = breakdown.timeWindowFactor ?? 0;
  const main = breakdown.main ?? Math.round(base * tw);
  const value = breakdown.valueBonus ?? 0;
  const likelihood = breakdown.likelihoodBonus ?? 0;
  const urgency = breakdown.urgencyBonus ?? 0;
  const conf = breakdown.confidenceFactor ?? 1;
  const subtotal = main + value + likelihood + urgency;
  return (
    <div className="space-y-1.5">
      <Header total={total} />
      <table className="w-full tabular-nums">
        <tbody>
          <Row label="临床基线" value={base.toFixed(0)} hint="召回场景类别基线分" />
          <Row label="× 时间窗" value={tw.toFixed(2)} hint="医嘱黄金窗内剩余比例" />
          <Subtotal label="主体" value={main.toFixed(0)} />
          <Row label="+ 价值" value={`+${value.toFixed(0)}`} hint="患者价值档位加权" tone="emerald" />
          <Row label="+ 转化" value={`+${likelihood.toFixed(0)}`} hint="历史触达成功率 + 流失风险" tone="emerald" />
          <Row label="+ 紧迫" value={`+${urgency.toFixed(0)}`} hint="过黄金窗临界点" tone="emerald" />
          <Subtotal label="小计" value={subtotal.toFixed(0)} />
          <Row label="× 置信" value={conf.toFixed(2)} hint="信号置信(诊断 1.0 / 建议 0.8)" tone={conf < 1 ? 'amber' : undefined} />
          <Subtotal label="= 总分" value={total.toString()} bold />
        </tbody>
      </table>
    </div>
  );
}

function Header({ total }: { total: number }) {
  return (
    <div className="flex items-baseline justify-between border-b border-slate-200 pb-1.5">
      <span className="text-[13px] font-semibold text-slate-900">优先级 {total} / 100</span>
      <span className="text-[10.5px] text-slate-500">6 因子算分</span>
    </div>
  );
}

function Row({
  label,
  value,
  hint,
  tone,
}: {
  label: string;
  value: string;
  hint?: string;
  tone?: 'emerald' | 'amber';
}) {
  const valueClass =
    tone === 'emerald' ? 'text-emerald-700 font-medium'
    : tone === 'amber' ? 'text-amber-700 font-medium'
    : 'text-slate-700';
  return (
    <tr>
      <td className="py-0.5 text-slate-600">{label}</td>
      <td className={`py-0.5 text-right ${valueClass}`}>{value}</td>
      <td className="py-0.5 pl-2 text-[10.5px] text-slate-400">{hint ?? ''}</td>
    </tr>
  );
}

function Subtotal({ label, value, bold }: { label: string; value: string; bold?: boolean }) {
  return (
    <tr>
      <td colSpan={3} className="border-t border-slate-100 pt-1 pb-0.5">
        <span className="flex justify-between">
          <span className={`text-slate-700 ${bold ? 'font-semibold' : ''}`}>{label}</span>
          <span className={`tabular-nums ${bold ? 'text-rose-700 font-bold' : 'text-slate-800 font-medium'}`}>{value}</span>
        </span>
      </td>
    </tr>
  );
}
