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 { Plus } from "lucide-react";
import { createTask } from "../services/taskService";
import { TaskAssigneePicker } from "./TaskAssigneePicker";
export function CreateTaskDialog(props) {
    const { open, onOpenChange, projectId, parentTaskId, availableParentTasks = [], onCreated, } = props;
    const [title, setTitle] = useState("");
    const [description, setDescription] = useState("");
    const [status, setStatus] = useState("Todo");
    const [priority, setPriority] = useState("");
    const [assignee, setAssignee] = useState(null);
    const [selectedParentTaskId, setSelectedParentTaskId] = useState(parentTaskId ?? "none");
    const [submitting, setSubmitting] = useState(false);
    useEffect(() => {
        if (open)
            return;
        setTitle("");
        setDescription("");
        setStatus("Todo");
        setPriority("");
        setAssignee(null);
        setSelectedParentTaskId(parentTaskId ?? "none");
    }, [open, parentTaskId, projectId]);
    const parentTaskOptions = useMemo(() => {
        const options = availableParentTasks.map((task) => {
            const taskLabel = task.taskKey || task.taskId.slice(0, 8).toUpperCase();
            return {
                value: task.taskId,
                label: `${taskLabel} - ${task.title}`,
            };
        });
        if (parentTaskId &&
            !options.some((option) => option.value === parentTaskId)) {
            options.unshift({
                value: parentTaskId,
                label: `[Parent: ${parentTaskId.substring(0, 8)}...]`,
            });
        }
        return [{ value: "none", label: "None" }, ...options];
    }, [availableParentTasks, parentTaskId]);
    const showParentTaskField = parentTaskOptions.length > 1 || !!parentTaskId;
    const submit = async () => {
        if (!title.trim()) {
            toast.error("Task title is required");
            return;
        }
        const body = {
            projectId,
            parentTaskId: selectedParentTaskId === "none" ? null : selectedParentTaskId,
            title: title.trim(),
            description: description.trim() ? description.trim() : undefined,
            status,
            priority: priority ? priority : null,
            assigneeType: assignee?.assigneeType ?? null,
            assigneeId: assignee?.assigneeId ?? null,
        };
        setSubmitting(true);
        try {
            const result = await createTask(body);
            if (result.type !== "success") {
                toast.error(result.summary || "Failed to create task");
                return;
            }
            toast.success("Task created");
            onOpenChange(false);
            await onCreated();
        }
        finally {
            setSubmitting(false);
        }
    };
    return (_jsx(Dialog, { open: open, onOpenChange: onOpenChange, children: _jsxs(DialogContent, { className: "max-w-lg", children: [_jsx(StyledDialogTitle, { icon: _jsx(Plus, { strokeWidth: 1 }), title: "Create Task", subtitle: selectedParentTaskId !== "none"
                        ? "Create a subtask"
                        : "Add a new task to this project" }), _jsxs("div", { className: "grid min-h-0 flex-1 gap-6 overflow-y-auto overscroll-y-contain p-6", children: [_jsxs("div", { className: "grid gap-2", children: [_jsx(Label, { htmlFor: "taskTitle", children: "Title *" }), _jsx(Input, { id: "taskTitle", value: title, onChange: (e) => setTitle(e.target.value), placeholder: "e.g. Implement user authentication", onKeyDown: (e) => {
                                        if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
                                            e.preventDefault();
                                            void submit();
                                        }
                                    } })] }), _jsxs("div", { className: "grid gap-2", children: [_jsx(Label, { htmlFor: "taskDescription", children: "Description" }), _jsx(Textarea, { id: "taskDescription", value: description, onChange: (e) => setDescription(e.target.value), placeholder: "Optional description", rows: 4 })] }), showParentTaskField && (_jsxs("div", { className: "grid gap-2", children: [_jsx(Label, { htmlFor: "taskParent", children: "Parent Task" }), _jsx(Select, { id: "taskParent", "data-testid": "taskboard-create-task-parent-select", value: selectedParentTaskId, onValueChange: setSelectedParentTaskId, options: parentTaskOptions, disabled: submitting, searchable: parentTaskOptions.length > 8, searchPlaceholder: "Search tasks...", emptyMessage: "No matching tasks" })] })), _jsxs("div", { className: "grid grid-cols-2 gap-4", children: [_jsxs("div", { className: "grid gap-2", children: [_jsx(Label, { htmlFor: "taskStatus", children: "Status" }), _jsx(Select, { id: "taskStatus", value: status, onValueChange: (v) => setStatus(v), options: [
                                                { value: "Todo", label: "Todo" },
                                                { value: "Waiting", label: "Waiting" },
                                                { value: "InProgress", label: "In progress" },
                                                { value: "Review", label: "Review" },
                                                { value: "Done", label: "Done" },
                                            ] })] }), _jsxs("div", { className: "grid gap-2", children: [_jsx(Label, { htmlFor: "taskPriority", children: "Priority" }), _jsx(Select, { id: "taskPriority", value: priority, onValueChange: (v) => setPriority(v), options: [
                                                { value: "", label: "None" },
                                                { value: "Low", label: "Low" },
                                                { value: "Medium", label: "Medium" },
                                                { value: "High", label: "High" },
                                                { value: "Critical", label: "Critical" },
                                            ] })] })] }), _jsxs("div", { className: "grid gap-2", children: [_jsx(Label, { children: "Assignee" }), _jsx(TaskAssigneePicker, { projectId: projectId, assigneeType: assignee?.assigneeType ?? null, value: assignee?.assigneeId ?? null, displayValue: assignee?.displayName ?? null, disabled: submitting, onChange: setAssignee, placeholder: "Unassigned" })] })] }), _jsxs(DialogFooter, { className: "flex-row justify-end p-4", children: [_jsx(Button, { variant: "outline", onClick: () => onOpenChange(false), disabled: submitting, children: "Cancel" }), _jsx(Button, { onClick: submit, disabled: submitting || !title.trim(), children: submitting ? "Creating..." : "Create Task" })] })] }) }));
}
//# sourceMappingURL=CreateTaskDialog.js.map