import { CSSProperties, useContext, useEffect, useRef, useState } from 'react';
import { ThemeContext } from 'styled-components';
import { Box, Code, Flex, List, Section, Text } from '../../components';
import { UIComponentProps } from '../../components/types';
import { ITheme, IThemeFont, IThemeFontVariant } from '../../theme';

type Props = {
};

export type TypographyProps = UIComponentProps<Props>;

const TypographyItem = (props: { variant: IThemeFontVariant, size: CSSProperties['fontSize'] | {} }) => {
  const ref = useRef<HTMLDivElement>(null);
  const [px, setPx] = useState('0px');
  useEffect(() => {
    function onResize() {
      if (ref.current) {
        setPx(window.getComputedStyle(ref.current).fontSize);
      }
    }
    onResize();
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);
  return (
    <List>
      <Text variant={props.variant} ref={ref} textTransform="capitalize">{props.variant}</Text>
      <Flex.Row justifyContent="space-between" paddingTop="1rem">
        <Code fontSize="0.7rem">{typeof props.size === 'string' ? props.size : JSON.stringify(props.size)}</Code>
        <Code fontSize="0.7rem">{px}</Code>
      </Flex.Row>
    </List>
  );
};

export const Typography = (props: TypographyProps) => {
  const theme = useContext(ThemeContext) as ITheme;
  return (
    <Section padding="3rem 0">
      {Object.entries(theme.font).map(([key, value]: [string, IThemeFont | undefined]) => {
        if (value) {
          return (
            <Box key={key} padding="0 1rem 1rem 1rem">
              {value.family && <Code>{value.family}</Code>}
              <TypographyItem variant={key} size={value.size} />
            </Box>
          );
        } else {
          return null;
        }
      })}
    </Section>
  );
};
