import {
  Box,
  Button,
  Collapse,
  Loader,
  SkeletonGroup,
  SkeletonLine,
  Text
} from "@wix/design-system";
import {
  ChevronDown,
  CircleSmallFilledSmall,
  Confirm,
  StatusAlertSmall
} from "@wix/wix-ui-icons-common";
import cs from "classnames";
import React, { useEffect, useState } from "react";
import { unreachable } from "./../../_shared/uncreachable.js";
import { getAssistantErrorDescriptor } from "./assistant-error-descriptor.js";
import styles from "./assistant-timeline-scss.js";
const MAX_DESCRIPTION_LENGTH = 60;
const ExpandableText = ({ text, className }) => {
  const [expanded, setExpanded] = useState(false);
  const needsTruncation = text.length > MAX_DESCRIPTION_LENGTH;
  const displayText = !expanded && needsTruncation ? text.slice(0, MAX_DESCRIPTION_LENGTH).trimEnd() + "…" : text;
  return /* @__PURE__ */ React.createElement(
    Text,
    {
      className,
      variant: "normal",
      size: "small",
      onClick: needsTruncation ? () => setExpanded((prev) => !prev) : void 0,
      style: needsTruncation ? { cursor: "pointer" } : void 0
    },
    displayText
  );
};
const renderStepIcon = (status) => {
  switch (status) {
    case "success":
      return /* @__PURE__ */ React.createElement(Confirm, { className: styles.stepIcon });
    case "inProgress":
      return /* @__PURE__ */ React.createElement("div", { className: styles.loaderContainer }, /* @__PURE__ */ React.createElement(Loader, { size: "tiny" }));
    case "error":
      return /* @__PURE__ */ React.createElement(StatusAlertSmall, { className: styles.stepIcon });
    case "pending":
      return /* @__PURE__ */ React.createElement(CircleSmallFilledSmall, { className: styles.stepIcon });
    default:
      throw unreachable(status);
  }
};
const getTimelineStepId = (task, index) => task.id ?? `step-${index}-${task.message}`;
const MessageTimeline = ({
  title,
  subtitle,
  tasks,
  isLoading = false,
  onRetry,
  footer,
  t
}) => {
  const visibleSteps = tasks ?? [];
  const expandedStepsResetKey = visibleSteps.map((task, index) => `${getTimelineStepId(task, index)}:${task.status}`).join("|");
  const [expandedSteps, setExpandedSteps] = useState({});
  useEffect(() => {
    const expanded = {};
    visibleSteps.forEach((task, index) => {
      expanded[getTimelineStepId(task, index)] = task.status === "inProgress";
    });
    setExpandedSteps(expanded);
  }, [expandedStepsResetKey]);
  const toggleStep = (stepId) => {
    setExpandedSteps((prev) => ({
      ...prev,
      [stepId]: !prev[stepId]
    }));
  };
  if (visibleSteps.some((step) => step.status === "error")) {
    const errorStep = visibleSteps.find((step) => step.status === "error");
    const errorDescriptor = getAssistantErrorDescriptor({
      applicationErrorCode: errorStep?.applicationErrorCode,
      message: errorStep?.description?.[0] ?? errorStep?.message,
      t
    });
    return /* @__PURE__ */ React.createElement(Box, { className: styles.assistantTimelineErrorContainer, direction: "vertical" }, /* @__PURE__ */ React.createElement(Box, { verticalAlign: "middle", marginBottom: "8px" }, /* @__PURE__ */ React.createElement(Box, { marginRight: "8px", color: "#D6453D" }, /* @__PURE__ */ React.createElement(StatusAlertSmall, { size: "24" })), /* @__PURE__ */ React.createElement(Text, { size: "small", weight: "bold" }, errorDescriptor.title)), /* @__PURE__ */ React.createElement(Box, { marginBottom: "16px" }, /* @__PURE__ */ React.createElement(Text, { size: "small" }, errorDescriptor.subtitle)), onRetry && errorDescriptor.isRetriable && /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(Button, { size: "small", priority: "primary", onClick: onRetry, skin: "dark" }, t("AssistantTimeline_Button_TryAgain"))));
  }
  return /* @__PURE__ */ React.createElement(Box, { className: styles.assistantTimelineContainer, direction: "vertical" }, /* @__PURE__ */ React.createElement(Text, { variant: "normal", size: "small", weight: "bold" }, title), /* @__PURE__ */ React.createElement(Text, { className: styles.timelineSubtitle, variant: "normal", size: "small" }, subtitle), /* @__PURE__ */ React.createElement(Box, { className: styles.stepsContainer, direction: "vertical" }, isLoading ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(SkeletonGroup, null, /* @__PURE__ */ React.createElement(SkeletonLine, { width: "75%", marginBottom: "8px" }), /* @__PURE__ */ React.createElement(SkeletonLine, { width: "60%", marginBottom: "16px" })), /* @__PURE__ */ React.createElement(SkeletonGroup, null, /* @__PURE__ */ React.createElement(SkeletonLine, { width: "80%", marginBottom: "8px" }), /* @__PURE__ */ React.createElement(SkeletonLine, { width: "55%", marginBottom: "16px" }))) : visibleSteps.map((step, index) => {
    const stepId = getTimelineStepId(step, index);
    return /* @__PURE__ */ React.createElement(
      Box,
      {
        key: stepId,
        className: cs(styles.stepItem, {
          [styles.stepItemLoading]: step.status === "inProgress"
        }),
        direction: "vertical"
      },
      /* @__PURE__ */ React.createElement(
        "div",
        {
          onClick: () => toggleStep(stepId),
          onKeyDown: (e) => {
            if (e.key === "Enter" || e.key === " ") {
              e.preventDefault();
              toggleStep(stepId);
            }
          },
          role: "button",
          tabIndex: 0
        },
        /* @__PURE__ */ React.createElement(Box, { className: styles.stepHeader }, renderStepIcon(step.status), /* @__PURE__ */ React.createElement(Text, { className: styles.stepTitle, variant: "normal", size: "small" }, step.message), /* @__PURE__ */ React.createElement(
          ChevronDown,
          {
            visibility: step.description && step.description.length > 0 ? "visible" : "hidden",
            className: `${styles.chevronIcon} ${expandedSteps[stepId] ? styles.expanded : ""}`
          }
        ))
      ),
      /* @__PURE__ */ React.createElement(Collapse, { open: !!expandedSteps[stepId] }, /* @__PURE__ */ React.createElement(Box, { direction: "vertical", className: styles.stepDetails }, step.description?.map((desc, descriptionIndex) => /* @__PURE__ */ React.createElement(
        ExpandableText,
        {
          key: descriptionIndex,
          text: desc,
          className: cs(
            styles.timelineSubtitle,
            step.isToolDescription && styles.toolDescription
          )
        }
      ))))
    );
  })), footer && /* @__PURE__ */ React.createElement("div", { className: styles.timelineFooter }, footer));
};
export {
  MessageTimeline
};
//# sourceMappingURL=assistant-timeline.js.map
