'use client';

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

/**
 * PriorityHover — 优先级数字旁悬停展示 v3.0 三维拆解。
 *
 * 数据来源:plan.reasons[0].breakdown.priority(后端 priority-scorer v3 输出)
 *   综合 = 急迫性×0.4 + 价值性×0.3 + 意愿度×0.3
 *   总分 = 综合 × 新鲜度 × 置信度 × 10
 *   意愿度 = RFM依从×0.375 + 主诉行为×0.375 + 信任基础×0.25
 *
 * 列表 + 详情页共用。breakdown 缺失时回退最简文案。
 */
export interface PriorityBreakdown {
  urgency?: number; // 急迫性 0-10
  value?: number; // 价值性 0-10
  willingness?: number; // 意愿度 0-10
  rfmAdherence?: number; // 意愿·RFM依从
  intentBehavior?: number; // 意愿·主诉行为
  trustBase?: number; // 意愿·信任基础
  freshness?: number; // 新鲜度因子 0.4-1
  confidenceFactor?: number; // 置信度因子 0.75-1
  base?: number; // 三维加权(未乘因子)
  raw?: number; // 综合 ×因子后
}

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-80 p-3 text-[11.5px]">
        <PriorityBreakdownTable score={score} breakdown={breakdown} />
      </HoverCardContent>
    </HoverCard>
  );
}

function PriorityBreakdownTable({
  score,
  breakdown,
}: {
  score: number;
  breakdown?: PriorityBreakdown | null;
}) {
  // 10 分制(保留两位小数):优先用 breakdown.raw(真 2 位精度),无则 score/10
  const disp = (breakdown?.raw ?? score / 10).toFixed(2);
  if (!breakdown || breakdown.urgency === undefined) {
    // 老数据 / 异常兜底(旧 6 因子 breakdown 也走这里)
    return (
      <div className="space-y-1.5">
        <Header disp={disp} />
        <p className="text-slate-500 leading-relaxed">
          三维加权:急迫性 ×0.4 + 价值性 ×0.3 + 意愿度 ×0.3,再 × 新鲜度 × 置信度。
          <br />
          (此条召回缺明细 — 重新计算后可恢复)
        </p>
      </div>
    );
  }
  const urgency = breakdown.urgency ?? 0;
  const value = breakdown.value ?? 0;
  const willing = breakdown.willingness ?? 0;
  const rfm = breakdown.rfmAdherence ?? 0;
  const intent = breakdown.intentBehavior ?? 0;
  const trust = breakdown.trustBase ?? 0;
  const fresh = breakdown.freshness ?? 1;
  const conf = breakdown.confidenceFactor ?? 1;
  const base = breakdown.base ?? urgency * 0.4 + value * 0.3 + willing * 0.3;
  return (
    <div className="space-y-1.5">
      <Header disp={disp} />
      <table className="w-full tabular-nums">
        <tbody>
          <Row label="急迫性" value={`${urgency.toFixed(0)} × 0.4`} hint="病情多急(末诊/超期)" />
          <Row label="价值性" value={`${value.toFixed(0)} × 0.3`} hint="治疗类型 + 牙数预估收入" />
          <Row
            label="意愿度"
            value={`${willing.toFixed(1)} × 0.3`}
            hint={`RFM ${rfm} / 主诉 ${intent} / 信任 ${trust}`}
          />
          <Subtotal label="三维小计" value={base.toFixed(1)} />
          <Row
            label="× 新鲜度"
            value={fresh.toFixed(2)}
            hint="诊断越老越降权(止损)"
            tone={fresh < 1 ? 'amber' : undefined}
          />
          <Row
            label="× 置信度"
            value={conf.toFixed(2)}
            hint="医生 1.0 / 影像·建议 0.9"
            tone={conf < 1 ? 'amber' : undefined}
          />
          <Subtotal label="= 总分" value={disp} bold />
        </tbody>
      </table>
    </div>
  );
}

function Header({ disp }: { disp: string }) {
  return (
    <div className="flex items-baseline justify-between border-b border-slate-100 pb-1.5">
      <span className="text-[13px] font-semibold text-slate-900">优先级 {disp} / 10</span>
      <span className="text-[10.5px] text-slate-500">急迫 × 价值 × 意愿</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 whitespace-nowrap">{label}</td>
      <td className={`py-0.5 text-right ${valueClass} whitespace-nowrap`}>{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>
  );
}
