"use client";
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
import { useState, useEffect, useRef, useCallback } from "react";
import { Play, Square } from "lucide-react";
import { Button } from "@open-mercato/ui/primitives/button";
import { IconButton } from "@open-mercato/ui/primitives/icon-button";
import { useT } from "@open-mercato/shared/lib/i18n/context";
import { apiCallOrThrow } from "@open-mercato/ui/backend/utils/apiCall";
import { flash } from "@open-mercato/ui/backend/FlashMessages";
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
import { ProjectColorDot } from "./ProjectColorDot.js";
import { useActiveTimesheetTimer } from "./useActiveTimesheetTimer.js";
import { startTimerEntry } from "./startTimer.js";
import { resolveTimerActionError } from "./timerErrors.js";
const TIMER_MUTATION_CONTEXT_ID = "staff-timesheets-timer-bar";
function formatElapsed(seconds) {
  const h = Math.floor(seconds / 3600);
  const m = Math.floor(seconds % 3600 / 60);
  const s = seconds % 60;
  return `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`;
}
function getToday() {
  const now = /* @__PURE__ */ new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}
function TimerBar({ projects, staffMemberId, onTimerStopped }) {
  const t = useT();
  const { runMutation, retryLastMutation } = useGuardedMutation({
    contextId: TIMER_MUTATION_CONTEXT_ID,
    blockedMessage: t("ui.forms.flash.saveBlocked", "Save blocked by validation")
  });
  const [elapsedSeconds, setElapsedSeconds] = useState(0);
  const [description, setDescription] = useState("");
  const [selectedProjectId, setSelectedProjectId] = useState(null);
  const [isStarting, setIsStarting] = useState(false);
  const [isStopping, setIsStopping] = useState(false);
  const [showProjectDropdown, setShowProjectDropdown] = useState(false);
  const [projectFilter, setProjectFilter] = useState("");
  const dropdownRef = useRef(null);
  const intervalRef = useRef(null);
  const activeTimer = useActiveTimesheetTimer({ staffMemberId });
  const activeEntryId = activeTimer.entryId;
  const activeProjectId = activeTimer.projectId;
  const isRunning = activeTimer.running;
  const activeProject = projects.find((p) => p.id === activeProjectId);
  const activeProjectName = activeProject?.name ?? activeTimer.projectName;
  const activeProjectColor = activeProject?.color ?? activeTimer.projectColor;
  const selectedProject = projects.find((p) => p.id === selectedProjectId);
  const filteredProjects = projects.filter(
    (p) => p.name.toLowerCase().includes(projectFilter.toLowerCase())
  );
  const startElapsedCounter = useCallback((startedAt) => {
    const startTime = new Date(startedAt).getTime();
    const calcElapsed = () => Math.max(0, Math.floor((Date.now() - startTime) / 1e3));
    setElapsedSeconds(calcElapsed());
    if (intervalRef.current) clearInterval(intervalRef.current);
    intervalRef.current = setInterval(() => {
      setElapsedSeconds(calcElapsed());
    }, 1e3);
  }, []);
  const stopElapsedCounter = useCallback(() => {
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
      intervalRef.current = null;
    }
    setElapsedSeconds(0);
  }, []);
  useEffect(() => {
    if (activeTimer.running && activeTimer.startedAt) {
      startElapsedCounter(activeTimer.startedAt);
      if (activeTimer.notes != null) setDescription(activeTimer.notes);
      return;
    }
    stopElapsedCounter();
  }, [activeTimer.running, activeTimer.startedAt, activeTimer.notes, startElapsedCounter, stopElapsedCounter]);
  useEffect(() => {
    return () => {
      if (intervalRef.current) clearInterval(intervalRef.current);
    };
  }, []);
  useEffect(() => {
    function handleClickOutside(event) {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
        setShowProjectDropdown(false);
        setProjectFilter("");
      }
    }
    if (showProjectDropdown) {
      document.addEventListener("mousedown", handleClickOutside);
    }
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [showProjectDropdown]);
  const handleStart = async () => {
    if (!selectedProjectId || !staffMemberId) return;
    setIsStarting(true);
    try {
      const today = getToday();
      const startPayload = {
        staffMemberId,
        timeProjectId: selectedProjectId,
        date: today,
        notes: description || null
      };
      await runMutation({
        operation: () => startTimerEntry(startPayload),
        context: {
          formId: TIMER_MUTATION_CONTEXT_ID,
          resourceKind: "staff.timesheets.time_entry",
          resourceId: staffMemberId,
          staffMemberId,
          action: "timer-start",
          retryLastMutation
        },
        mutationPayload: startPayload
      });
      await activeTimer.refresh();
    } catch (err) {
      flash(
        resolveTimerActionError(err, t("staff.timesheets.my.timer.startError", "Failed to start timer")),
        "error"
      );
    } finally {
      setIsStarting(false);
    }
  };
  const handleStop = async () => {
    if (!activeEntryId) return;
    setIsStopping(true);
    try {
      const stopPayload = {
        id: activeEntryId,
        action: "timer-stop",
        staffMemberId
      };
      await runMutation({
        operation: () => apiCallOrThrow(
          `/api/staff/timesheets/time-entries/${activeEntryId}/timer-stop`,
          { method: "POST" }
        ),
        context: {
          formId: TIMER_MUTATION_CONTEXT_ID,
          resourceKind: "staff.timesheets.time_entry",
          resourceId: activeEntryId,
          staffMemberId,
          action: "timer-stop",
          retryLastMutation
        },
        mutationPayload: stopPayload
      });
      setDescription("");
      await activeTimer.refresh();
      onTimerStopped();
    } catch (err) {
      flash(
        resolveTimerActionError(err, t("staff.timesheets.my.timer.stopError", "Failed to stop timer")),
        "error"
      );
    } finally {
      setIsStopping(false);
    }
  };
  return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 rounded-lg border bg-card p-3 mb-4", children: [
    /* @__PURE__ */ jsx(
      "input",
      {
        type: "text",
        value: description,
        onChange: (e) => setDescription(e.target.value),
        readOnly: isRunning,
        placeholder: t(
          "staff.timesheets.my.timer.placeholder",
          "What are you working on?"
        ),
        className: "flex-1 bg-transparent border-0 outline-none text-sm placeholder:text-muted-foreground"
      }
    ),
    /* @__PURE__ */ jsx("div", { className: "relative", ref: dropdownRef, children: isRunning ? activeProjectName ? /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1.5 text-xs font-medium px-2 py-1 rounded border bg-muted", children: [
      /* @__PURE__ */ jsx(ProjectColorDot, { colorKey: activeProjectColor, projectName: activeProjectName, size: "xs" }),
      activeProjectName
    ] }) : null : /* @__PURE__ */ jsxs(Fragment, { children: [
      /* @__PURE__ */ jsx(
        Button,
        {
          type: "button",
          variant: "outline",
          size: "sm",
          onClick: () => {
            setShowProjectDropdown(!showProjectDropdown);
            setProjectFilter("");
          },
          className: "text-xs font-medium",
          children: selectedProject ? /* @__PURE__ */ jsxs(Fragment, { children: [
            /* @__PURE__ */ jsx(ProjectColorDot, { colorKey: selectedProject.color, projectName: selectedProject.name, size: "xs" }),
            /* @__PURE__ */ jsx("span", { className: "ml-1", children: selectedProject.name })
          ] }) : t("staff.timesheets.my.timer.selectProject", "Project")
        }
      ),
      showProjectDropdown && /* @__PURE__ */ jsxs("div", { className: "absolute right-0 top-full mt-1 z-50 min-w-[200px] rounded-md border bg-popover p-1 shadow-md", children: [
        /* @__PURE__ */ jsx(
          "input",
          {
            type: "text",
            value: projectFilter,
            onChange: (e) => setProjectFilter(e.target.value),
            placeholder: t(
              "staff.timesheets.my.timer.searchProject",
              "Search projects..."
            ),
            className: "w-full bg-transparent border-b px-2 py-1.5 text-xs outline-none placeholder:text-muted-foreground mb-1",
            autoFocus: true
          }
        ),
        /* @__PURE__ */ jsx("div", { className: "max-h-[200px] overflow-y-auto", children: filteredProjects.length === 0 ? /* @__PURE__ */ jsx("div", { className: "px-2 py-1.5 text-xs text-muted-foreground", children: t(
          "staff.timesheets.my.timer.noProjects",
          "No projects found"
        ) }) : filteredProjects.map((project) => /* @__PURE__ */ jsxs(
          Button,
          {
            type: "button",
            variant: "ghost",
            size: "sm",
            className: "w-full justify-start text-xs h-auto py-1.5",
            onClick: () => {
              setSelectedProjectId(project.id);
              setShowProjectDropdown(false);
              setProjectFilter("");
            },
            children: [
              /* @__PURE__ */ jsx(ProjectColorDot, { colorKey: project.color, projectName: project.name, size: "xs" }),
              /* @__PURE__ */ jsx("span", { className: "ml-1", children: project.name }),
              project.code ? /* @__PURE__ */ jsxs("span", { className: "ml-1 text-muted-foreground", children: [
                "(",
                project.code,
                ")"
              ] }) : null
            ]
          },
          project.id
        )) })
      ] })
    ] }) }),
    /* @__PURE__ */ jsx("span", { className: "font-mono text-sm tabular-nums min-w-[64px] text-right", children: formatElapsed(elapsedSeconds) }),
    isRunning ? /* @__PURE__ */ jsx(
      IconButton,
      {
        type: "button",
        variant: "destructive",
        size: "default",
        onClick: handleStop,
        disabled: isStopping,
        "aria-label": t("staff.timesheets.my.timer.stop", "Stop timer"),
        children: /* @__PURE__ */ jsx(Square, { className: "size-4" })
      }
    ) : /* @__PURE__ */ jsx(
      IconButton,
      {
        type: "button",
        variant: "primary",
        size: "default",
        onClick: handleStart,
        disabled: isStarting || !selectedProjectId,
        "aria-label": t("staff.timesheets.my.timer.start", "Start timer"),
        children: /* @__PURE__ */ jsx(Play, { className: "size-4" })
      }
    )
  ] });
}
export {
  TimerBar
};
//# sourceMappingURL=TimerBar.js.map
