import React, { useContext, useMemo } from 'react';

import TypeContext, { StyleDefinition, TypeStyles } from './TypeContext';

const HEADING_LEVELS: Array<'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6'> = [
  'h1',
  'h2',
  'h3',
  'h4',
  'h5',
  'h6',
];

export default function Typography({
  styles,
  children,
}: {
  styles: StyleDefinition;
  children: React.ReactNode;
}): React.ReactElement {
  const parentStyles: TypeStyles = useContext(TypeContext);
  const value: TypeStyles = useMemo(() => {
    const {
      skipLevels = 0,
      headings = [parentStyles.H1, parentStyles.H2, parentStyles.H3],
      aside: Aside = parentStyles.Aside,
      p: P = parentStyles.P,
    } = styles;
    const topLevel = parentStyles.topLevel + skipLevels;
    const [H1, H2, H3] =
      skipLevels === 0
        ? headings
        : headings.map((heading, i) =>
            heading.withComponent(HEADING_LEVELS[topLevel + i - 1]),
          );
    return { topLevel, P, Aside, H1, H2, H3 };
  }, [styles]);
  return <TypeContext.Provider value={value}>{children}</TypeContext.Provider>;
}
