import { useAtomSet } from "@effect/atom-react";
import {
BOARD_POST_CSV_COLUMNS,
BOARD_POST_CSV_TEMPLATE,
} from "@feeblo/domain-contracts/board-csv";
import { DATA_IMPORT_MAX_BYTES } from "@feeblo/domain/data-transfer/limits";
import type { TDataImportProviderDescriptor } from "@feeblo/domain/data-transfer/provider-schema";
import {
DataImportJobSummary,
type TDataImportJobSummary,
} from "@feeblo/domain/data-transfer/schema";
import { Alert, AlertDescription, AlertTitle } from "@feeblo/ui/alert";
import { Button } from "@feeblo/ui/button";
import {
Dialog,
DialogClose,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPanel,
DialogPopup,
DialogTitle,
} from "@feeblo/ui/dialog";
import { useAppForm } from "@feeblo/ui/hooks/form";
import { toastManager } from "@feeblo/ui/toast";
import { cn } from "@feeblo/ui/utils";
import {
CheckmarkCircle02Icon,
FileSpreadsheetIcon,
FileUploadIcon,
LinkSquare02Icon,
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { Link } from "@tanstack/react-router";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { useState } from "react";
import { z } from "zod";
import { m } from "@/paraglide/messages.js";
import {
dataTransferApiBase,
downloadBlob,
errorEnvelopeMessage,
} from "../api";
import { startProviderDataImportAtom } from "../atoms";
import { plannedRowCount } from "../format";
import { useImportStart } from "../use-import-start";
import { ImportStat } from "./import-status";
const csvFileNamePattern = /\.csv$/iu;
/** The same template the parser reads, so a column cannot drift out of it. */
const downloadImportTemplate = () => {
downloadBlob(
new Blob([BOARD_POST_CSV_TEMPLATE], { type: "text/csv;charset=utf-8" }),
"board-import-template.csv"
);
};
/** The staged job, shown once the server has parsed and planned it. */
function StagedImport({
job,
onDone,
organizationId,
}: {
readonly job: TDataImportJobSummary;
readonly onDone: () => void;
readonly organizationId: string;
}) {
return (
<>
{m.data_import_staged_title()}
{m.data_import_staged_description()}
{job.notices.length === 0 ? null : (
{job.notices.slice(0, 4).map((notice) => (
{notice}
))}
)}
}>
{m.data_import_close()}
>
);
}
/**
* What a person is told before they choose a file or paste a key: an import
* creates posts and does not fire the notifications a normal post would. It is
* here, not on the review page, because it changes whether they start at all.
*/
function ImportDisclosure({
children,
}: {
readonly children: React.ReactNode;
}) {
return (
{children}
);
}
export function CsvImportDialog({
onOpenChange,
onStaged,
open,
organizationId,
}: {
readonly onOpenChange: (open: boolean) => void;
readonly onStaged: (job: TDataImportJobSummary) => void;
readonly open: boolean;
readonly organizationId: string;
}) {
const start = useImportStart(m.data_import_csv_failed());
const [file, setFile] = useState(null);
const [stagedJob, setStagedJob] = useState(
null
);
const [isDragging, setIsDragging] = useState(false);
const accept = (candidate: File | null) => {
if (candidate === null) {
setFile(null);
return;
}
if (!csvFileNamePattern.test(candidate.name)) {
toastManager.add({
title: m.data_import_csv_choose_csv(),
type: "error",
});
return;
}
if (candidate.size > DATA_IMPORT_MAX_BYTES) {
toastManager.add({ title: m.data_import_csv_too_large(), type: "error" });
return;
}
setFile(candidate);
};
const upload = async () => {
if (file === null) {
return;
}
await start.run(async () => {
const body = new FormData();
body.append("file", file);
body.append("organizationId", organizationId);
const response = await fetch(`${dataTransferApiBase()}/api/data/import`, {
body,
credentials: "include",
method: "POST",
});
if (!response.ok) {
const message = await errorEnvelopeMessage(response);
throw new Error(message ?? m.data_import_csv_failed());
}
const payload: unknown = await response.json();
// SAFETY: the endpoint contract returns a DataImportJobSummary; the
// schema rejects drift instead of letting it reach the review panel.
// This is a React event handler, not Effect code, so the Option is the
// recovery path.
// eslint-disable-next-line effecttsgo/schema-sync -- non-Effect React boundary
const decoded = Schema.decodeUnknownOption(DataImportJobSummary)(payload);
if (Option.isNone(decoded)) {
throw new Error(m.data_import_csv_failed());
}
setStagedJob(decoded.value);
onStaged(decoded.value);
});
};
return (
);
}
export function ProviderImportDialog({
onOpenChange,
onStaged,
open,
organizationId,
provider,
}: {
readonly onOpenChange: (open: boolean) => void;
readonly onStaged: (job: TDataImportJobSummary) => void;
readonly open: boolean;
readonly organizationId: string;
readonly provider: TDataImportProviderDescriptor;
}) {
const startImport = useAtomSet(startProviderDataImportAtom, {
mode: "promise",
});
const start = useImportStart(m.data_import_provider_failed());
const [stagedJob, setStagedJob] = useState(
null
);
// SAFETY: every credential field's default is the empty string, so the
// object literal is a string record whatever keys the descriptor declares.
const credentials = Object.fromEntries(
provider.credentialFields.map((field) => [field.key, ""])
) as Record;
const form = useAppForm({
defaultValues: credentials,
validators: {
onSubmit: z.object(
Object.fromEntries(
provider.credentialFields.map((field) => [
field.key,
z
.string()
.trim()
.min(
1,
m.data_import_provider_field_required({ field: field.label })
),
])
)
),
},
onSubmit: async ({ value }) => {
await start.run(async () => {
const job = await startImport({
payload: {
credentials: value,
organizationId,
provider: provider.id,
},
});
setStagedJob(job);
onStaged(job);
});
},
});
return (
);
}