"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { useRouter } from "next/navigation";
import { Page, PageBody } from "@open-mercato/ui/backend/Page";
import { Badge } from "@open-mercato/ui/primitives/badge";
import { LoadingMessage, ErrorMessage, RecordNotFoundState } from "@open-mercato/ui/backend/detail";
import { SendObjectMessageDialog } from "@open-mercato/ui/backend/messages";
import { readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { updateCrud } from "@open-mercato/ui/backend/utils/crud";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { LeaveRequestForm, buildLeaveRequestPayload } from "@open-mercato/core/modules/staff/components/LeaveRequestForm";
import { normalizeLeaveRequest, resolveStatusVariant, formatDateLabel, formatDateRange } from "../../../../lib/leaveRequestHelpers.js";
function StaffMyLeaveRequestDetailPage({ params }) {
  const id = params?.id;
  const t = useT();
  const router = useRouter();
  const [isLoading, setIsLoading] = React.useState(true);
  const [error, setError] = React.useState(null);
  const [isNotFound, setIsNotFound] = React.useState(false);
  const [record, setRecord] = React.useState(null);
  React.useEffect(() => {
    if (!id) {
      setIsNotFound(true);
      setIsLoading(false);
      return;
    }
    const requestId = id;
    let cancelled = false;
    async function load() {
      setIsLoading(true);
      setError(null);
      setIsNotFound(false);
      try {
        const params2 = new URLSearchParams({ page: "1", pageSize: "1", ids: requestId });
        const payload = await readApiResultOrThrow(
          `/api/staff/leave-requests?${params2.toString()}`,
          void 0,
          { errorMessage: t("staff.leaveRequests.errors.load", "Failed to load leave request.") }
        );
        const entry = Array.isArray(payload.items) ? payload.items[0] : null;
        if (!entry) {
          if (!cancelled) {
            setIsNotFound(true);
            setRecord(null);
          }
          return;
        }
        if (!cancelled) {
          setRecord(normalizeLeaveRequest(entry));
        }
      } catch (err) {
        if (!cancelled) {
          if (err.status === 404) {
            setIsNotFound(true);
            setRecord(null);
          } else {
            const message = err instanceof Error ? err.message : t("staff.leaveRequests.errors.load", "Failed to load leave request.");
            setError(message);
            setRecord(null);
          }
        }
      } finally {
        if (!cancelled) setIsLoading(false);
      }
    }
    void load();
    return () => {
      cancelled = true;
    };
  }, [id, t]);
  const status = record?.status ?? "pending";
  const memberLabel = record?.member?.displayName ?? null;
  const initialValues = React.useMemo(() => ({
    id: record?.id,
    memberId: record?.memberId ?? null,
    memberLabel,
    startDate: record?.startDate ?? null,
    endDate: record?.endDate ?? null,
    timezone: record?.timezone ?? null,
    unavailabilityReasonEntryId: record?.unavailabilityReasonEntryId ?? null,
    unavailabilityReasonValue: record?.unavailabilityReasonValue ?? null,
    note: record?.note ?? null,
    updatedAt: record?.updatedAt ?? null
  }), [record, memberLabel]);
  const dateSummary = formatDateRange(record?.startDate, record?.endDate);
  const handleSubmit = React.useCallback(async (values) => {
    if (!record?.id) return;
    const payload = buildLeaveRequestPayload(values, { id: record.id });
    await updateCrud("staff/leave-requests", payload, {
      errorMessage: t("staff.leaveRequests.form.errors.update", "Failed to update leave request.")
    });
    flash(t("staff.leaveRequests.form.flash.updated", "Leave request updated."), "success");
    router.push("/backend/staff/my-leave-requests");
  }, [record?.id, router, t]);
  if (isLoading) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(LoadingMessage, { label: t("staff.leaveRequests.form.loading", "Loading leave request...") }) }) });
  }
  if (isNotFound) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(
      RecordNotFoundState,
      {
        label: t("staff.leaveRequests.errors.notFound", "Leave request not found."),
        backHref: "/backend/staff/my-leave-requests",
        backLabel: t("staff.leaveRequests.actions.backToMyList", "Back to my leave requests")
      }
    ) }) });
  }
  if (error || !record) {
    return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsx(PageBody, { children: /* @__PURE__ */ jsx(ErrorMessage, { label: error ?? t("staff.leaveRequests.errors.load", "Failed to load leave request.") }) }) });
  }
  return /* @__PURE__ */ jsx(Page, { children: /* @__PURE__ */ jsxs(PageBody, { children: [
    /* @__PURE__ */ jsxs("div", { className: "mb-6 space-y-2 rounded-lg border bg-card p-4", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-3", children: [
        /* @__PURE__ */ jsx(Badge, { variant: resolveStatusVariant(status), children: t(`staff.leaveRequests.status.${status}`, status) }),
        record.decidedAt ? /* @__PURE__ */ jsxs("span", { className: "text-xs text-muted-foreground", children: [
          t("staff.leaveRequests.decision.at", "Decision at"),
          " ",
          formatDateLabel(record.decidedAt)
        ] }) : null
      ] }),
      record.decisionComment ? /* @__PURE__ */ jsxs("div", { className: "text-sm text-muted-foreground", children: [
        /* @__PURE__ */ jsx("div", { className: "font-medium text-foreground", children: t("staff.leaveRequests.decision.comment", "Decision comment") }),
        /* @__PURE__ */ jsx("p", { children: record.decisionComment })
      ] }) : null
    ] }),
    status === "pending" ? /* @__PURE__ */ jsx(
      LeaveRequestForm,
      {
        title: t("staff.leaveRequests.form.editTitle", "Leave request"),
        submitLabel: t("staff.leaveRequests.form.actions.save", "Save"),
        backHref: "/backend/staff/my-leave-requests",
        cancelHref: "/backend/staff/my-leave-requests",
        initialValues,
        onSubmit: handleSubmit,
        allowMemberSelect: false,
        memberLabel,
        extraActions: record.id ? /* @__PURE__ */ jsx(
          SendObjectMessageDialog,
          {
            object: {
              entityModule: "staff",
              entityType: "leave_request",
              entityId: record.id,
              sourceEntityType: "staff:leave_request",
              sourceEntityId: record.id,
              previewData: {
                title: memberLabel || t("staff.leaveRequests.messages.contextTitle", "Linked leave request"),
                subtitle: dateSummary || void 0,
                status: record?.status ?? void 0
              }
            },
            viewHref: `/backend/staff/leave-requests/${record.id}`,
            lockedType: "staff.leave_request_approval",
            requiredActionConfig: {
              mode: "required",
              options: [
                { id: "approve", label: t("staff.notifications.leaveRequest.actions.approve", "Approve") },
                { id: "reject", label: t("staff.notifications.leaveRequest.actions.reject", "Reject") }
              ]
            },
            defaultValues: {
              type: "staff.leave_request_approval",
              subject: t("staff.leaveRequests.messages.compose.subject", "Leave request approval needed"),
              body: t("staff.leaveRequests.messages.compose.body", "Please review this leave request and take action.")
            }
          }
        ) : null
      }
    ) : /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-4 text-sm text-muted-foreground", children: [
      /* @__PURE__ */ jsx("div", { className: "font-medium text-foreground", children: t("staff.leaveRequests.detail.summary", "Request details") }),
      /* @__PURE__ */ jsx("p", { children: memberLabel ? t("staff.leaveRequests.detail.member", "Team member") + `: ${memberLabel}` : null }),
      /* @__PURE__ */ jsxs("p", { children: [
        t("staff.leaveRequests.detail.dates", "Dates"),
        ": ",
        formatDateRange(record.startDate, record.endDate)
      ] }),
      record.unavailabilityReasonValue ? /* @__PURE__ */ jsxs("p", { children: [
        t("staff.leaveRequests.detail.reason", "Reason"),
        ": ",
        record.unavailabilityReasonValue
      ] }) : null,
      record.note ? /* @__PURE__ */ jsxs("p", { children: [
        t("staff.leaveRequests.detail.note", "Note"),
        ": ",
        record.note
      ] }) : null
    ] })
  ] }) });
}
export {
  StaffMyLeaveRequestDetailPage as default
};
//# sourceMappingURL=page.js.map
