'use client';
// 屏4.5 确认预览：提交审核 / 重新生成（飞轮-1）
import { useRouter, useParams } from 'next/navigation';
import { ProgressBar } from '@/components/layout/ProgressBar';
import { ConfirmActionBar } from '@/components/tasks/ConfirmActionBar';
import { ConfirmPreviewImages } from '@/components/tasks/ConfirmPreviewImages';
import { useTaskStore } from '@/stores/taskStore';
import { useGenerationStore } from '@/stores/generationStore';
import { api } from '@/lib/api';
import { useState } from 'react';

export default function ConfirmPage() {
  const params = useParams<{ id: string }>();
  const taskId = params?.id ? Number(params.id) : null;
  const router = useRouter();
  const { selectedTextIds, selectedImageIds } = useTaskStore();
  // imageCandidates 平铺（契约 image_candidate 事件无 batch 字段）
  const { textCandidates, imageCandidates } = useGenerationStore();
  const [submitting, setSubmitting] = useState(false);
  const [regenerating, setRegenerating] = useState(false);

  const selectedTexts = textCandidates.filter((c) => selectedTextIds.includes(c.candidate_id));
  const selectedImages = imageCandidates.filter((c) => selectedImageIds.includes(c.candidate_id));

  async function handleSubmitReview() {
    if (!taskId) return;
    setSubmitting(true);
    try {
      await api.post(`/api/v1/tasks/${taskId}/submit-review`);
      router.push('/review');
    } finally {
      setSubmitting(false);
    }
  }

  async function handleRegenerate() {
    if (!taskId) return;
    setRegenerating(true);
    try {
      await api.post(`/api/v1/tasks/${taskId}/regenerate`);
      router.push(`/tasks/${taskId}/text`);
    } finally {
      setRegenerating(false);
    }
  }

  return (
    <div className="flex flex-col h-full">
      <ProgressBar currentStep={4} />

      <div className="p-6 flex-1 overflow-auto max-w-4xl">
        <h2 className="text-xl font-bold text-text-primary mb-6">确认预览</h2>

        <div className="grid grid-cols-2 gap-6">
          {/* 已选文案 */}
          <div>
            <h3 className="text-sm font-semibold text-text-secondary mb-3">已选文案</h3>
            {selectedTexts.length === 0 ? (
              <p className="text-text-tertiary text-sm">暂无选中文案</p>
            ) : (
              <div className="space-y-3">
                {selectedTexts.map((c) => (
                  <div key={c.candidate_id}
                    className="border border-border-default rounded-xl p-4 bg-surface-primary">
                    <span className="text-xs text-brand-orange font-medium">{c.angle_label}</span>
                    <p className="text-sm text-text-primary mt-1 whitespace-pre-wrap line-clamp-6">
                      {c.content}
                    </p>
                    <span className="text-xs text-text-tertiary mt-1 block">总分 {c.score.total}</span>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* 已选图 */}
          <ConfirmPreviewImages images={selectedImages} />
        </div>

        {/* 操作栏 */}
        <ConfirmActionBar
          submitting={submitting}
          regenerating={regenerating}
          canSubmit={selectedTextIds.length > 0}
          onSubmit={handleSubmitReview}
          onRegenerate={handleRegenerate}
        />
      </div>
    </div>
  );
}
