import React from 'react';
import styled from 'styled-components';

import { Tooltip } from '@redocly/theme/components/Tooltip/Tooltip';

export type CatalogLastUpdateCellProps = {
  lastModified: string;
};

function formatLastModified(isoString: string): string {
  const date = new Date(isoString);
  if (Number.isNaN(date.getTime())) {
    return isoString;
  }
  return date.toLocaleDateString('en-US', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    timeZone: 'UTC',
  });
}

function formatLastModifiedTooltip(isoString: string): string {
  const date = new Date(isoString);
  if (Number.isNaN(date.getTime())) {
    return isoString;
  }
  return date.toLocaleString('en-US', {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false,
    timeZone: 'UTC',
  });
}

export function CatalogLastUpdateCell({
  lastModified,
}: CatalogLastUpdateCellProps): React.ReactElement {
  return (
    <CatalogLastUpdateCellWrapper data-component-name="Catalog/CatalogTableView/CatalogLastUpdateCell">
      <Tooltip tip={formatLastModifiedTooltip(lastModified)} placement="bottom">
        {formatLastModified(lastModified)}
      </Tooltip>
    </CatalogLastUpdateCellWrapper>
  );
}

const CatalogLastUpdateCellWrapper = styled.div`
  color: var(--text-color-helper);
`;
