import { css } from '@emotion/css';
import { useState } from 'react';

import { type GrafanaTheme2 } from '@grafana/data';
import { t } from '@grafana/i18n';
import {
  ClipboardButton,
  type CustomCellRendererProps,
  IconButton,
  TableCellInspector,
  TableCellInspectorMode,
  useTheme2,
} from '@grafana/ui';
import { type LogsFrame } from 'app/features/logs/logsFrame';

import { type BuildLinkToLogLine } from '../types';

interface Props extends CustomCellRendererProps {
  buildLinkToLog?: BuildLinkToLogLine;
  showInspectLogLine: boolean;
  logsFrame: LogsFrame;
}

/**
 * Logs row actions buttons
 * @param props
 * @constructor
 */
export function LogsTableRowActionButtons(props: Props) {
  const { rowIndex, buildLinkToLog, showInspectLogLine, logsFrame } = props;
  const theme = useTheme2();
  const [isInspecting, setIsInspecting] = useState(false);
  const styles = getStyles(theme);

  const handleViewClick = () => {
    setIsInspecting(true);
  };

  return (
    <>
      <div className={styles.container}>
        {showInspectLogLine && (
          <div className={styles.buttonWrapper}>
            <IconButton
              className={styles.inspectButton}
              tooltip={t('explore.logs-table.action-buttons.view-log-line', 'View log line')}
              variant="secondary"
              aria-label={t('explore.logs-table.action-buttons.view-log-line', 'View log line')}
              tooltipPlacement="top"
              size="md"
              name="eye"
              onClick={handleViewClick}
              tabIndex={0}
            />
          </div>
        )}
        {buildLinkToLog && (
          <div className={styles.buttonWrapper}>
            <ClipboardButton
              className={styles.clipboardButton}
              icon="share-alt"
              variant="secondary"
              fill="text"
              size="md"
              tooltip={t('explore.logs-table.action-buttons.copy-link', 'Copy link to log line')}
              tooltipPlacement="top"
              tabIndex={0}
              aria-label={t('explore.logs-table.action-buttons.copy-link', 'Copy link to log line')}
              getText={() => {
                const logId = logsFrame?.idField?.values?.[rowIndex];
                if (logId) {
                  return buildLinkToLog(logId) ?? '';
                } else {
                  console.error('failed to copy log line link!');
                }
                return '';
              }}
            />
          </div>
        )}
      </div>
      {isInspecting && (
        <TableCellInspector
          value={getLineValue(logsFrame, rowIndex)}
          mode={TableCellInspectorMode.code}
          onDismiss={function (): void {
            setIsInspecting(false);
          }}
        />
      )}
    </>
  );
}

const getLineValue = (logsFrame: LogsFrame, rowIndex: number) => {
  const bodyField = logsFrame.bodyField;
  return bodyField?.values[rowIndex];
};

export const getStyles = (theme: GrafanaTheme2) => ({
  container: css({
    background: theme.colors.background.secondary,
    boxShadow: theme.shadows.z2,
    display: 'flex',
    flexDirection: 'row',
    height: '100%',
    left: 0,
    top: 0,
    position: 'absolute',
    zIndex: 1,
  }),
  buttonWrapper: css({
    height: '100%',
    '&:hover': {
      color: theme.colors.text.link,
    },
    padding: theme.spacing(0, 0.5),
    display: 'flex',
    alignItems: 'center',
  }),
  inspectButton: css({
    borderRadius: theme.shape.radius.default,
    display: 'inline-flex',
    margin: 0,
    overflow: 'hidden',
    verticalAlign: 'middle',
    cursor: 'pointer',
    height: '24px',
    width: '20px',
  }),
  clipboardButton: css({
    lineHeight: '1',
    padding: 0,
    width: '20px',
    cursor: 'pointer',
    height: '24px',
  }),
});
