"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { Button } from "@open-mercato/ui/primitives/button";
import { Input } from "@open-mercato/ui/primitives/input";
import { EmailInput } from "@open-mercato/ui/primitives/email-input";
import { FormHeader } from "@open-mercato/ui/backend/forms";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue
} from "@open-mercato/ui/primitives/select";
import { Spinner } from "@open-mercato/ui/primitives/spinner";
import { Separator } from "@open-mercato/ui/primitives/separator";
import { JsonDisplay } from "@open-mercato/ui/backend/JsonDisplay";
import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useQuery } from "@tanstack/react-query";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { MobileTaskForm } from "../../../components/mobile/MobileTaskForm.js";
import { useIsMobile } from "@open-mercato/ui/hooks/useIsMobile";
import { RecordNotFoundState, ErrorMessage } from "@open-mercato/ui/backend/detail";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("workflows");
function UserTaskDetailPage({ params }) {
  const router = useRouter();
  const t = useT();
  const isMobile = useIsMobile();
  const [formData, setFormData] = React.useState({});
  const [comments, setComments] = React.useState("");
  const [submitting, setSubmitting] = React.useState(false);
  const [invalidField, setInvalidField] = React.useState(null);
  const { data: task, isLoading, error } = useQuery({
    queryKey: ["workflow-task", params.id],
    queryFn: async () => {
      const result = await apiCall(
        `/api/workflows/tasks/${params.id}`
      );
      if (!result.ok) {
        const httpErr = new Error(
          result.status === 404 ? t("workflows.tasks.detail.notFound", "Task not found") : t("workflows.tasks.detail.loadFailed", "Failed to load task")
        );
        httpErr.status = result.status;
        throw httpErr;
      }
      return result.result?.data ?? null;
    }
  });
  const handleFieldChange = (fieldName, value) => {
    setFormData((prev) => ({
      ...prev,
      [fieldName]: value
    }));
    if (invalidField === fieldName) setInvalidField(null);
  };
  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!task) return;
    if (task.formSchema?.required) {
      for (const requiredField of task.formSchema.required) {
        if (!formData[requiredField] || formData[requiredField] === "") {
          const fieldSchema = task.formSchema.properties?.[requiredField];
          const fieldLabel = fieldSchema?.title ?? requiredField;
          flash(t("workflows.tasks.detail.validation.requiredField", { field: fieldLabel }), "error");
          setInvalidField(requiredField);
          if (typeof document !== "undefined") {
            const trigger = document.getElementById(requiredField);
            trigger?.scrollIntoView({ behavior: "smooth", block: "center" });
            trigger?.focus();
          }
          return;
        }
      }
    }
    setInvalidField(null);
    setSubmitting(true);
    try {
      const result = await apiCall(`/api/workflows/tasks/${params.id}/complete`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json"
        },
        body: JSON.stringify({
          formData,
          comments: comments || void 0
        })
      });
      if (result.ok) {
        flash(t("workflows.tasks.messages.completed"), "success");
        router.push("/backend/tasks");
      } else {
        const error2 = result.result;
        flash(error2?.error || t("workflows.tasks.messages.completeFailed"), "error");
      }
    } catch (err) {
      logger.error("Error completing task", { err });
      flash(t("workflows.tasks.messages.completeFailed"), "error");
    } finally {
      setSubmitting(false);
    }
  };
  const fieldValue = (fieldName) => {
    const val = formData[fieldName];
    if (val == null || val === false) return "";
    if (typeof val === "boolean") return "";
    return val;
  };
  const renderFormField = (fieldName, fieldSchema) => {
    const fieldType = fieldSchema.type || "string";
    const fieldTitle = fieldSchema.title || fieldName;
    const fieldDescription = fieldSchema.description;
    const required = task?.formSchema?.required?.includes(fieldName) || false;
    const enumValues = fieldSchema.enum;
    const inputClasses = "w-full px-3 py-2 border border-border rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring";
    const labelClasses = "block text-sm font-medium text-foreground mb-1";
    if (enumValues && Array.isArray(enumValues)) {
      return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
        /* @__PURE__ */ jsxs("label", { htmlFor: fieldName, className: labelClasses, children: [
          fieldTitle,
          required && /* @__PURE__ */ jsx("span", { className: "text-status-error-text ml-1", children: "*" })
        ] }),
        fieldDescription && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: fieldDescription }),
        /* @__PURE__ */ jsxs(
          Select,
          {
            value: fieldValue(fieldName) ? String(fieldValue(fieldName)) : void 0,
            onValueChange: (value) => handleFieldChange(fieldName, value ?? ""),
            children: [
              /* @__PURE__ */ jsx(
                SelectTrigger,
                {
                  id: fieldName,
                  className: `${inputClasses} ${invalidField === fieldName ? "ring-2 ring-status-error-border border-status-error-border" : ""}`,
                  "aria-required": required,
                  "aria-invalid": invalidField === fieldName ? true : void 0,
                  children: /* @__PURE__ */ jsx(SelectValue, { placeholder: t("workflows.tasks.detail.form.selectOption") })
                }
              ),
              /* @__PURE__ */ jsx(SelectContent, { children: enumValues.map((value) => /* @__PURE__ */ jsx(SelectItem, { value, children: value }, value)) })
            ]
          }
        )
      ] }, fieldName);
    }
    switch (fieldType) {
      case "string":
        if (fieldSchema.format === "email") {
          return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
            /* @__PURE__ */ jsxs("label", { htmlFor: fieldName, className: labelClasses, children: [
              fieldTitle,
              required && /* @__PURE__ */ jsx("span", { className: "text-status-error-text ml-1", children: "*" })
            ] }),
            fieldDescription && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: fieldDescription }),
            /* @__PURE__ */ jsx(
              EmailInput,
              {
                id: fieldName,
                value: fieldValue(fieldName),
                onChange: (e) => handleFieldChange(fieldName, e.target.value),
                required
              }
            )
          ] }, fieldName);
        }
        if (fieldSchema.format === "date") {
          return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
            /* @__PURE__ */ jsxs("label", { htmlFor: fieldName, className: labelClasses, children: [
              fieldTitle,
              required && /* @__PURE__ */ jsx("span", { className: "text-status-error-text ml-1", children: "*" })
            ] }),
            fieldDescription && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: fieldDescription }),
            /* @__PURE__ */ jsx(
              "input",
              {
                type: "date",
                id: fieldName,
                value: fieldValue(fieldName),
                onChange: (e) => handleFieldChange(fieldName, e.target.value),
                required,
                className: inputClasses
              }
            )
          ] }, fieldName);
        }
        if (fieldSchema.maxLength && fieldSchema.maxLength > 200) {
          return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
            /* @__PURE__ */ jsxs("label", { htmlFor: fieldName, className: labelClasses, children: [
              fieldTitle,
              required && /* @__PURE__ */ jsx("span", { className: "text-status-error-text ml-1", children: "*" })
            ] }),
            fieldDescription && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: fieldDescription }),
            /* @__PURE__ */ jsx(
              "textarea",
              {
                id: fieldName,
                value: fieldValue(fieldName),
                onChange: (e) => handleFieldChange(fieldName, e.target.value),
                required,
                rows: 4,
                className: inputClasses
              }
            )
          ] }, fieldName);
        }
        return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsxs("label", { htmlFor: fieldName, className: labelClasses, children: [
            fieldTitle,
            required && /* @__PURE__ */ jsx("span", { className: "text-status-error-text ml-1", children: "*" })
          ] }),
          fieldDescription && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: fieldDescription }),
          /* @__PURE__ */ jsx(
            Input,
            {
              type: "text",
              id: fieldName,
              value: fieldValue(fieldName),
              onChange: (e) => handleFieldChange(fieldName, e.target.value),
              required
            }
          )
        ] }, fieldName);
      case "number":
      case "integer":
        return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsxs("label", { htmlFor: fieldName, className: labelClasses, children: [
            fieldTitle,
            required && /* @__PURE__ */ jsx("span", { className: "text-status-error-text ml-1", children: "*" })
          ] }),
          fieldDescription && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: fieldDescription }),
          /* @__PURE__ */ jsx(
            Input,
            {
              type: "number",
              id: fieldName,
              value: fieldValue(fieldName),
              onChange: (e) => handleFieldChange(fieldName, e.target.value ? Number(e.target.value) : ""),
              required,
              step: fieldType === "integer" ? 1 : "any"
            }
          )
        ] }, fieldName);
      case "boolean":
        return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
            /* @__PURE__ */ jsx(
              "input",
              {
                type: "checkbox",
                id: fieldName,
                checked: !!formData[fieldName],
                onChange: (e) => handleFieldChange(fieldName, e.target.checked),
                className: "w-4 h-4 text-primary border-border rounded focus-visible:ring-ring"
              }
            ),
            /* @__PURE__ */ jsxs("label", { htmlFor: fieldName, className: "text-sm font-medium text-foreground", children: [
              fieldTitle,
              required && /* @__PURE__ */ jsx("span", { className: "text-status-error-text ml-1", children: "*" })
            ] })
          ] }),
          fieldDescription && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground ml-6", children: fieldDescription })
        ] }, fieldName);
      default:
        return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsxs("label", { htmlFor: fieldName, className: labelClasses, children: [
            fieldTitle,
            required && /* @__PURE__ */ jsx("span", { className: "text-status-error-text ml-1", children: "*" })
          ] }),
          fieldDescription && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: fieldDescription }),
          /* @__PURE__ */ jsx(
            Input,
            {
              type: "text",
              id: fieldName,
              value: fieldValue(fieldName),
              onChange: (e) => handleFieldChange(fieldName, e.target.value),
              required
            }
          )
        ] }, fieldName);
    }
  };
  const getStatusBadgeClass = (status) => {
    switch (status) {
      case "PENDING":
        return "bg-status-warning-bg text-status-warning-text";
      case "IN_PROGRESS":
        return "bg-status-info-bg text-status-info-text";
      case "COMPLETED":
        return "bg-status-success-bg text-status-success-text";
      case "CANCELLED":
        return "bg-muted text-foreground";
      default:
        return "bg-muted text-muted-foreground";
    }
  };
  if (isLoading) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-center py-12", children: [
      /* @__PURE__ */ jsx(Spinner, {}),
      /* @__PURE__ */ jsx("span", { className: "ml-3 text-muted-foreground", children: t("workflows.tasks.detail.loading") })
    ] }) }) });
  }
  const isNotFound = !isLoading && error?.status === 404;
  if (isNotFound) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      RecordNotFoundState,
      {
        label: t("workflows.tasks.detail.notFound", "Task not found"),
        backHref: "/backend/tasks",
        backLabel: t("workflows.tasks.detail.backToList", "Back to Tasks")
      }
    ) }) });
  }
  if (error || !task) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      ErrorMessage,
      {
        label: error?.message ?? t("workflows.tasks.detail.loadFailed", "Failed to load task"),
        action: /* @__PURE__ */ jsx(Button, { asChild: true, variant: "outline", size: "sm", children: /* @__PURE__ */ jsx(Link, { href: "/backend/tasks", children: t("workflows.tasks.detail.backToList", "Back to Tasks") }) })
      }
    ) }) });
  }
  const isCompletable = task.status === "PENDING" || task.status === "IN_PROGRESS";
  const isOverdue = task.dueDate && new Date(task.dueDate) < /* @__PURE__ */ new Date() && isCompletable;
  if (isMobile) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
      /* @__PURE__ */ jsx(
        FormHeader,
        {
          mode: "detail",
          backHref: "/backend/tasks",
          backLabel: t("workflows.tasks.backToList", "Back to tasks")
        }
      ),
      /* @__PURE__ */ jsx(
        MobileTaskForm,
        {
          task,
          formData,
          comments,
          submitting,
          isCompletable,
          isOverdue: !!isOverdue,
          onFieldChange: handleFieldChange,
          onCommentsChange: setComments,
          onSubmit: handleSubmit,
          onCancel: () => router.push("/backend/tasks"),
          getStatusBadgeClass
        }
      )
    ] }) }) });
  }
  return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsxs("div", { className: "max-w-4xl mx-auto space-y-6", children: [
    /* @__PURE__ */ jsx(
      FormHeader,
      {
        mode: "detail",
        backHref: "/backend/tasks",
        backLabel: t("workflows.tasks.backToList", "Back to tasks"),
        entityTypeLabel: t("workflows.tasks.detail.type", "User task"),
        title: task.taskName,
        subtitle: task.description || void 0,
        statusBadge: /* @__PURE__ */ jsx(
          "span",
          {
            className: `inline-flex items-center px-3 py-1 rounded text-sm font-medium ${getStatusBadgeClass(task.status)}`,
            children: t(`workflows.tasks.statuses.${task.status}`)
          }
        )
      }
    ),
    /* @__PURE__ */ jsx("div", { className: "space-y-3", children: isOverdue && /* @__PURE__ */ jsx("div", { className: "bg-status-error-bg border border-status-error-border rounded-lg p-3", children: /* @__PURE__ */ jsx("p", { className: "text-sm text-status-error-text font-medium", children: t("workflows.tasks.detail.overdueWarning") }) }) }),
    /* @__PURE__ */ jsx(Separator, {}),
    /* @__PURE__ */ jsxs("div", { className: "bg-muted/50 rounded-lg p-4 space-y-3", children: [
      /* @__PURE__ */ jsx("h2", { className: "text-sm font-semibold", children: t("workflows.tasks.detail.sections.taskInfo") }),
      /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 sm:grid-cols-2 gap-4 text-sm", children: [
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground", children: [
            t("workflows.tasks.fields.createdAt"),
            ":"
          ] }),
          /* @__PURE__ */ jsx("span", { className: "ml-2 text-foreground", children: new Date(task.createdAt).toLocaleString() })
        ] }),
        task.dueDate && /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground", children: [
            t("workflows.tasks.fields.dueDate"),
            ":"
          ] }),
          /* @__PURE__ */ jsx("span", { className: `ml-2 ${isOverdue ? "text-status-error-text font-medium" : "text-foreground"}`, children: new Date(task.dueDate).toLocaleString() })
        ] }),
        task.assignedTo && /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground", children: [
            t("workflows.tasks.detail.assignedTo"),
            ":"
          ] }),
          /* @__PURE__ */ jsx("span", { className: "ml-2 text-foreground", children: task.assignedTo })
        ] }),
        task.claimedBy && /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground", children: [
            t("workflows.tasks.claimedBy"),
            ":"
          ] }),
          /* @__PURE__ */ jsx("span", { className: "ml-2 text-foreground", children: task.claimedBy })
        ] }),
        /* @__PURE__ */ jsxs("div", { children: [
          /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground", children: [
            t("workflows.tasks.detail.workflowInstance"),
            ":"
          ] }),
          /* @__PURE__ */ jsxs(
            Link,
            {
              href: `/backend/instances/${task.workflowInstanceId}`,
              className: "ml-2 text-primary hover:underline text-xs font-mono",
              children: [
                task.workflowInstanceId.slice(0, 8),
                "..."
              ]
            }
          )
        ] })
      ] })
    ] }),
    !isCompletable && /* @__PURE__ */ jsx("div", { className: "bg-status-info-bg border border-status-info-border rounded-lg p-4", children: /* @__PURE__ */ jsx("p", { className: "text-sm text-status-info-text", children: t("workflows.tasks.detail.cannotComplete") }) }),
    isCompletable && /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsx(Separator, {}),
      /* @__PURE__ */ jsxs("form", { onSubmit: handleSubmit, className: "space-y-6", children: [
        task.formSchema?.properties && /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
          /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold", children: t("workflows.tasks.detail.sections.form") }),
          Object.keys(task.formSchema.properties).map(
            (fieldName) => renderFormField(fieldName, task.formSchema.properties[fieldName])
          )
        ] }),
        !task.formSchema?.properties && /* @__PURE__ */ jsx("div", { className: "bg-status-info-bg border border-status-info-border rounded-lg p-4", children: /* @__PURE__ */ jsx("p", { className: "text-sm text-status-info-text", children: t("workflows.tasks.detail.noFormSchema") }) }),
        /* @__PURE__ */ jsx(Separator, {}),
        /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
          /* @__PURE__ */ jsxs("label", { htmlFor: "comments", className: "block text-sm font-medium text-foreground", children: [
            t("workflows.tasks.detail.comments"),
            " (",
            t("workflows.tasks.detail.optional"),
            ")"
          ] }),
          /* @__PURE__ */ jsx(
            "textarea",
            {
              id: "comments",
              value: comments,
              onChange: (e) => setComments(e.target.value),
              rows: 3,
              className: "w-full px-3 py-2 border border-border rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
              placeholder: t("workflows.tasks.detail.commentsPlaceholder")
            }
          )
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-3 pt-4 sm:flex-row sm:items-center", children: [
          /* @__PURE__ */ jsx(
            Button,
            {
              type: "submit",
              disabled: submitting,
              className: "w-full sm:w-auto bg-primary text-primary-foreground hover:bg-primary/90",
              children: submitting ? t("workflows.tasks.detail.submitting") : t("workflows.tasks.detail.completeTask")
            }
          ),
          /* @__PURE__ */ jsx(
            Button,
            {
              type: "button",
              variant: "outline",
              onClick: () => router.push("/backend/tasks"),
              disabled: submitting,
              className: "w-full sm:w-auto",
              children: t("common.cancel")
            }
          )
        ] })
      ] })
    ] }),
    task.status === "COMPLETED" && task.formData && /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsx(Separator, {}),
      /* @__PURE__ */ jsx(
        JsonDisplay,
        {
          data: task.formData,
          title: t("workflows.tasks.detail.sections.submittedData"),
          maxInitialDepth: 2
        }
      ),
      task.comments && /* @__PURE__ */ jsxs("div", { className: "bg-muted/50 rounded-lg p-4", children: [
        /* @__PURE__ */ jsxs("p", { className: "text-sm font-medium text-foreground mb-2", children: [
          t("workflows.tasks.detail.comments"),
          ":"
        ] }),
        /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground whitespace-pre-wrap", children: task.comments })
      ] })
    ] })
  ] }) }) });
}
export {
  UserTaskDetailPage as default
};
//# sourceMappingURL=page.js.map
