"use client";

import { CheckCircle2, CircleDashed, UserRound } from "lucide-react";

import { Badge } from "@/components/ui/Badge";
import type { CharacterizationIssue, CharacterizationReport } from "@/lib/review/sse";

interface CharacterizationPanelProps {
  characterization: CharacterizationReport | null;
  incomplete: boolean;
}

// 高置信度阈值：≥0.7 为主区常显，<0.7 折进「更多低置信度建议」抽屉（控作者注意力预算，灵感 §10）。
const HIGH_CONFIDENCE = 0.7;

// 人物塑造报告区（灵感③ advisory 单维）：只读建议、**无裁决 UI**（不进 conflicts/不阻断验收）。
// 以人物卡 motive/appearance 为客观锚点；每条带逐字引用 + 置信度。按置信度降序，
// 低置信度折叠，避免维度噪声淹没作者。
export function CharacterizationPanel({
  characterization,
  incomplete,
}: CharacterizationPanelProps) {
  if (incomplete) {
    return (
      <section>
        <Badge variant="warning">
          <CircleDashed className="h-3 w-3" aria-hidden="true" />
          未完成
        </Badge>
      </section>
    );
  }
  const issues = characterization?.issues ?? [];
  if (characterization === null || issues.length === 0) {
    return (
      <section>
        <Badge variant="success">
          <CheckCircle2 className="h-3 w-3" aria-hidden="true" />
          人物塑造无明显问题
        </Badge>
      </section>
    );
  }

  // 置信度降序（优先级合并）；高/低分区。
  const sorted = [...issues].sort((a, b) => b.confidence - a.confidence);
  const high = sorted.filter((i) => i.confidence >= HIGH_CONFIDENCE);
  const low = sorted.filter((i) => i.confidence < HIGH_CONFIDENCE);

  return (
    <section className="space-y-2 text-xs">
      <p className="rounded border border-dashed border-line/70 bg-bg/40 px-3 py-1.5 text-[11px] text-ink-soft">
        以下为人物塑造建议（仅供参考，不影响验收）。忽略文本长度与辞藻，只看人物是否写得立体。
      </p>
      <ul className="space-y-2">
        {(high.length > 0 ? high : sorted).map((issue, i) => (
          <CharacterizationIssueCard key={i} issue={issue} />
        ))}
      </ul>
      {high.length > 0 && low.length > 0 ? (
        <details className="group rounded border border-line/70 bg-bg/35 p-2">
          <summary className="cursor-pointer list-none text-2xs font-semibold text-ink-soft">
            更多低置信度建议（{low.length}）
          </summary>
          <ul className="mt-2 space-y-2">
            {low.map((issue, i) => (
              <CharacterizationIssueCard key={i} issue={issue} />
            ))}
          </ul>
        </details>
      ) : null}
    </section>
  );
}

function CharacterizationIssueCard({ issue }: { issue: CharacterizationIssue }) {
  const pct = Math.round(Math.max(0, Math.min(1, issue.confidence)) * 100);
  return (
    <li className="rounded border border-line/70 bg-bg/35 p-2">
      <div className="flex items-center justify-between gap-2">
        <span className="flex items-center gap-1.5 font-semibold text-ink">
          <UserRound className="h-3.5 w-3.5 text-ink-soft" aria-hidden="true" />
          {issue.character || "（未归属角色）"}
          {issue.aspect ? <Badge variant="accent">{issue.aspect}</Badge> : null}
        </span>
        <span className="shrink-0 font-mono text-2xs text-ink-soft" title="置信度">
          {pct}%
        </span>
      </div>
      {issue.where ? <p className="mt-1 text-ink-soft">定位：{issue.where}</p> : null}
      {issue.quote ? (
        <blockquote className="mt-1 border-l-2 border-line pl-2 text-ink-soft italic">
          「{issue.quote}」
        </blockquote>
      ) : null}
      {issue.diagnosis ? <p className="mt-1 text-ink">{issue.diagnosis}</p> : null}
      {issue.suggestion ? (
        <p className="mt-1 text-ink-soft">建议：{issue.suggestion}</p>
      ) : null}
    </li>
  );
}
