"use client" import { useState, useEffect } from "react" import { useTranslations } from "next-intl" import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, } from "@/components/ui/dialog" import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" import { ScrollArea } from "@/components/ui/scroll-area" import { Plus, Trash2 } from "lucide-react" import type { FolderCommand } from "@/lib/types" import { createFolderCommand, updateFolderCommand, deleteFolderCommand, } from "@/lib/api" interface CommandDraft { id: number | null name: string command: string deleted: boolean } interface CommandManageDialogProps { open: boolean onOpenChange: (open: boolean) => void folderId: number commands: FolderCommand[] onSaved: () => void } export function CommandManageDialog({ open, onOpenChange, folderId, commands, onSaved, }: CommandManageDialogProps) { const t = useTranslations("Folder.commandDropdown.manageDialog") const tCommon = useTranslations("Folder.common") const [drafts, setDrafts] = useState([]) const [saving, setSaving] = useState(false) useEffect(() => { if (open) { setDrafts( commands.map((c) => ({ id: c.id, name: c.name, command: c.command, deleted: false, })) ) } }, [open, commands]) const addDraft = () => { setDrafts((prev) => [ ...prev, { id: null, name: "", command: "", deleted: false }, ]) } const updateDraft = ( index: number, field: "name" | "command", value: string ) => { setDrafts((prev) => prev.map((d, i) => (i === index ? { ...d, [field]: value } : d)) ) } const removeDraft = (index: number) => { setDrafts((prev) => prev.map((d, i) => (i === index ? { ...d, deleted: true } : d)) ) } const handleSave = async () => { setSaving(true) try { for (const draft of drafts) { if (draft.deleted && draft.id != null) { await deleteFolderCommand(draft.id) } else if (draft.deleted) { continue } else if (draft.id == null && draft.name && draft.command) { await createFolderCommand(folderId, draft.name, draft.command) } else if (draft.id != null) { const orig = commands.find((c) => c.id === draft.id) if ( orig && (orig.name !== draft.name || orig.command !== draft.command) ) { await updateFolderCommand(draft.id, draft.name, draft.command) } } } onSaved() onOpenChange(false) } catch (err) { console.error("Failed to save commands:", err) } finally { setSaving(false) } } const visibleDrafts = drafts.filter((d) => !d.deleted) return ( {t("title")}
{visibleDrafts.length === 0 && (

{t("empty")}

)} {drafts.map( (draft, index) => !draft.deleted && (
updateDraft(index, "name", e.target.value) } className="h-8 text-sm flex-1" /> updateDraft(index, "command", e.target.value) } className="h-8 text-sm font-mono flex-[2]" />
) )}
) }