"use client"; import { useRef, useState } from "react"; import { useTranslation } from "react-i18next"; import { Download, FileSpreadsheet, Loader2, X } from "lucide-react"; import { commitPracticeImport, downloadPracticeTemplate, previewPracticeImport, type ImportPreview, } from "@/lib/practice-api"; export function PracticeImport({ onClose, onImported, initialTarget, }: { onClose: () => void; onImported: (message: string) => void; initialTarget: "bank" | "mistakes"; }) { const { t } = useTranslation(); const [target, setTarget] = useState(initialTarget); const [preview, setPreview] = useState(null); const [filename, setFilename] = useState(""); const [busy, setBusy] = useState(false); const pending = useRef(false); const [error, setError] = useState(""); async function select(file?: File) { if (!file || pending.current) return; pending.current = true; setBusy(true); setError(""); setPreview(null); setFilename(file.name); try { setPreview(await previewPracticeImport(file, target)); } catch (err) { setError(err instanceof Error ? err.message : String(err)); } finally { pending.current = false; setBusy(false); } } async function commit() { if (!preview?.token || pending.current) return; pending.current = true; setBusy(true); setError(""); try { const result = await commitPracticeImport(preview.token); onImported(t("Imported {{created}} questions; skipped {{duplicates}} duplicates.", result)); } catch (err) { setError(err instanceof Error ? err.message : String(err)); } finally { pending.current = false; setBusy(false); } } return (

{t("Import questions")}

{t( "Import XLSX, CSV, TSV or JSON. Up to 500 questions and 5 MB per file. XLSX uses the active sheet. Chinese and English column names are supported.", )}

{(["xlsx", "csv"] as const).map(format => ( ))}
{busy && (

{t("Processing…")}

)} {error && (

{error}

)} {preview && (

{filename} ·{" "} {t("{{valid}} of {{total}} rows are valid", { valid: preview.valid, total: preview.total, })}

{preview.errors.length > 0 && (

{t("Nothing has been imported. Fix these rows and select the file again.")}

{preview.errors.map(error => (

{t("Row {{row}}", { row: error.row })}: {error.message}

))}
)}
    {preview.samples.map((question, index) => (
  1. {question.question}

    {t("Correct answer")}: {question.correct_answer} {question.tags.length ? ` · ${question.tags.join(" / ")}` : ""}

  2. ))}

{t( "Existing questions are kept. Identical imports are skipped and their tags are combined.", )}

)}
); }