import { useState } from "react";
import { ModelSelector } from "../ModelSelector";
import { DataPreviewModal } from "./DataPreviewModal";
import { AnswerGridEditor, type AnswerGrid } from "./AnswerGridEditor";

interface PromptEditorProps {
  sessionId: number;
  onGenerate: (model: string) => void;
  isGenerating: boolean;
  selectedCount: number;
  selectedIndices: number[];
  students: { index: number; name: string }[];
}

export function PromptEditor({
  sessionId,
  onGenerate,
  isGenerating,
  selectedCount,
  selectedIndices,
  students,
}: PromptEditorProps) {
  const [model, setModel] = useState("gpt-5.4");
  const [showPreview, setShowPreview] = useState(false);
  const [confirmedGrid, setConfirmedGrid] = useState<AnswerGrid | null>(null);

  const canGenerate =
    !isGenerating && selectedCount > 0 && confirmedGrid !== null;

  const buttonLabel = (() => {
    if (selectedCount === 0) return "請先選擇學生";
    if (!confirmedGrid) return "請先確認答案表";
    return `預覽並生成報告（${selectedCount} 位學生）→`;
  })();

  return (
    <div className="space-y-4">
      <AnswerGridEditor
        sessionId={sessionId}
        onConfirmedChange={setConfirmedGrid}
      />

      <div className="flex items-center justify-end">
        <ModelSelector value={model} onChange={setModel} label="報告模型：" />
      </div>

      <div className="text-center">
        <button
          onClick={() => setShowPreview(true)}
          disabled={!canGenerate}
          className="btn btn-accent text-lg px-8 py-4 disabled:opacity-50 disabled:cursor-not-allowed relative overflow-visible"
        >
          {buttonLabel}
        </button>
      </div>

      {showPreview && (
        <DataPreviewModal
          onGenerate={() => {
            setShowPreview(false);
            onGenerate(model);
          }}
          onClose={() => setShowPreview(false)}
          isGenerating={isGenerating}
          sessionId={sessionId}
          selectedIndices={selectedIndices}
          students={students}
        />
      )}
    </div>
  );
}
