'use client';
/**
 * FissionLauncher — 裂变发起面板
 * 选源爆款 + 参考强度(low/mid/high) + 扇出套数(1~5) → POST /fission，回调 fission_id。
 */
import { useState } from 'react';
import { api } from '@/lib/api';
import { TaskListItem } from '@/types';
import { getErrorAction } from '@/types/errors';
import { clsx } from 'clsx';

interface Props {
  sources: TaskListItem[];
  onLaunched: (fissionId: number) => void;
}

const LEVELS: { key: string; label: string; desc: string }[] = [
  { key: 'low', label: '低', desc: '只借结构，文案视觉大改' },
  { key: 'mid', label: '中', desc: '保留核心卖点，角度换新' },
  { key: 'high', label: '高', desc: '贴近原作，仅做差异微调' },
];

export function FissionLauncher({ sources, onLaunched }: Props) {
  const [sourceId, setSourceId] = useState<number | null>(sources[0]?.id ?? null);
  const [level, setLevel] = useState('mid');
  const [fanout, setFanout] = useState(3);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  async function launch() {
    if (!sourceId) { setError('请选择一个源爆款'); return; }
    setSubmitting(true);
    setError(null);
    try {
      const res = await api.post<{ fission_id: number }>('/api/v1/fission', {
        source_task_id: sourceId, reference_level: level, fanout_count: fanout,
      });
      onLaunched(res.fission_id);
    } catch (e: unknown) {
      const ae = e as { code?: number; message?: string };
      setError(ae.message || getErrorAction(ae.code ?? 50001).message);
    } finally {
      setSubmitting(false);
    }
  }

  return (
    <div className="flex flex-col gap-5">
      {/* 选源爆款 */}
      <div>
        <label className="block text-sm font-medium text-text-primary mb-2">源爆款笔记</label>
        <select
          value={sourceId ?? ''}
          onChange={(e) => setSourceId(Number(e.target.value))}
          className="w-full border border-border-default rounded-lg px-3 py-2 text-sm focus:outline-none focus:border-brand-orange"
        >
          {sources.map((t) => (
            <option key={t.id} value={t.id}>
              #{t.id} · {t.theme || '（无主题）'}
            </option>
          ))}
        </select>
      </div>

      {/* 参考强度 */}
      <div>
        <label className="block text-sm font-medium text-text-primary mb-2">参考强度</label>
        <div className="grid grid-cols-3 gap-2">
          {LEVELS.map((l) => (
            <button
              key={l.key}
              type="button"
              onClick={() => setLevel(l.key)}
              className={clsx(
                'border rounded-lg p-3 text-left transition-colors',
                level === l.key
                  ? 'border-brand-orange bg-brand-orange-light'
                  : 'border-border-default hover:border-brand-orange'
              )}
            >
              <div className="text-sm font-medium text-text-primary">{l.label}</div>
              <div className="text-xs text-text-tertiary mt-1">{l.desc}</div>
            </button>
          ))}
        </div>
      </div>

      {/* 扇出套数 */}
      <div>
        <label className="block text-sm font-medium text-text-primary mb-2">
          裂变套数：<span className="text-brand-orange font-semibold">{fanout}</span> 套
        </label>
        <input
          type="range" min={1} max={5} value={fanout}
          onChange={(e) => setFanout(Number(e.target.value))}
          className="w-full accent-brand-orange"
        />
      </div>

      {error && <div className="text-sm text-red-600">{error}</div>}

      <button
        type="button"
        onClick={launch}
        disabled={submitting || !sourceId}
        className="self-start bg-brand-orange text-white text-sm font-medium px-6 py-2.5 rounded-lg hover:bg-orange-600 disabled:opacity-50"
      >
        {submitting ? '裂变中…' : `裂变成 ${fanout} 套笔记包 →`}
      </button>
    </div>
  );
}
