"use client";
'use strict';

const jsxRuntime = require('react/jsx-runtime');
const React = require('react');
const LucideIcons = require('lucide-react');
const button = require('../../../../../../../ui/src/components/button.cjs');
const input = require('../../../../../../../ui/src/components/input.cjs');
const label = require('../../../../../../../ui/src/components/label.cjs');
const select = require('../../../../../../../ui/src/components/select.cjs');
const minimalTiptap = require('../../../../../../../ui/src/components/minimal-tiptap/minimal-tiptap.cjs');
const searchSelect = require('../../../../../../../ui/src/components/search-select.cjs');
const kanbanHooks = require('../../hooks/kanban-hooks.cjs');
const utils = require('../../../utils.cjs');

function TaskForm({
  columnId,
  boardId,
  taskId,
  task,
  columns,
  onClose,
  onSuccess,
  onDelete
}) {
  const isEditing = !!taskId;
  const {
    createTask,
    updateTask,
    moveTask,
    isCreating,
    isUpdating,
    isDeleting,
    isMoving
  } = kanbanHooks.useTaskMutations();
  const [title, setTitle] = React.useState(task?.title || "");
  const [description, setDescription] = React.useState(task?.description || "");
  const [priority, setPriority] = React.useState(
    task?.priority || "MEDIUM"
  );
  const [selectedColumnId, setSelectedColumnId] = React.useState(
    task?.columnId || columnId
  );
  const [assigneeId, setAssigneeId] = React.useState(task?.assigneeId || "");
  const [error, setError] = React.useState(null);
  const { data: users = [] } = kanbanHooks.useSearchUsers("", boardId);
  const userOptions = [
    { value: "", label: "Unassigned" },
    ...users.map((user) => ({ value: user.id, label: user.name }))
  ];
  const isPending = isCreating || isUpdating || isDeleting || isMoving;
  const handleSubmit = async (e) => {
    e.preventDefault();
    setError(null);
    if (!title.trim()) {
      setError("Title is required");
      return;
    }
    try {
      if (isEditing && taskId) {
        const isColumnChanging = task?.columnId && selectedColumnId !== task.columnId;
        if (isColumnChanging) {
          await updateTask(taskId, {
            title,
            description,
            priority,
            assigneeId: assigneeId || null
          });
          try {
            const targetColumn = columns.find((c) => c.id === selectedColumnId);
            const targetTasks = targetColumn?.tasks || [];
            const targetOrder = targetTasks.length > 0 ? Math.max(...targetTasks.map((t) => t.order)) + 1 : 0;
            await moveTask(taskId, selectedColumnId, targetOrder);
          } catch (moveErr) {
            const moveErrorMsg = moveErr instanceof Error ? moveErr.message : "Unknown error";
            setError(
              `Task properties were saved, but moving to the new column failed: ${moveErrorMsg}. You can try dragging the task to the desired column.`
            );
            return;
          }
        } else {
          await updateTask(taskId, {
            title,
            description,
            priority,
            columnId: selectedColumnId,
            assigneeId: assigneeId || null
          });
        }
      } else {
        await createTask({
          title,
          description,
          priority,
          columnId: selectedColumnId,
          assigneeId: assigneeId || void 0
        });
      }
      onSuccess();
    } catch (err) {
      setError(err instanceof Error ? err.message : "An error occurred");
    }
  };
  return /* @__PURE__ */ jsxRuntime.jsxs("form", { onSubmit: handleSubmit, className: "space-y-4", children: [
    /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-2", children: [
      /* @__PURE__ */ jsxRuntime.jsx(label.Label, { htmlFor: "title", children: "Title *" }),
      /* @__PURE__ */ jsxRuntime.jsx(
        input.Input,
        {
          id: "title",
          value: title,
          onChange: (e) => setTitle(e.target.value),
          placeholder: "e.g., Fix login bug",
          disabled: isPending
        }
      )
    ] }),
    /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "grid grid-cols-2 gap-4", children: [
      /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsxRuntime.jsx(label.Label, { htmlFor: "priority", children: "Priority" }),
        /* @__PURE__ */ jsxRuntime.jsxs(
          select.Select,
          {
            value: priority,
            onValueChange: (v) => setPriority(v),
            children: [
              /* @__PURE__ */ jsxRuntime.jsx(select.SelectTrigger, { children: /* @__PURE__ */ jsxRuntime.jsx(select.SelectValue, { placeholder: "Select priority" }) }),
              /* @__PURE__ */ jsxRuntime.jsx(select.SelectContent, { children: utils.PRIORITY_OPTIONS.map((option) => /* @__PURE__ */ jsxRuntime.jsx(select.SelectItem, { value: option.value, children: option.label }, option.value)) })
            ]
          }
        )
      ] }),
      /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsxRuntime.jsx(label.Label, { htmlFor: "column", children: "Column" }),
        /* @__PURE__ */ jsxRuntime.jsxs(select.Select, { value: selectedColumnId, onValueChange: setSelectedColumnId, children: [
          /* @__PURE__ */ jsxRuntime.jsx(select.SelectTrigger, { children: /* @__PURE__ */ jsxRuntime.jsx(select.SelectValue, { placeholder: "Select column" }) }),
          /* @__PURE__ */ jsxRuntime.jsx(select.SelectContent, { children: columns.map((col) => /* @__PURE__ */ jsxRuntime.jsx(select.SelectItem, { value: col.id, children: col.title }, col.id)) })
        ] })
      ] })
    ] }),
    /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-2", children: [
      /* @__PURE__ */ jsxRuntime.jsx(label.Label, { htmlFor: "assignee", children: "Assignee" }),
      /* @__PURE__ */ jsxRuntime.jsx(
        searchSelect,
        {
          options: userOptions,
          value: assigneeId,
          onChange: setAssigneeId,
          placeholder: "Select assignee",
          emptyMessage: "No users found"
        }
      )
    ] }),
    /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-2", children: [
      /* @__PURE__ */ jsxRuntime.jsx(label.Label, { children: "Description" }),
      /* @__PURE__ */ jsxRuntime.jsx(
        minimalTiptap.MinimalTiptapEditor,
        {
          value: description,
          onChange: (value) => setDescription(typeof value === "string" ? value : ""),
          output: "markdown",
          placeholder: "Describe the task...",
          editable: !isPending,
          className: "min-h-[150px]"
        }
      )
    ] }),
    error && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "p-3 text-sm text-red-600 bg-red-50 border border-red-200 rounded-md", children: error }),
    /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex justify-between pt-2", children: [
      /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-2", children: [
        /* @__PURE__ */ jsxRuntime.jsx(button.Button, { type: "submit", disabled: isPending, children: isPending ? isEditing ? "Updating..." : "Creating..." : isEditing ? "Update Task" : "Create Task" }),
        /* @__PURE__ */ jsxRuntime.jsx(
          button.Button,
          {
            type: "button",
            variant: "outline",
            onClick: onClose,
            disabled: isPending,
            children: "Cancel"
          }
        )
      ] }),
      isEditing && onDelete && /* @__PURE__ */ jsxRuntime.jsxs(
        button.Button,
        {
          type: "button",
          variant: "destructive",
          onClick: onDelete,
          disabled: isPending,
          children: [
            /* @__PURE__ */ jsxRuntime.jsx(LucideIcons.Trash2, { className: "mr-2 h-4 w-4" }),
            "Delete"
          ]
        }
      )
    ] })
  ] });
}

exports.TaskForm = TaskForm;
