"use client";
import { jsxs, jsx } from 'react/jsx-runtime';
import { useState } from 'react';
import { Trash2 } from 'lucide-react';
import { Button } from '../../../../../../../ui/src/components/button.mjs';
import { Input } from '../../../../../../../ui/src/components/input.mjs';
import { Label } from '../../../../../../../ui/src/components/label.mjs';
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from '../../../../../../../ui/src/components/select.mjs';
import { MinimalTiptapEditor } from '../../../../../../../ui/src/components/minimal-tiptap/minimal-tiptap.mjs';
import SearchSelect from '../../../../../../../ui/src/components/search-select.mjs';
import { useTaskMutations, useSearchUsers } from '../../hooks/kanban-hooks.mjs';
import { PRIORITY_OPTIONS } from '../../../utils.mjs';

function TaskForm({
  columnId,
  boardId,
  taskId,
  task,
  columns,
  onClose,
  onSuccess,
  onDelete
}) {
  const isEditing = !!taskId;
  const {
    createTask,
    updateTask,
    moveTask,
    isCreating,
    isUpdating,
    isDeleting,
    isMoving
  } = useTaskMutations();
  const [title, setTitle] = useState(task?.title || "");
  const [description, setDescription] = useState(task?.description || "");
  const [priority, setPriority] = useState(
    task?.priority || "MEDIUM"
  );
  const [selectedColumnId, setSelectedColumnId] = useState(
    task?.columnId || columnId
  );
  const [assigneeId, setAssigneeId] = useState(task?.assigneeId || "");
  const [error, setError] = useState(null);
  const { data: users = [] } = 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__ */ jsxs("form", { onSubmit: handleSubmit, className: "space-y-4", children: [
    /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
      /* @__PURE__ */ jsx(Label, { htmlFor: "title", children: "Title *" }),
      /* @__PURE__ */ jsx(
        Input,
        {
          id: "title",
          value: title,
          onChange: (e) => setTitle(e.target.value),
          placeholder: "e.g., Fix login bug",
          disabled: isPending
        }
      )
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-4", children: [
      /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: "priority", children: "Priority" }),
        /* @__PURE__ */ jsxs(
          Select,
          {
            value: priority,
            onValueChange: (v) => setPriority(v),
            children: [
              /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, { placeholder: "Select priority" }) }),
              /* @__PURE__ */ jsx(SelectContent, { children: PRIORITY_OPTIONS.map((option) => /* @__PURE__ */ jsx(SelectItem, { value: option.value, children: option.label }, option.value)) })
            ]
          }
        )
      ] }),
      /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsx(Label, { htmlFor: "column", children: "Column" }),
        /* @__PURE__ */ jsxs(Select, { value: selectedColumnId, onValueChange: setSelectedColumnId, children: [
          /* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, { placeholder: "Select column" }) }),
          /* @__PURE__ */ jsx(SelectContent, { children: columns.map((col) => /* @__PURE__ */ jsx(SelectItem, { value: col.id, children: col.title }, col.id)) })
        ] })
      ] })
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
      /* @__PURE__ */ jsx(Label, { htmlFor: "assignee", children: "Assignee" }),
      /* @__PURE__ */ jsx(
        SearchSelect,
        {
          options: userOptions,
          value: assigneeId,
          onChange: setAssigneeId,
          placeholder: "Select assignee",
          emptyMessage: "No users found"
        }
      )
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
      /* @__PURE__ */ jsx(Label, { children: "Description" }),
      /* @__PURE__ */ jsx(
        MinimalTiptapEditor,
        {
          value: description,
          onChange: (value) => setDescription(typeof value === "string" ? value : ""),
          output: "markdown",
          placeholder: "Describe the task...",
          editable: !isPending,
          className: "min-h-[150px]"
        }
      )
    ] }),
    error && /* @__PURE__ */ jsx("div", { className: "p-3 text-sm text-red-600 bg-red-50 border border-red-200 rounded-md", children: error }),
    /* @__PURE__ */ jsxs("div", { className: "flex justify-between pt-2", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
        /* @__PURE__ */ jsx(Button, { type: "submit", disabled: isPending, children: isPending ? isEditing ? "Updating..." : "Creating..." : isEditing ? "Update Task" : "Create Task" }),
        /* @__PURE__ */ jsx(
          Button,
          {
            type: "button",
            variant: "outline",
            onClick: onClose,
            disabled: isPending,
            children: "Cancel"
          }
        )
      ] }),
      isEditing && onDelete && /* @__PURE__ */ jsxs(
        Button,
        {
          type: "button",
          variant: "destructive",
          onClick: onDelete,
          disabled: isPending,
          children: [
            /* @__PURE__ */ jsx(Trash2, { className: "mr-2 h-4 w-4" }),
            "Delete"
          ]
        }
      )
    ] })
  ] });
}

export { TaskForm };
