"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { Plus } from "lucide-react";
import { Button } from "@open-mercato/ui/primitives/button";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@open-mercato/ui/primitives/dialog";
import { CrudForm } from "@open-mercato/ui/backend/CrudForm";
import { LoadingMessage, ErrorMessage, TabEmptyState } from "@open-mercato/ui/backend/detail";
import { readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { createCrud, updateCrud, deleteCrud } from "@open-mercato/ui/backend/utils/crud";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { surfaceRecordConflict } from "@open-mercato/ui/backend/conflicts";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useConfirmDialog } from "@open-mercato/ui/backend/confirm-dialog";
function JobHistorySection({ memberId }) {
  const t = useT();
  const { confirm: confirmDialog, ConfirmDialogElement } = useConfirmDialog();
  const [items, setItems] = React.useState([]);
  const [isLoading, setIsLoading] = React.useState(false);
  const [loadError, setLoadError] = React.useState(null);
  const [dialogOpen, setDialogOpen] = React.useState(false);
  const [dialogMode, setDialogMode] = React.useState("create");
  const [activeRecord, setActiveRecord] = React.useState(null);
  const [reloadToken, setReloadToken] = React.useState(0);
  const labels = React.useMemo(() => ({
    title: t("staff.teamMembers.detail.jobHistory.title", "Job history"),
    emptyTitle: t("staff.teamMembers.detail.jobHistory.emptyTitle", "No job history yet"),
    emptyAction: t("staff.teamMembers.detail.jobHistory.emptyAction", "Add job history"),
    add: t("staff.teamMembers.detail.jobHistory.add", "Add job"),
    edit: t("staff.teamMembers.detail.jobHistory.edit", "Edit job"),
    deleteConfirm: t("staff.teamMembers.detail.jobHistory.deleteConfirm", "Delete this job history entry?"),
    errorLoad: t("staff.teamMembers.detail.jobHistory.errorLoad", "Failed to load job history."),
    errorSave: t("staff.teamMembers.detail.jobHistory.errorSave", "Failed to save job history."),
    errorDelete: t("staff.teamMembers.detail.jobHistory.errorDelete", "Failed to delete job history."),
    conflict: t("staff.teamMembers.detail.jobHistory.conflict", "This record was modified by someone else. Refresh and try again."),
    loading: t("staff.teamMembers.detail.jobHistory.loading", "Loading job history..."),
    saved: t("staff.teamMembers.detail.jobHistory.saved", "Job history saved."),
    updated: t("staff.teamMembers.detail.jobHistory.updated", "Job history updated."),
    deleted: t("staff.teamMembers.detail.jobHistory.deleted", "Job history deleted."),
    present: t("staff.teamMembers.detail.jobHistory.present", "Present"),
    unknownDate: t("staff.teamMembers.detail.jobHistory.unknownDate", "Unknown date"),
    fields: {
      name: t("staff.teamMembers.detail.jobHistory.fields.name", "Role / title"),
      companyName: t("staff.teamMembers.detail.jobHistory.fields.companyName", "Company"),
      startDate: t("staff.teamMembers.detail.jobHistory.fields.startDate", "From"),
      endDate: t("staff.teamMembers.detail.jobHistory.fields.endDate", "To"),
      description: t("staff.teamMembers.detail.jobHistory.fields.description", "Description")
    },
    save: t("staff.teamMembers.detail.jobHistory.save", "Save job"),
    update: t("staff.teamMembers.detail.jobHistory.update", "Update job"),
    cancel: t("staff.teamMembers.detail.jobHistory.cancel", "Cancel")
  }), [t]);
  const fields = React.useMemo(() => [
    { id: "name", label: labels.fields.name, type: "text", required: true },
    { id: "companyName", label: labels.fields.companyName, type: "text" },
    { id: "startDate", label: labels.fields.startDate, type: "date", required: true, layout: "half" },
    { id: "endDate", label: labels.fields.endDate, type: "date", layout: "half" },
    { id: "description", label: labels.fields.description, type: "textarea" }
  ], [labels.fields]);
  const dateFormatter = React.useMemo(
    () => new Intl.DateTimeFormat(void 0, { year: "numeric", month: "short", day: "numeric" }),
    []
  );
  const loadJobHistory = React.useCallback(async () => {
    if (!memberId) return;
    setIsLoading(true);
    setLoadError(null);
    try {
      const params = new URLSearchParams({
        entityId: memberId,
        pageSize: "100",
        sortField: "startDate",
        sortDir: "desc"
      });
      const payload = await readApiResultOrThrow(
        `/api/staff/job-histories?${params.toString()}`,
        void 0,
        { errorMessage: labels.errorLoad }
      );
      const records = normalizeJobHistoryItems(payload?.items);
      setItems(records);
    } catch (error) {
      const message = error instanceof Error ? error.message : labels.errorLoad;
      setLoadError(message);
    } finally {
      setIsLoading(false);
    }
  }, [labels.errorLoad, memberId]);
  React.useEffect(() => {
    void loadJobHistory();
  }, [loadJobHistory, reloadToken]);
  const openCreateDialog = React.useCallback(() => {
    if (!memberId) return;
    setDialogMode("create");
    setActiveRecord(null);
    setDialogOpen(true);
  }, [memberId]);
  const openEditDialog = React.useCallback((record) => {
    setDialogMode("edit");
    setActiveRecord(record);
    setDialogOpen(true);
  }, []);
  const closeDialog = React.useCallback(() => {
    setDialogOpen(false);
    setActiveRecord(null);
  }, []);
  const handleSubmit = React.useCallback(async (values) => {
    if (!memberId) return;
    const payload = buildJobHistoryPayload(values);
    if (dialogMode === "edit" && activeRecord) {
      await updateCrud("staff/job-histories", { id: activeRecord.id, updatedAt: activeRecord.updatedAt, ...payload }, { errorMessage: labels.errorSave });
      flash(labels.updated, "success");
    } else {
      await createCrud("staff/job-histories", { entityId: memberId, ...payload }, { errorMessage: labels.errorSave });
      flash(labels.saved, "success");
    }
    closeDialog();
    setReloadToken((prev) => prev + 1);
  }, [activeRecord, closeDialog, dialogMode, labels.conflict, labels.errorSave, labels.saved, labels.updated, memberId]);
  const handleDelete = React.useCallback(async (record) => {
    const confirmed = await confirmDialog({
      title: labels.deleteConfirm,
      variant: "destructive"
    });
    if (!confirmed) return;
    try {
      await deleteCrud("staff/job-histories", {
        id: record.id,
        body: { id: record.id, updatedAt: record.updatedAt },
        errorMessage: labels.errorDelete
      });
      flash(labels.deleted, "success");
      setReloadToken((prev) => prev + 1);
    } catch (error) {
      if (surfaceRecordConflict(error, t)) return;
      flash(labels.errorDelete, "error");
    }
  }, [labels.deleteConfirm, labels.deleted, labels.errorDelete, confirmDialog, t]);
  const dialogTitle = dialogMode === "edit" ? labels.edit : labels.add;
  const initialValues = dialogMode === "edit" && activeRecord ? {
    name: activeRecord.name,
    companyName: activeRecord.companyName ?? "",
    description: activeRecord.description ?? "",
    startDate: toDateInputValue(activeRecord.startDate) ?? "",
    endDate: toDateInputValue(activeRecord.endDate) ?? ""
  } : {
    name: "",
    companyName: "",
    description: "",
    startDate: "",
    endDate: ""
  };
  const hasItems = items.length > 0;
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
    /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3", children: [
      /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold text-foreground", children: labels.title }),
      hasItems ? /* @__PURE__ */ jsxs(Button, { type: "button", size: "sm", onClick: openCreateDialog, disabled: !memberId, children: [
        /* @__PURE__ */ jsx(Plus, { className: "mr-2 h-4 w-4", "aria-hidden": true }),
        labels.add
      ] }) : null
    ] }),
    isLoading ? /* @__PURE__ */ jsx(LoadingMessage, { label: labels.loading }) : loadError ? /* @__PURE__ */ jsx(ErrorMessage, { label: loadError }) : items.length === 0 ? /* @__PURE__ */ jsx(
      TabEmptyState,
      {
        title: labels.emptyTitle,
        actionLabel: labels.emptyAction,
        onAction: openCreateDialog,
        disabled: !memberId
      }
    ) : /* @__PURE__ */ jsx("div", { className: "space-y-3", children: items.map((record) => /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card p-4", children: [
      /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-start justify-between gap-3", children: [
        /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
          /* @__PURE__ */ jsx("div", { className: "text-base font-semibold text-foreground", children: record.name }),
          /* @__PURE__ */ jsx("div", { className: "text-sm text-muted-foreground", children: formatDateRange(record, labels.present, labels.unknownDate, dateFormatter) }),
          record.companyName ? /* @__PURE__ */ jsx("div", { className: "text-sm text-foreground", children: record.companyName }) : null
        ] }),
        /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
          /* @__PURE__ */ jsx(Button, { type: "button", size: "sm", variant: "ghost", onClick: () => openEditDialog(record), children: labels.edit }),
          /* @__PURE__ */ jsx(Button, { type: "button", size: "sm", variant: "ghost", onClick: () => handleDelete(record), children: t("staff.teamMembers.actions.delete", "Delete") })
        ] })
      ] }),
      record.description ? /* @__PURE__ */ jsx("p", { className: "mt-3 text-sm text-muted-foreground", children: record.description }) : null
    ] }, record.id)) }),
    /* @__PURE__ */ jsx(Dialog, { open: dialogOpen, onOpenChange: (open) => open ? setDialogOpen(true) : closeDialog(), children: /* @__PURE__ */ jsxs(DialogContent, { className: "sm:max-w-2xl", children: [
      /* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { children: dialogTitle }) }),
      /* @__PURE__ */ jsx(
        CrudForm,
        {
          fields,
          initialValues,
          optimisticLockUpdatedAt: activeRecord?.updatedAt ?? null,
          onSubmit: handleSubmit,
          submitLabel: dialogMode === "edit" ? labels.update : labels.save,
          extraActions: /* @__PURE__ */ jsx(Button, { type: "button", variant: "ghost", onClick: closeDialog, children: labels.cancel }),
          embedded: true
        }
      )
    ] }) }),
    ConfirmDialogElement
  ] });
}
function normalizeJobHistoryItems(items) {
  if (!Array.isArray(items)) return [];
  return items.map((item) => {
    if (!item || typeof item !== "object") return null;
    const record = item;
    const rawId = record.id ?? record.job_history_id ?? null;
    const id = typeof rawId === "string" ? rawId : typeof rawId === "number" || typeof rawId === "bigint" ? String(rawId) : null;
    if (!id) return null;
    const name = typeof record.name === "string" ? record.name : "";
    return {
      id,
      name,
      companyName: typeof record.company_name === "string" ? record.company_name : typeof record.companyName === "string" ? record.companyName : null,
      description: typeof record.description === "string" ? record.description : null,
      startDate: typeof record.start_date === "string" ? record.start_date : typeof record.startDate === "string" ? record.startDate : null,
      endDate: typeof record.end_date === "string" ? record.end_date : typeof record.endDate === "string" ? record.endDate : null,
      updatedAt: typeof record.updated_at === "string" ? record.updated_at : typeof record.updatedAt === "string" ? record.updatedAt : void 0
    };
  }).filter((value) => value !== null);
}
function buildJobHistoryPayload(values) {
  const payload = {
    name: values.name?.trim() ?? "",
    companyName: values.companyName?.trim() || null,
    description: values.description?.trim() || null
  };
  if (values.startDate) payload.startDate = values.startDate;
  if (values.endDate) payload.endDate = values.endDate;
  return payload;
}
import { toDateInputValue } from "@open-mercato/shared/lib/date/format";
function formatDateRange(record, presentLabel, unknownLabel, formatter) {
  const start = record.startDate ? new Date(record.startDate) : null;
  const end = record.endDate ? new Date(record.endDate) : null;
  const startLabel = start && !Number.isNaN(start.getTime()) ? formatter.format(start) : unknownLabel;
  const endLabel = end && !Number.isNaN(end.getTime()) ? formatter.format(end) : presentLabel;
  return `${startLabel} \u2014 ${endLabel}`;
}
export {
  JobHistorySection
};
//# sourceMappingURL=JobHistorySection.js.map
