import React, { useEffect, useState } from "react"; import { useNavigate } from "react-router-dom"; import { Alert, Box, Button, Chip, Dialog, DialogActions, DialogContent, DialogTitle, IconButton, Menu, MenuItem, Paper, Stack, TextField, Typography, } from "@mui/material"; import AddIcon from "@mui/icons-material/Add"; import DescriptionOutlinedIcon from "@mui/icons-material/DescriptionOutlined"; import MoreVertIcon from "@mui/icons-material/MoreVert"; import PublicIcon from "@mui/icons-material/Public"; import { api, getApiErrorMessage } from "../api"; import { useToast } from "../toast"; import { CvTheme, CvVariantSummary, cvBuilderApi, emptyCvVariantSettings } from "../cvBuilder"; import { useDialogActions } from "../dialogs"; import CvTemplateThumbnail from "../components/CvTemplateThumbnail"; import { useI18n } from "../i18n/I18nProvider"; export default function CvBuilderPage() { const navigate = useNavigate(); const { toast } = useToast(); const { language, t } = useI18n(); const { confirmAction, promptForValue } = useDialogActions(); const [variants, setVariants] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); const [menu, setMenu] = useState<{ anchor: HTMLElement; id: number } | null>(null); const [themes, setThemes] = useState([]); const [createOpen, setCreateOpen] = useState(false); const [newName, setNewName] = useState(t("cvDashboardUntitled")); const [newTheme, setNewTheme] = useState("modern"); const [creating, setCreating] = useState(false); const load = async () => { try { setVariants(await cvBuilderApi.list()); try { setThemes(await cvBuilderApi.themes()); } catch { setThemes([]); } } catch (err) { setError(getApiErrorMessage(err, t("cvDashboardLoadFailed"))); } finally { setLoading(false); } }; useEffect(() => { load(); }, []); const createNew = async () => { setCreateOpen(true); }; const confirmCreate = async () => { if (!newName.trim()) return; setCreating(true); try { const variant = await cvBuilderApi.create({ name: newName.trim(), settings: emptyCvVariantSettings(newTheme) }); setCreateOpen(false); navigate(`/career/builder/${variant.id}`); } catch (err) { toast(getApiErrorMessage(err, t("cvDashboardCreateFailed")), "error"); } finally { setCreating(false); } }; const duplicate = async (id: number) => { try { await cvBuilderApi.duplicate(id); await load(); toast(t("cvDashboardDuplicated"), "success"); } catch (err) { toast(getApiErrorMessage(err, t("cvDashboardDuplicateFailed")), "error"); } finally { setMenu(null); } }; const remove = async (id: number) => { const variant = variants.find((item) => item.id === id); setMenu(null); if (!(await confirmAction(t("cvDashboardDeleteMessage", { name: variant?.name ?? t("cvDashboardThisCv") }), { title: t("cvDashboardDeleteCv"), confirmLabel: t("cvDashboardDeleteCv"), destructive: true, }))) return; try { await cvBuilderApi.remove(id); setVariants((v) => v.filter((x) => x.id !== id)); toast(t("cvDashboardDeleted"), "success"); } catch (err) { toast(getApiErrorMessage(err, t("cvDashboardDeleteFailed")), "error"); } finally { setMenu(null); } }; const rename = async (id: number) => { const current = variants.find((item) => item.id === id); setMenu(null); const nextName = await promptForValue(t("cvDashboardRenameMessage"), current?.name ?? "", { title: t("cvDashboardRenameCv"), confirmLabel: t("cvDashboardRename") }); if (!nextName?.trim() || nextName.trim() === current?.name) return; try { const variant = await cvBuilderApi.get(id); const updated = await cvBuilderApi.save(id, { name: nextName.trim(), settings: variant.settings, source: "manual" }); setVariants((items) => items.map((item) => item.id === id ? { ...item, name: updated.name, updatedAtUtc: updated.updatedAtUtc, version: updated.version } : item)); toast(t("cvDashboardRenamed"), "success"); } catch (err) { toast(getApiErrorMessage(err, t("cvDashboardRenameFailed")), "error"); } }; const download = async (id: number, cvName: string) => { setMenu(null); try { const response = await api.post(cvBuilderApi.exportPdfUrl(id), {}, { responseType: "blob" }); const url = URL.createObjectURL(response.data as Blob); const link = document.createElement("a"); link.href = url; link.download = `${cvName || "cv"}.pdf`; link.click(); URL.revokeObjectURL(url); } catch (err) { toast(getApiErrorMessage(err, t("cvDashboardDownloadFailed")), "error"); } }; return ( {t("cvDashboardTitle")} {t("cvDashboardSubtitle")} {error && {error}} {!loading && variants.length === 0 && !error && ( {t("cvDashboardEmptyTitle")} {t("cvDashboardEmptyBody")} )} {variants.map((v) => ( navigate(`/career/builder/${v.id}`)} onKeyDown={(event) => { if (event.target === event.currentTarget && (event.key === "Enter" || event.key === " ")) { event.preventDefault(); navigate(`/career/builder/${v.id}`); } }} > theme.id === v.themeId)} /> {v.name} { e.stopPropagation(); setMenu({ anchor: e.currentTarget, id: v.id }); }}> {v.isPublic && } label={t("cvEditorPublic")} />} {t("cvDashboardUpdatedVersion", { date: new Date(v.updatedAtUtc).toLocaleDateString(language === "nb" ? "nb-NO" : "en-GB"), version: v.version })} {v.jobApplicationId ? ` ยท ${[v.jobTitle, v.companyName].filter(Boolean).join(t("cvDashboardAt")) || t("cvDashboardJobNumber", { id: v.jobApplicationId })}` : ""} ))} setMenu(null)}> menu && navigate(`/career/builder/${menu.id}`)}>{t("cvDashboardOpen")} menu && duplicate(menu.id)}>{t("cvEditorDuplicate")} menu && void rename(menu.id)}>{t("cvDashboardRename")} { const cv = variants.find((item) => item.id === menu?.id); if (cv) void download(cv.id, cv.name); }}>{t("cvEditorDownloadPdf")} menu && remove(menu.id)} sx={{ color: "error.main" }}>{t("cvDashboardDelete")} { if (!creating) setCreateOpen(false); }} fullWidth maxWidth="md" aria-labelledby="create-cv-title"> {t("cvDashboardCreateTitle")} {t("cvDashboardCreateHelp")} setNewName(event.target.value)} error={!newName.trim()} helperText={!newName.trim() ? t("cvDashboardEnterName") : t("cvDashboardNameExample")} sx={{ mb: 2 }} /> {t("cvDashboardChooseTemplate")} {(themes.length ? themes.filter((theme) => theme.available) : [{ id: "modern", name: "Modern", category: "Professional", layout: "header-band", swatches: ["#3157d5", "#eef1f4", "#fff"] } as CvTheme]).map((theme) => setNewTheme(theme.id)} onKeyDown={(event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); setNewTheme(theme.id); } }} variant="outlined" sx={{ p: 0.75, cursor: "pointer", borderWidth: newTheme === theme.id ? 2 : 1, borderColor: newTheme === theme.id ? "primary.main" : "divider", "&:focus-visible": { outline: "3px solid", outlineColor: "primary.main" } }}>{theme.name}{theme.category})} ); }