import type { CSSProperties, FC, ReactNode } from 'react';
import type { Scroller2Props } from '../Scroller2';

import Card, { CARD_STYLE } from '../Card';
import Scroller2 from '../Scroller2';

export const Table: FC<
  {
    style?: CSSProperties;
    children: ReactNode;
    testId?: string;
    renderAfter?: () => ReactNode;
  } & Scroller2Props
> = ({ style, children, testId, renderAfter, ...scrollerProps }) => (
  <Card>
    <Scroller2 {...scrollerProps} fullHeight={false}>
      <table
        data-testid={testId}
        style={{
          ...style,

          tableLayout: 'fixed',
          borderCollapse: 'collapse',
          border: 0,
          width: '100%',
        }}
      >
        {children}
      </table>
    </Scroller2>
    {renderAfter?.()}
  </Card>
);

export const TableBody: FC<{ children: ReactNode; style?: CSSProperties }> = (
  props
) => <tbody {...props} />;

export const TableHead: FC<{ children: ReactNode; style?: CSSProperties }> = (
  props
) => <thead {...props} />;

export const TableRow: FC<{ children: ReactNode; style?: CSSProperties }> = (
  props
) => (
  <>
    <tr
      {...props}
      style={{
        borderTop: CARD_STYLE.border,
        ...props.style,
      }}
    />
    <style jsx>{`
      tr:first-child {
        border-top: 0 !important;
      }
    `}</style>
  </>
);

export const TableCell: FC<{
  isHead?: boolean;
  align?: 'left' | 'right';
  style?: CSSProperties;
  children: ReactNode;
}> = ({ isHead, align, style, ...props }) => {
  const Tag = isHead ? 'th' : 'td';

  return (
    <>
      <Tag
        {...props}
        style={{
          borderLeft: CARD_STYLE.border,
          padding: '0 0.9em',
          textAlign: align,
          height: '2.7em',
          width: isHead ? '20%' : undefined,
          background: isHead ? '#1b1b1b' : undefined,

          // prevent overflowing content from stretching the cell
          // https://stackoverflow.com/a/11877033/516629
          maxWidth: !isHead ? 0 : undefined,
          ...style,
        }}
      />
      <style jsx>{`
        :global(td:first-child),
        :global(th:first-child) {
          border-left: 0 !important;
        }
      `}</style>
    </>
  );
};
