"use client";
import { jsx, jsxs } from "react/jsx-runtime";
import * as React from "react";
import { apiCall, readApiResultOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { Button } from "@open-mercato/ui/primitives/button";
import { Input } from "@open-mercato/ui/primitives/input";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { useActiveTimesheetTimer } from "../../../lib/timesheets-ui/useActiveTimesheetTimer.js";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { startTimerEntry } from "../../../lib/timesheets-ui/startTimer.js";
import { resolveTimerActionError } from "../../../lib/timesheets-ui/timerErrors.js";
import { DEFAULT_SETTINGS, hydrateSettings } from "./config.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("staff");
const TIMER_WIDGET_MUTATION_CONTEXT_ID = "staff-timesheets-time-reporting-widget";
function formatElapsed(startedAt) {
  const elapsed = Math.max(0, Date.now() - new Date(startedAt).getTime());
  const totalSeconds = Math.floor(elapsed / 1e3);
  const hours = Math.floor(totalSeconds / 3600);
  const minutes = Math.floor(totalSeconds % 3600 / 60);
  const seconds = totalSeconds % 60;
  return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
}
const TimeReportingWidget = ({
  mode,
  settings = DEFAULT_SETTINGS,
  onSettingsChange,
  refreshToken,
  onRefreshStateChange
}) => {
  const t = useT();
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: TIMER_WIDGET_MUTATION_CONTEXT_ID,
    blockedMessage: t("ui.forms.flash.saveBlocked", "Save blocked by validation")
  });
  const hydrated = React.useMemo(() => hydrateSettings(settings), [settings]);
  const [projects, setProjects] = React.useState([]);
  const [selectedProjectId, setSelectedProjectId] = React.useState(hydrated.lastProjectId);
  const [notes, setNotes] = React.useState("");
  const [elapsed, setElapsed] = React.useState("00:00:00");
  const [loading, setLoading] = React.useState(true);
  const [actionLoading, setActionLoading] = React.useState(false);
  const [error, setError] = React.useState(null);
  const didLoadRef = React.useRef(false);
  const activeTimer = useActiveTimesheetTimer();
  const {
    staffMemberId,
    entryId: activeEntryId,
    running: timerRunning,
    startedAt: timerStartedAt,
    projectId: activeProjectId,
    projectName: activeProjectName,
    isLoading: activeTimerLoading,
    error: activeTimerError,
    refresh: refreshActiveTimer
  } = activeTimer;
  const loadState = React.useCallback(async () => {
    onRefreshStateChange?.(true);
    setLoading(true);
    setError(null);
    try {
      const assignmentsRes = await readApiResultOrThrow(
        "/api/staff/timesheets/my-projects?pageSize=100",
        void 0,
        { errorMessage: "", fallback: { items: [] } }
      );
      const assignmentItems = Array.isArray(assignmentsRes.items) ? assignmentsRes.items : [];
      const projectIds = assignmentItems.map((item) => String(item.time_project_id ?? item.timeProjectId ?? "")).filter((id) => id.length > 0);
      if (projectIds.length > 0) {
        const projectsRes = await readApiResultOrThrow(
          `/api/staff/timesheets/time-projects?ids=${projectIds.join(",")}&pageSize=100`,
          void 0,
          { errorMessage: "", fallback: { items: [] } }
        );
        const items = Array.isArray(projectsRes.items) ? projectsRes.items : [];
        setProjects(items.map((item) => ({
          id: String(item.id ?? ""),
          name: String(item.name ?? ""),
          code: typeof item.code === "string" ? item.code : null
        })));
      } else {
        setProjects([]);
      }
    } catch (err) {
      logger.error("staff.timesheets.timeReporting.load", { err });
      setError(t("staff.timesheets.widgets.timeReporting.error", "Failed to load timer state"));
    } finally {
      setLoading(false);
      onRefreshStateChange?.(false);
    }
  }, [onRefreshStateChange, t]);
  React.useEffect(() => {
    if (!didLoadRef.current) {
      didLoadRef.current = true;
      void loadState();
      return;
    }
    void Promise.allSettled([loadState(), refreshActiveTimer()]);
  }, [loadState, refreshActiveTimer, refreshToken]);
  React.useEffect(() => {
    if (!timerRunning || !timerStartedAt) {
      setElapsed("00:00:00");
      return;
    }
    const tick = () => setElapsed(formatElapsed(timerStartedAt));
    tick();
    const interval = setInterval(tick, 1e3);
    return () => clearInterval(interval);
  }, [timerRunning, timerStartedAt]);
  const handleStart = React.useCallback(async () => {
    if (!selectedProjectId || !staffMemberId) return;
    if (timerRunning) return;
    setActionLoading(true);
    try {
      const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
      const startPayload = {
        staffMemberId,
        timeProjectId: selectedProjectId,
        date: today,
        notes: notes.trim() || null
      };
      await runMutation({
        operation: () => startTimerEntry(startPayload),
        context: {
          formId: TIMER_WIDGET_MUTATION_CONTEXT_ID,
          resourceKind: "staff.timesheets.time_entry",
          resourceId: staffMemberId,
          staffMemberId,
          action: "timer-start",
          retryLastMutation
        },
        mutationPayload: startPayload
      });
      onSettingsChange({ ...hydrated, lastProjectId: selectedProjectId });
      await refreshActiveTimer();
    } catch (err) {
      logger.error("staff.timesheets.timeReporting.start", { err });
      setError(resolveTimerActionError(err, t("staff.timesheets.widgets.timeReporting.startError", "Failed to start timer")));
    } finally {
      setActionLoading(false);
    }
  }, [selectedProjectId, staffMemberId, timerRunning, notes, runMutation, retryLastMutation, hydrated, onSettingsChange, refreshActiveTimer, t]);
  const handleStop = React.useCallback(async () => {
    if (!activeEntryId || !staffMemberId) return;
    setActionLoading(true);
    try {
      const stopPayload = {
        id: activeEntryId,
        action: "timer-stop",
        staffMemberId
      };
      await runMutation({
        operation: () => apiCall(`/api/staff/timesheets/time-entries/${activeEntryId}/timer-stop`, { method: "POST" }),
        context: {
          formId: TIMER_WIDGET_MUTATION_CONTEXT_ID,
          resourceKind: "staff.timesheets.time_entry",
          resourceId: activeEntryId,
          staffMemberId,
          action: "timer-stop",
          retryLastMutation
        },
        mutationPayload: stopPayload
      });
      await refreshActiveTimer();
    } catch (err) {
      logger.error("staff.timesheets.timeReporting.stop", { err });
      setError(resolveTimerActionError(err, t("staff.timesheets.widgets.timeReporting.stopError", "Failed to stop timer")));
    } finally {
      setActionLoading(false);
    }
  }, [activeEntryId, staffMemberId, runMutation, retryLastMutation, refreshActiveTimer, t]);
  if (mode === "settings") {
    return /* @__PURE__ */ jsx("div", { className: "space-y-2 text-sm", children: /* @__PURE__ */ jsx("p", { className: "text-muted-foreground", children: t("staff.timesheets.widgets.timeReporting.settings.description", "No additional settings. Select a project and start tracking from the widget.") }) });
  }
  if (loading || activeTimerLoading) {
    return /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center py-8", children: /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("staff.timesheets.widgets.timeReporting.loading", "Loading...") }) });
  }
  if (error || activeTimerError) {
    return /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center py-8", children: /* @__PURE__ */ jsx("p", { role: "alert", className: "text-sm text-destructive", children: error ?? t("staff.timesheets.widgets.timeReporting.error", "Failed to load timer state") }) });
  }
  if (projects.length === 0) {
    return /* @__PURE__ */ jsx("div", { className: "flex h-full items-center justify-center py-8", children: /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("staff.timesheets.widgets.timeReporting.noProjects", "No projects assigned.") }) });
  }
  if (timerRunning) {
    const runningProject = projects.find((p) => p.id === activeProjectId);
    return /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
      /* @__PURE__ */ jsx("div", { className: "text-sm text-muted-foreground", children: runningProject?.name ?? activeProjectName ?? t("staff.timesheets.widgets.timeReporting.unknownProject", "Unknown project") }),
      /* @__PURE__ */ jsxs("div", { className: "text-center", children: [
        /* @__PURE__ */ jsx("p", { className: "font-mono text-3xl font-bold tabular-nums", children: elapsed }),
        /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs text-muted-foreground", children: t("staff.timesheets.widgets.timeReporting.running", "Timer running") })
      ] }),
      /* @__PURE__ */ jsx(
        Button,
        {
          type: "button",
          variant: "destructive",
          className: "w-full",
          onClick: handleStop,
          disabled: actionLoading,
          children: t("staff.timesheets.widgets.timeReporting.stop", "Stop Timer")
        }
      )
    ] });
  }
  return /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
    /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
      /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", htmlFor: "timer-project", children: t("staff.timesheets.widgets.timeReporting.project", "Project") }),
      /* @__PURE__ */ jsxs(
        "select",
        {
          id: "timer-project",
          className: "w-full rounded-md border bg-background px-3 py-2 text-sm",
          value: selectedProjectId ?? "",
          onChange: (e) => setSelectedProjectId(e.target.value || null),
          children: [
            /* @__PURE__ */ jsx("option", { value: "", children: t("staff.timesheets.widgets.timeReporting.selectProject", "Select project...") }),
            projects.map((project) => /* @__PURE__ */ jsxs("option", { value: project.id, children: [
              project.name,
              project.code ? ` (${project.code})` : ""
            ] }, project.id))
          ]
        }
      )
    ] }),
    /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
      /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", htmlFor: "timer-notes", children: t("staff.timesheets.widgets.timeReporting.taskNote", "Task / Note") }),
      /* @__PURE__ */ jsx(
        Input,
        {
          id: "timer-notes",
          value: notes,
          onChange: (e) => setNotes(e.target.value),
          placeholder: t("staff.timesheets.widgets.timeReporting.notesPlaceholder", "What are you working on?")
        }
      )
    ] }),
    /* @__PURE__ */ jsx("div", { className: "text-center", children: /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("staff.timesheets.widgets.timeReporting.notRunning", "Not running") }) }),
    /* @__PURE__ */ jsx(
      Button,
      {
        type: "button",
        className: "w-full",
        onClick: handleStart,
        disabled: actionLoading || !selectedProjectId,
        children: t("staff.timesheets.widgets.timeReporting.start", "Start Timer")
      }
    )
  ] });
};
var widget_client_default = TimeReportingWidget;
export {
  widget_client_default as default
};
//# sourceMappingURL=widget.client.js.map
