'use client';
/**
 * FissionProgress — 裂变进度（轮询 GET /fission/{id} 聚合 x/N 完成）
 * 新架构：一次 LLM 出 N 套完整笔记包落 FissionNote，完成后进独立展示页看 N 套。
 */
import { useEffect, useState, useCallback } from 'react';
import Link from 'next/link';
import { api } from '@/lib/api';

interface FissionStatus {
  fission_id: number;
  reference_level: string;
  fanout_count: number;
  status: 'generating' | 'completed' | 'failed';
  progress: { done: number; failed: number; total: number };
}

interface Props {
  fissionId: number;
  onReset: () => void;
}

export function FissionProgress({ fissionId, onReset }: Props) {
  const [data, setData] = useState<FissionStatus | null>(null);
  const [error, setError] = useState<string | null>(null);

  const poll = useCallback(async () => {
    try {
      const res = await api.get<FissionStatus>(`/api/v1/fission/${fissionId}`);
      setData(res);
      return res.status;
    } catch {
      setError('查询裂变进度失败');
      return 'failed';
    }
  }, [fissionId]);

  useEffect(() => {
    let timer: ReturnType<typeof setTimeout>;
    let stopped = false;
    const tick = async () => {
      const status = await poll();
      if (!stopped && status === 'generating') timer = setTimeout(tick, 3000);
    };
    tick();
    return () => { stopped = true; clearTimeout(timer); };
  }, [poll]);

  if (error) {
    return (
      <div className="rounded-lg bg-red-50 border border-red-200 p-4 text-sm text-red-600">
        {error}
        <button className="ml-4 underline" onClick={onReset}>返回</button>
      </div>
    );
  }

  if (!data) return <div className="py-12 text-center text-text-tertiary text-sm">启动裂变…</div>;

  const { progress, status } = data;
  const pct = progress.total > 0 ? Math.round((progress.done / progress.total) * 100) : 0;

  return (
    <div className="flex flex-col gap-4">
      <div className="flex items-center justify-between">
        <h2 className="text-base font-semibold text-text-primary">
          裂变 #{data.fission_id} · {data.fanout_count} 套
        </h2>
        <span className="text-sm text-text-secondary">
          {progress.done}/{progress.total || data.fanout_count} 完成
          {progress.failed > 0 && <span className="text-red-500"> · {progress.failed} 失败</span>}
        </span>
      </div>

      <div className="w-full h-2 bg-surface-tertiary rounded-full overflow-hidden">
        <div
          className="h-full bg-brand-orange transition-all duration-500"
          style={{ width: `${pct}%` }}
        />
      </div>

      {status === 'generating' && (
        <p className="text-sm text-text-tertiary">正在一次性生成 {data.fanout_count} 套差异化笔记包，请稍候…</p>
      )}
      {status === 'failed' && (
        <div className="rounded-lg bg-red-50 border border-red-200 p-3 text-sm text-red-600">
          这批裂变全部生成失败，可点下方「再裂变一个」重试，或换一个源爆款。
        </div>
      )}
      {status === 'completed' && (
        <Link
          href={`/fission/${data.fission_id}/notes`}
          className="self-start rounded-lg bg-brand-orange text-white px-5 py-2.5 text-sm font-medium hover:opacity-90 transition-opacity"
        >
          查看 {data.fanout_count} 套笔记包 →
        </Link>
      )}

      <button
        type="button"
        onClick={onReset}
        className="self-start text-sm text-text-secondary underline mt-2"
      >
        再裂变一个
      </button>
    </div>
  );
}
