import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import { Button } from "../../components/ui/button";
import { Dialog, DialogContent, DialogFooter, } from "../../components/ui/dialog";
import { StyledDialogTitle } from "../../components/ui/styled-dialog-title";
import { Input } from "../../components/ui/input";
import { Label } from "../../components/ui/label";
import { Textarea } from "../../components/ui/textarea";
import { Select } from "../../components/ui/select";
import { Target } from "lucide-react";
import { createGoal, updateGoal } from "../services/goalService";
const CUSTOM_VALUE = "__custom__";
const STATUS_OPTIONS = [
    { value: "Open", label: "Open" },
    { value: "InProgress", label: "In progress" },
    { value: "Achieved", label: "Achieved" },
    { value: "Abandoned", label: "Abandoned" },
];
function readStringField(data, key) {
    if (data && typeof data === "object" && !Array.isArray(data)) {
        const value = data[key];
        if (typeof value === "string")
            return value;
    }
    return "";
}
function readStringListField(data, key) {
    if (data && typeof data === "object" && !Array.isArray(data)) {
        const value = data[key];
        if (Array.isArray(value)) {
            return value.filter((x) => typeof x === "string").join("\n");
        }
    }
    return "";
}
export function GoalDialog(props) {
    const { open, onOpenChange, projectId, catalog, goal, onSaved } = props;
    const isEdit = !!goal;
    const [definitionId, setDefinitionId] = useState(CUSTOM_VALUE);
    const [title, setTitle] = useState("");
    const [description, setDescription] = useState("");
    const [status, setStatus] = useState("Open");
    const [summary, setSummary] = useState("");
    const [recommendations, setRecommendations] = useState("");
    const [submitting, setSubmitting] = useState(false);
    useEffect(() => {
        if (!open)
            return;
        if (goal) {
            setDefinitionId(goal.sourceGoalTemplateId ?? CUSTOM_VALUE);
            setTitle(goal.title ?? "");
            setDescription(goal.description ?? "");
            setStatus(goal.status);
            setSummary(readStringField(goal.data, "summary"));
            setRecommendations(readStringListField(goal.data, "recommendations"));
        }
        else {
            setDefinitionId(CUSTOM_VALUE);
            setTitle("");
            setDescription("");
            setStatus("Open");
            setSummary("");
            setRecommendations("");
        }
    }, [open, goal]);
    const definitionOptions = useMemo(() => [
        { value: CUSTOM_VALUE, label: "Custom goal" },
        ...catalog.map((def) => ({
            value: def.id,
            label: def.title,
            ...(def.description ? { description: def.description } : {}),
        })),
    ], [catalog]);
    const onSelectDefinition = (value) => {
        setDefinitionId(value);
        if (value !== CUSTOM_VALUE) {
            const def = catalog.find((d) => d.id === value);
            if (def && !title.trim())
                setTitle(def.title);
        }
    };
    const buildData = () => {
        const data = {};
        if (summary.trim())
            data.summary = summary.trim();
        const recs = recommendations
            .split("\n")
            .map((line) => line.trim())
            .filter(Boolean);
        if (recs.length > 0)
            data.recommendations = recs;
        return Object.keys(data).length > 0 ? data : null;
    };
    const submit = async () => {
        if (!title.trim()) {
            toast.error("A goal title is required");
            return;
        }
        setSubmitting(true);
        try {
            const data = buildData();
            if (isEdit && goal) {
                const result = await updateGoal({
                    goalId: goal.goalId,
                    title: title.trim(),
                    status,
                    description: description.trim() ? description.trim() : undefined,
                    clearDescription: !description.trim(),
                    // Merge the structured fields into any existing payload (preserves
                    // other keys an agent may have attached). Full/raw editing is Phase 5.
                    dataPatch: data ?? undefined,
                });
                if (result.type !== "success") {
                    toast.error(result.summary || "Failed to update goal");
                    return;
                }
                toast.success("Goal updated");
            }
            else {
                const result = await createGoal({
                    projectId,
                    title: title.trim(),
                    description: description.trim() ? description.trim() : undefined,
                    sourceGoalTemplateId: definitionId !== CUSTOM_VALUE ? definitionId : undefined,
                    data: data ?? undefined,
                });
                if (result.type !== "success") {
                    toast.error(result.summary || "Failed to create goal");
                    return;
                }
                toast.success("Goal created");
            }
            onOpenChange(false);
            onSaved();
        }
        finally {
            setSubmitting(false);
        }
    };
    return (_jsx(Dialog, { open: open, onOpenChange: onOpenChange, children: _jsxs(DialogContent, { className: "max-w-lg", "data-testid": "taskboard-goal-dialog", children: [_jsx(StyledDialogTitle, { icon: _jsx(Target, { strokeWidth: 1 }), title: isEdit ? "Edit goal" : "Add goal", subtitle: isEdit
                        ? "Update this goal's details"
                        : "Create a goal from the catalog or a custom one" }), _jsxs("div", { className: "grid min-h-0 flex-1 gap-6 overflow-y-auto p-6", children: [!isEdit && catalog.length > 0 ? (_jsxs("div", { className: "grid gap-2", children: [_jsx(Label, { htmlFor: "goalDefinition", children: "Goal type" }), _jsx(Select, { id: "goalDefinition", value: definitionId, onValueChange: onSelectDefinition, options: definitionOptions, placeholder: "Custom goal" })] })) : null, _jsxs("div", { className: "grid gap-2", children: [_jsx(Label, { htmlFor: "goalTitle", children: "Title" }), _jsx(Input, { id: "goalTitle", "data-testid": "taskboard-goal-title-input", value: title, onChange: (e) => setTitle(e.target.value), placeholder: "e.g. Review all pages of Site X" })] }), _jsxs("div", { className: "grid gap-2", children: [_jsx(Label, { htmlFor: "goalDescription", children: "Description" }), _jsx(Textarea, { id: "goalDescription", className: "text-xs", value: description, onChange: (e) => setDescription(e.target.value), placeholder: "Optional description", rows: 2 })] }), isEdit ? (_jsxs("div", { className: "grid gap-2", children: [_jsx(Label, { htmlFor: "goalStatus", children: "Status" }), _jsx(Select, { id: "goalStatus", value: status, onValueChange: (value) => setStatus(value), options: STATUS_OPTIONS })] })) : null, _jsxs("div", { className: "grid gap-2", children: [_jsx(Label, { htmlFor: "goalSummary", children: "Summary" }), _jsx(Textarea, { id: "goalSummary", className: "text-xs", value: summary, onChange: (e) => setSummary(e.target.value), placeholder: "Optional summary (markdown). Attached to the goal data.", rows: 3 })] }), _jsxs("div", { className: "grid gap-2", children: [_jsx(Label, { htmlFor: "goalRecommendations", children: "Recommendations" }), _jsx(Textarea, { id: "goalRecommendations", className: "text-xs", value: recommendations, onChange: (e) => setRecommendations(e.target.value), placeholder: "One per line", rows: 3 })] })] }), _jsxs(DialogFooter, { className: "flex flex-row items-center justify-end gap-2 p-4", children: [_jsx(Button, { variant: "outline", onClick: () => onOpenChange(false), disabled: submitting, children: "Cancel" }), _jsx(Button, { onClick: submit, disabled: submitting || !title.trim(), "data-testid": "taskboard-goal-submit-button", children: submitting
                                ? "Saving..."
                                : isEdit
                                    ? "Save goal"
                                    : "Create goal" })] })] }) }));
}
//# sourceMappingURL=GoalDialog.js.map