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

import type { JSX } from 'react';
import type { ResolvedNavItemWithLink, MarkdownConfig } from '@redocly/config';

import { breakpoints } from '@redocly/theme/core/utils';
import { H1_CLASS } from '@redocly/theme/core/constants';
import { CodeSnippetProvider } from '@redocly/theme/core/contexts/CodeSnippetContext';
import { DocumentationLayoutTop } from '@redocly/theme/layouts/DocumentationLayoutTop';
import { DocumentationLayoutBottom } from '@redocly/theme/layouts/DocumentationLayoutBottom';

type DocumentationLayoutProps = {
  tableOfContent: React.ReactNode;
  feedback: React.ReactNode;
  config?: MarkdownConfig;
  editPage?: {
    to: string;
  };
  /** String in ISO format */
  lastModified?: string | null;
  nextPage?: ResolvedNavItemWithLink | null;
  prevPage?: ResolvedNavItemWithLink | null;
  className?: string;
};

export function DocumentationLayout({
  tableOfContent,
  feedback,
  config,
  editPage,
  lastModified,
  nextPage,
  prevPage,
  className,
  children,
}: React.PropsWithChildren<DocumentationLayoutProps>): JSX.Element {
  return (
    <CodeSnippetProvider>
      <LayoutWrapper data-component-name="Layout/DocumentationLayout" className={className}>
        <ContentWrapper withToc={!config?.toc?.hide}>
          <DocumentationLayoutTop config={config} editPage={editPage} lastModified={lastModified} />
          {children}
          <DocumentationLayoutBottom feedback={feedback} nextPage={nextPage} prevPage={prevPage} />
        </ContentWrapper>
        {tableOfContent}
      </LayoutWrapper>
    </CodeSnippetProvider>
  );
}

const LayoutWrapper = styled.div.attrs(({ className }) => ({
  className,
}))`
  display: flex;
  flex: 1;
  width: 100%;
`;

const ContentWrapper = styled.section<{ withToc: boolean }>`
  --md-content-font-size: var(--font-size-lg);
  --md-content-line-height: var(--line-height-lg);
  --md-table-font-size: var(--md-content-font-size);
  --md-table-line-height: var(--md-content-line-height);
  --md-tabs-content-font-size: var(--md-content-font-size);
  --md-tabs-content-line-height: var(--md-content-line-height);

  max-width: var(--md-content-max-width);
  width: 90%;
  margin: 0 auto;

  padding: var(--md-content-padding);

  article:first-child > h1:first-child,
  article:first-child > .${H1_CLASS}:first-child {
    // disable margin top for h1 on the title heading
    margin-top: 0;
  }

  @media screen and (min-width: ${breakpoints.medium}) {
    width: ${({ withToc }) => (withToc ? `calc(90% - var(--toc-width))` : '90%')};
  }
`;
