'use client';
/**
 * /fission — 独立裂变页（第11环，倩倩姐2026-06-15拍板"新建独立裂变页"）
 * 选一个已通过/已归档的爆款源任务 → 设定参考强度+扇出套数 → 一键裂变成 N 套完整笔记包。
 * 后端：POST /api/v1/fission，GET /api/v1/fission/{id} 查聚合进度。
 */
import { useEffect, useState, useCallback } from 'react';
import { api } from '@/lib/api';
import { TaskListItem, PaginatedResponse } from '@/types';
import { getErrorAction } from '@/types/errors';
import { FissionLauncher } from '@/components/fission/FissionLauncher';
import { FissionProgress } from '@/components/fission/FissionProgress';

// 裂变源 = 已验证的爆款，只从通过/归档里选
const SOURCE_STATUSES = ['approved', 'archived'];

export default function FissionPage() {
  const [sources, setSources] = useState<TaskListItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [activeFissionId, setActiveFissionId] = useState<number | null>(null);

  const fetchSources = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const params = new URLSearchParams({ page: '1', page_size: '50' });
      SOURCE_STATUSES.forEach((s) => params.append('status', s));
      const res = await api.get<PaginatedResponse<TaskListItem>>(`/api/v1/tasks?${params}`);
      setSources(res.items);
    } catch (e: unknown) {
      const ae = e as { code?: number };
      setError(getErrorAction(ae.code ?? 50001).message);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { fetchSources(); }, [fetchSources]);

  return (
    <div className="flex flex-col gap-6 p-6 max-w-3xl">
      <div>
        <h1 className="text-xl font-semibold text-text-primary">裂变扩散</h1>
        <p className="text-sm text-text-secondary mt-1">
          选一个验证过的爆款笔记，一键裂变成多套差异化的完整笔记包，交给不同达人分发。
        </p>
      </div>

      {error && (
        <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={fetchSources}>重试</button>
        </div>
      )}

      {activeFissionId ? (
        <FissionProgress
          fissionId={activeFissionId}
          onReset={() => { setActiveFissionId(null); fetchSources(); }}
        />
      ) : loading ? (
        <div className="py-12 text-center text-text-tertiary text-sm">加载可裂变的爆款…</div>
      ) : sources.length === 0 ? (
        <div className="py-12 text-center text-text-tertiary text-sm">
          还没有通过审核的笔记可裂变。先去开新任务并通过审核，再回来裂变。
        </div>
      ) : (
        <FissionLauncher
          sources={sources}
          onLaunched={(fissionId) => setActiveFissionId(fissionId)}
        />
      )}
    </div>
  );
}
