'use client';
// 屏3 挑文案：SSE实时+五维分+多选+飞轮隐形
import { useEffect } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { ProgressBar } from '@/components/layout/ProgressBar';
import { FlywheelBannerFromSse } from '@/components/FlywheelBanner';
import { TextCandidateCard, TextCandidateCardSkeleton } from '@/components/tasks/TextCandidateCard';
import { SseStatusBar } from '@/components/tasks/SseStatusBar';
import { useSse } from '@/hooks/useSse';
import { useGenerationStore } from '@/stores/generationStore';
import { useTaskStore } from '@/stores/taskStore';
import { api } from '@/lib/api';

export default function TextSelectionPage() {
  const params = useParams<{ id: string }>();
  const taskId = params?.id ? Number(params.id) : null;
  const router = useRouter();

  const { textCandidates, textDone, textTotal, flywheelInjected } = useGenerationStore();
  const { selectedTextIds, toggleTextSelection, setCurrentTask } = useTaskStore();
  const { connectionStatus, reconnectAttempt } = useSse(taskId);

  useEffect(() => {
    if (taskId) setCurrentTask(taskId, 'generating');
  }, [taskId]);

  async function handleProceedToImages() {
    if (!taskId || selectedTextIds.length === 0) return;
    for (const candidateId of selectedTextIds) {
      await api.post(`/api/v1/tasks/${taskId}/text-candidates/select`, { candidate_id: candidateId });
    }
    router.push(`/tasks/${taskId}/images`);
  }

  const isGenerating = textDone < textTotal || textTotal === 0;
  const showSkeleton = textCandidates.length === 0 && isGenerating;

  return (
    <div className="flex flex-col h-full">
      <ProgressBar currentStep={2} />
      {flywheelInjected && (
        <FlywheelBannerFromSse recentPreference={flywheelInjected.recentPreference} rejectReasons={flywheelInjected.rejectReasons} />
      )}

      <div className="p-6 flex-1 overflow-auto">
        <div className="flex items-center justify-between mb-4">
          <h2 className="text-xl font-bold text-text-primary">
            挑文案{textTotal > 0 && <span className="text-sm font-normal text-text-secondary ml-2">已生成 {textDone}/{textTotal} 条</span>}
          </h2>
          <SseStatusBar status={connectionStatus} attempt={reconnectAttempt} />
        </div>

        {/* SSE 进度提示（生成中且无内容时） */}
        {showSkeleton && (
          <div className="mb-4 bg-brand-cream border border-brand-orange/20 rounded-xl px-4 py-3 text-sm text-text-secondary"
            role="status" aria-live="polite">
            正在生成文案… 预计 15-30 秒，好了会更新，可先去忙别的
          </div>
        )}

        {/* 文案卡网格（谁好谁先冒） */}
        <div className="grid grid-cols-2 xl:grid-cols-3 gap-4">
          {showSkeleton
            ? Array.from({ length: 4 }).map((_, i) => <TextCandidateCardSkeleton key={i} />)
            : textCandidates.map((c) => (
                <TextCandidateCard
                  key={c.candidate_id}
                  candidate={c}
                  selected={selectedTextIds.includes(c.candidate_id)}
                  onToggle={toggleTextSelection}
                />
              ))}
        </div>

        {/* 底部操作栏 */}
        {textCandidates.length > 0 && (
          <div className="sticky bottom-0 bg-surface-primary border-t border-border-default px-6 py-4 flex items-center justify-between mt-4">
            <span className="text-sm text-text-secondary">
              已选 <strong className="text-text-primary">{selectedTextIds.length}</strong> 条
            </span>
            <button
              onClick={handleProceedToImages}
              disabled={selectedTextIds.length === 0}
              aria-label={`用选中的 ${selectedTextIds.length} 条文案去生图`}
              className="bg-brand-orange text-white rounded-lg px-6 py-2.5 text-sm font-medium hover:bg-orange-600 disabled:opacity-50"
            >
              用这 {selectedTextIds.length} 条去生图 →
            </button>
          </div>
        )}
      </div>
    </div>
  );
}
