'use client';

import { useState } from 'react';
import type { DeepStep } from './use-script-stream';

/**
 * ScriptDeepProcess — 深度档"可见生成过程"时间线(规划→撰写→自检→[修订])。
 * 展开规则:进行中的步骤默认展开、其余收缩;用户手动点过的步骤改由用户控制(不再受程序自动展开影响)。
 */

const STEP_LABEL: Record<DeepStep['step'], string> = {
  plan: '规划大纲',
  write: '撰写话术',
  verify: '安全自检',
  repair: '问题修订',
};

function stepHasDetail(s: DeepStep): boolean {
  const d = s.detail;
  if (!d) return false;
  if (s.step === 'plan') return !!d.outline?.length;
  if (s.step === 'verify') return true;
  if (s.step === 'repair') return typeof d.issuesCount === 'number';
  return false;
}

export function ScriptDeepProcess({ steps }: { steps: DeepStep[] }) {
  // 仅记录用户手动点过的步骤的开合状态;没点过的走程序默认(进行中=展开)
  const [manual, setManual] = useState<Record<string, boolean>>({});
  if (!steps.length) return null;

  const runningStep = steps.find((s) => s.status === 'running')?.step ?? null;

  return (
    <div className="mb-3 rounded-lg border border-slate-100 bg-slate-50 p-2.5">
      <ol className="space-y-1.5">
        {steps.map((s) => {
          const hasDetail = stepHasDetail(s);
          const autoOpen = s.step === runningStep; // 程序默认:进行中展开
          const open = s.step in manual ? manual[s.step]! : autoOpen;
          const toggle = () => setManual((m) => ({ ...m, [s.step]: !open }));
          return (
            <li key={s.step} className="text-[12px]">
              <button
                type="button"
                onClick={hasDetail ? toggle : undefined}
                aria-expanded={hasDetail ? open : undefined}
                className={`flex w-full items-center gap-2 rounded px-1.5 py-1 text-left transition-colors ${
                  hasDetail ? 'cursor-pointer hover:bg-slate-100' : 'cursor-default'
                }`}
              >
                <StepIcon status={s.status} />
                <span className="font-medium text-slate-700">{STEP_LABEL[s.step]}</span>
                {s.status === 'running' && <span className="shimmer-text text-slate-400">…</span>}
                {hasDetail && (
                  // 右指箭头(收起)→ 旋转 90° 朝下(展开):清晰的可展开标识
                  <svg
                    viewBox="0 0 24 24"
                    fill="none"
                    stroke="currentColor"
                    strokeWidth="2.5"
                    className={`ml-auto h-3.5 w-3.5 flex-none text-slate-400 transition-transform ${open ? 'rotate-90' : ''}`}
                  >
                    <path d="M9 6l6 6-6 6" strokeLinecap="round" strokeLinejoin="round" />
                  </svg>
                )}
              </button>
              {hasDetail && open && (
                <div className="mt-1 pl-7">
                  <StepDetail step={s} />
                </div>
              )}
            </li>
          );
        })}
      </ol>
    </div>
  );
}

function StepIcon({ status }: { status: DeepStep['status'] }) {
  if (status === 'running') {
    return (
      <svg viewBox="0 0 24 24" fill="none" className="h-3.5 w-3.5 flex-none animate-spin text-slate-400">
        <circle cx="12" cy="12" r="9" stroke="currentColor" strokeWidth="3" strokeOpacity="0.25" />
        <path d="M21 12a9 9 0 0 0-9-9" stroke="currentColor" strokeWidth="3" strokeLinecap="round" />
      </svg>
    );
  }
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" className="h-3.5 w-3.5 flex-none text-slate-500">
      <path d="M20 6L9 17l-5-5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function StepDetail({ step: s }: { step: DeepStep }) {
  const d = s.detail;
  if (!d) return null;

  if (s.step === 'plan' && d.outline?.length) {
    return (
      <ul className="space-y-0.5 text-[11px] text-slate-500">
        {d.outline.map((o, i) => (
          <li key={i} className="break-words leading-snug">
            <span className="text-slate-600">{o.title}</span>
            {o.intent && <span className="text-slate-400"> — {o.intent}</span>}
          </li>
        ))}
      </ul>
    );
  }

  if (s.step === 'verify') {
    const q = d.quality?.overall;
    return (
      <div className="space-y-1">
        <div className="flex flex-wrap items-center gap-x-2 gap-y-0.5 text-[11px] text-slate-500">
          <span>接地 + 安全 {d.pass ? '通过' : `${d.issuesCount ?? 0} 处待修`}</span>
          {typeof q === 'number' && <span>· 质量 {q.toFixed(1)} / 5</span>}
        </div>
        <IssueList issues={d.issues} />
      </div>
    );
  }

  if (s.step === 'repair' && typeof d.issuesCount === 'number') {
    return (
      <div className="space-y-1">
        <div className="text-[11px] text-slate-500">针对 {d.issuesCount} 处问题重写</div>
        <IssueList issues={d.issues} />
      </div>
    );
  }

  return null;
}

/** 逐条问题明细:出问题的段 + 哪里不对 + 改法。 */
function IssueList({
  issues,
}: {
  issues?: { section: string; problem: string; fix: string }[];
}) {
  if (!issues?.length) return null;
  return (
    <ul className="space-y-1">
      {issues.map((it, i) => (
        <li key={i} className="rounded border border-slate-100 bg-white px-2 py-1 text-[11px] leading-snug">
          <div className="font-medium text-slate-600">{it.section || `问题 ${i + 1}`}</div>
          <div className="break-words text-slate-500">{it.problem}</div>
          {it.fix && (
            <div className="mt-0.5 break-words text-brand-600">改法:{it.fix}</div>
          )}
        </li>
      ))}
    </ul>
  );
}
