import {
  InfoIconTooltip
} from "./chunk-LW7PUO7V.js";
import {
  ClipboardTextField
} from "./chunk-ZOIGYYOQ.js";
import {
  useClipboard
} from "./chunk-QHODHUW2.js";
import {
  lineClamp,
  overflowAutoWithoutScrollbars
} from "./chunk-FAWI3ZGU.js";
import {
  Loading
} from "./chunk-YNCTWF7N.js";
import {
  Icon
} from "./chunk-DMPXNHDT.js";
import {
  standardContentInset
} from "./chunk-HGZGGJQB.js";
import {
  Link,
  replaceParams,
  useNavigate
} from "./chunk-SWMGDTQN.js";
import {
  themeOrWithKey
} from "./chunk-VAH342U2.js";
import {
  bp
} from "./chunk-JSGRNWSB.js";
import {
  __spreadProps,
  __spreadValues
} from "./chunk-W7FAWX6T.js";

// src/components/Table/Table.tsx
import { css } from "@emotion/react";
import styled from "@emotion/styled";
import {
  flexRender,
  getCoreRowModel,
  getSortedRowModel,
  useReactTable
} from "@tanstack/react-table";
import { isObject } from "lodash-es";
import { Fragment, useCallback, useMemo, useState } from "react";
import { jsx, jsxs } from "@emotion/react/jsx-runtime";
var isObjectCell = (value) => {
  return isObject(value) && "text" in value && typeof value.text === "string";
};
var isLinkCell = (value) => {
  return isObjectCell(value) && ("link" in value || "to" in value);
};
var isClipboardCell = (value) => {
  return isObjectCell(value) && "canCopy" in value;
};
var isLinkAndClipboardCell = (value) => {
  return isObjectCell(value) && ("link" in value || "to" in value) && "canCopy" in value;
};
var isMultilineCell = (value) => {
  return isObjectCell(value) && "multiline" in value;
};
function Table({
  columns,
  data,
  loading,
  onClickRow,
  emptyState,
  clipboardCallbacks,
  customComponents,
  rowHoverEffect = "border",
  minHeight = 300
}) {
  const navigate = useNavigate();
  const [sorting, setSorting] = useState([]);
  const { canWriteToClipboard, writeTextToClipboard } = useClipboard(clipboardCallbacks);
  const onClickCopy = useCallback(
    (value) => (event) => {
      event.stopPropagation();
      void writeTextToClipboard(value);
    },
    [writeTextToClipboard]
  );
  const mappedColumns = useMemo(
    () => columns.map((column) => __spreadProps(__spreadValues({}, column), {
      header: (context) => typeof column.header === "string" ? column.header : /* @__PURE__ */ jsxs("div", { children: [
        column.header.name,
        /* @__PURE__ */ jsx(
          InfoIconTooltip,
          {
            id: `tooltip-${column.header.name}`,
            content: column.header.tooltip || "",
            verticalAlign: -2
          }
        )
      ] }),
      accessorKey: column.accessorKey.toString(),
      cell: (context) => {
        var _a, _b;
        const value = context.getValue();
        let content = null;
        let icon = null;
        if (isObjectCell(value)) {
          const base64icon = value.base64icon ? /* @__PURE__ */ jsx(Base64Icon, { src: value.base64icon, alt: "Icon" }) : null;
          icon = value.icon ? /* @__PURE__ */ jsx(Icon, { name: value.icon, width: 14, mr: 4, color: "c4Neutral" }) : null;
          if (isMultilineCell(value)) {
            content = /* @__PURE__ */ jsxs(LineClampSpan, { children: [
              base64icon ? base64icon : icon,
              value.text
            ] });
          } else {
            content = /* @__PURE__ */ jsxs(Fragment, { children: [
              base64icon ? base64icon : icon,
              value.text
            ] });
          }
        } else {
          content = value;
        }
        if (isLinkAndClipboardCell(value)) {
          const copyButton = canWriteToClipboard && /* @__PURE__ */ jsx(
            CopyButton,
            {
              onClick: onClickCopy(value.text),
              role: "button",
              tabIndex: 0,
              children: /* @__PURE__ */ jsx(Icon, { name: "Copy", width: 16, mr: 12 })
            }
          );
          return value.link ? /* @__PURE__ */ jsxs(LinkClipboardCell, { children: [
            /* @__PURE__ */ jsxs(
              HoverableLinkCell,
              {
                href: value.link,
                target: "_blank",
                rel: "noreferrer",
                onClick: (e) => {
                  e.stopPropagation();
                },
                children: [
                  /* @__PURE__ */ jsx(Icon, { name: "LinkIcon", width: 12 }),
                  /* @__PURE__ */ jsx(LinkCellContent, { children: content })
                ]
              }
            ),
            copyButton
          ] }) : value.to ? /* @__PURE__ */ jsxs(HoverableCellWrapper, { children: [
            /* @__PURE__ */ jsxs(
              Link,
              {
                to: value.to,
                params: value.toParams,
                onClick: (e) => {
                  e.stopPropagation();
                },
                children: [
                  icon,
                  /* @__PURE__ */ jsx(LinkCellContent, { children: value.text })
                ]
              }
            ),
            copyButton
          ] }) : /* @__PURE__ */ jsx("span", { children: content });
        } else if (isLinkCell(value)) {
          return value.link ? /* @__PURE__ */ jsxs(
            HoverableLinkCell,
            {
              href: value.link,
              target: "_blank",
              rel: "noreferrer",
              onClick: (e) => {
                e.stopPropagation();
              },
              children: [
                /* @__PURE__ */ jsx(Icon, { name: "LinkIcon", width: 12 }),
                /* @__PURE__ */ jsx(LinkCellContent, { children: content })
              ]
            }
          ) : value.to ? /* @__PURE__ */ jsx(HoverableCellWrapper, { children: /* @__PURE__ */ jsxs(
            Link,
            {
              to: value.to,
              params: value.toParams,
              onClick: (e) => {
                e.stopPropagation();
              },
              children: [
                icon,
                /* @__PURE__ */ jsx(LinkCellContent, { children: value.text })
              ]
            }
          ) }) : /* @__PURE__ */ jsx("span", { children: content });
        } else if (isClipboardCell(value)) {
          let maxLines = 1;
          let maxChars = void 0;
          if (isMultilineCell(value)) {
            maxLines = 2;
          } else {
            maxChars = value.maxChars || 16;
          }
          const ellipsisPosition = value.ellipsisPosition || "middle";
          return /* @__PURE__ */ jsxs(HoverableCellWrapper, { children: [
            icon,
            /* @__PURE__ */ jsx(
              ClipboardTextField,
              {
                value: value.text,
                elide: maxChars ? {
                  maxChars,
                  ellipsisPosition
                } : void 0,
                stopPropagation: true,
                maxLines,
                icon: true,
                iconSide: "right",
                clipboardCallbacks,
                typography: ((_a = customComponents == null ? void 0 : customComponents.clipboardTextField) == null ? void 0 : _a.typography) ? customComponents.clipboardTextField.typography : void 0,
                iconName: (_b = customComponents == null ? void 0 : customComponents.clipboardTextField) == null ? void 0 : _b.iconName
              }
            )
          ] });
        }
        return /* @__PURE__ */ jsx("span", { children: content });
      }
    })),
    [
      columns,
      canWriteToClipboard,
      onClickCopy,
      clipboardCallbacks,
      customComponents
    ]
  );
  const tableInstance = useReactTable({
    columns: mappedColumns,
    data,
    state: {
      sorting
    },
    onSortingChange: setSorting,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel()
    // debugTable: true
  });
  function onClickDataRow(event, row) {
    const onClickRowResult = onClickRow ? onClickRow(row) : null;
    if (onClickRowResult) {
      const newTabKey = event.metaKey || event.ctrlKey;
      if ((onClickRowResult == null ? void 0 : onClickRowResult.link) || (onClickRowResult == null ? void 0 : onClickRowResult.to) && newTabKey) {
        let link = onClickRowResult == null ? void 0 : onClickRowResult.link;
        if (!link) {
          link = replaceParams(onClickRowResult.to, onClickRowResult.params);
        }
        const target = newTabKey ? "_blank" : void 0;
        window.open(link, target);
      } else if (onClickRowResult == null ? void 0 : onClickRowResult.to) {
        navigate(onClickRowResult.to, onClickRowResult.params);
      }
    }
  }
  const thead = /* @__PURE__ */ jsx("thead", {
    // Loop over the header rows
    children: tableInstance.getHeaderGroups().map((headerGroup) => {
      return /* @__PURE__ */ jsx("tr", { children: headerGroup.headers.map((header) => /* @__PURE__ */ jsx("th", { children: header.isPlaceholder ? null : flexRender(
        header.column.columnDef.header,
        header.getContext()
      ) }, header.id)) }, headerGroup.id);
    })
  });
  const tbody = /* @__PURE__ */ jsx("tbody", {
    // Loop over the table rows
    children: tableInstance.getRowModel().rows.map((row) => {
      return /* @__PURE__ */ jsx(
        "tr",
        {
          onClick: (event) => onClickDataRow(event, row),
          onKeyDown: (event) => {
            if (event.key === "Enter") {
              onClickDataRow(event, row);
            }
          },
          tabIndex: 0,
          children: row.getVisibleCells().map((cell) => /* @__PURE__ */ jsx("td", { children: flexRender(cell.column.columnDef.cell, cell.getContext()) }, cell.id))
        },
        row.id
      );
    })
  });
  const TableComponent = (customComponents == null ? void 0 : customComponents.table) || StyledTable;
  return /* @__PURE__ */ jsxs(TableWrapper, { minHeight, children: [
    /* @__PURE__ */ jsxs(
      TableComponent,
      {
        clickable: Boolean(onClickRow),
        rowHoverEffect,
        children: [
          thead,
          tbody
        ]
      }
    ),
    emptyState,
    loading && /* @__PURE__ */ jsx(Loading, {})
  ] });
}
var TableWrapper = styled.div`
  position: relative;
  min-height: ${({ minHeight }) => minHeight}px;
  ${overflowAutoWithoutScrollbars}
`;
var hoverCellStyles = css`
  cursor: pointer;
  transition: opacity 0.25s;

  &:hover {
    opacity: 0.6;
  }
`;
var LinkCellContent = styled.span`
  vertical-align: middle;
`;
var HoverableCellWrapper = styled.div`
  ${hoverCellStyles}

  ${Link} {
    text-overflow: ellipsis;
    overflow: hidden;
  }
  display: flex !important;
  gap: 4px;
`;
var LinkClipboardCell = styled.a`
  ${hoverCellStyles}

  color: ${({ theme }) => theme.hcNeutral};
  display: flex !important;
  gap: 4px;
`;
var HoverableLinkCell = styled.a`
  ${hoverCellStyles}

  color: ${({ theme }) => theme.hcNeutral};
  display: flex !important;
  gap: 4px;
`;
var CopyButton = styled.span`
  overflow: hidden;
  align-items: center;
  cursor: pointer;
  display: inline-table;
`;
var LineClampSpan = styled.span`
  ${lineClamp(2)}
`;
var Base64Icon = styled.img`
  width: 32px;
  height: 32px;
  object-fit: contain;
  border-radius: 4px;
  margin-right: 12px;
`;
var cellPaddingPx = 15;
var StyledTable = styled.table`
  position: relative;
  border-spacing: 0;
  width: 100%;

  /* Important to use padding here instead of width so that table container overflow functions properly: */
  ${bp.lg(`
    padding-left: ${standardContentInset.lgPx}px;
    padding-right: ${standardContentInset.lgPx}px;
  `)}
  ${bp.sm(`
    padding-left: ${standardContentInset.smPx}px;
    padding-right: ${standardContentInset.smPx}px;
  `)}
  ${bp.minSmMaxLg(`
    padding-left: ${standardContentInset.minSmMaxLgPx}px;
    padding-right: ${standardContentInset.minSmMaxLgPx}px;
  `)}

  th {
    max-width: 200px;
    overflow: hidden;
    text-overflow: ellipsis;
    text-align: left;
    padding: ${cellPaddingPx}px 0px;
    border-bottom: 1px solid
      ${({ theme }) => themeOrWithKey("c1Neutral", "c2Neutral")({ theme })};
    padding: ${cellPaddingPx}px;
    &:first-of-type {
      padding-left: 0px;
    }
    &:last-of-type {
      padding-right: 0px;
    }
    &:last-of-type {
      text-align: right;
    }
  }

  td {
    max-width: 200px;
    text-overflow: ellipsis;
    overflow: hidden;
    padding: 0 ${cellPaddingPx}px;
    white-space: nowrap;
    & > span {
      overflow: hidden;
      text-overflow: ellipsis;
      display: block;
      padding: ${cellPaddingPx}px 0px;
      & > * {
        overflow: hidden;
        text-overflow: ellipsis;
        vertical-align: middle;
      }
    }
    &:first-of-type {
      padding-left: 0px;
    }
    &:last-of-type {
      text-align: right;
      padding-right: 0px;
    }
    & span:has(> ${LineClampSpan}),
    & ${LineClampSpan} {
      white-space: normal;
    }
  }

  tr {
    cursor: ${({ clickable }) => clickable ? "pointer" : "default"};
    position: relative;

    ${({ rowHoverEffect, theme }) => `
        &:hover {
          td {
            position: relative;
            &:before {
              content: "";
              display: block;
              position: absolute;
              pointer-events: none;
              height: 80%;
              top: 10%;
              bottom: 10%;
              ${rowHoverEffect === "background" ? `background: ${theme.c1Neutral};` : `
                    border: 1px solid ${themeOrWithKey(
  "c1Neutral",
  "c2Neutral"
)({ theme })};
                    border-left-width: 0;
                    border-right-width: 0;
                  `}
              left: 0;
              right: 0;
              width: 100%;
            }
            &:first-of-type {
              overflow: visible;
              &:before {
                border-top-left-radius: 32px;
                border-bottom-left-radius: 32px;
                transform: translateX(-12px);
                width: calc(100% + 12px);
                ${rowHoverEffect === "border" ? "border-left-width: 1px;" : ""}
              }
            }
            &:last-of-type {
              overflow: visible;
              &:before {
                border-top-right-radius: 32px;
                border-bottom-right-radius: 32px;
                transform: translateX(12px);
                width: calc(100% + 12px);
                left: auto;
                ${rowHoverEffect === "border" ? "border-right-width: 1px;" : ""}
              }
            }
          }
        }
        `}
  }
`;

export {
  Table
};
