import React, { PropsWithChildren, useState } from 'react';
import styled from 'styled-components';

import type { JSX } from 'react';

import { useThemeHooks } from '@redocly/theme/core/hooks';
import { ChevronUpIcon } from '@redocly/theme/icons/ChevronUpIcon/ChevronUpIcon';
import { ChevronDownIcon } from '@redocly/theme/icons/ChevronDownIcon/ChevronDownIcon';

export function CodePanelPreview({ children }: PropsWithChildren): JSX.Element {
  const [isOpen, setIsOpen] = useState(false);
  const { useTranslate } = useThemeHooks();
  const { translate } = useTranslate();

  return (
    <CodePanelPreviewWrapper data-component-name="Markdoc/CodeWalkthrough/CodePanelPreview">
      <PreviewDropdown onClick={() => setIsOpen(!isOpen)}>
        {translate('codeWalkthrough.preview', 'Preview')}
        {isOpen ? <ChevronUpIcon /> : <ChevronDownIcon />}
      </PreviewDropdown>
      <PreviewContentWrapper isOpen={isOpen}>{children}</PreviewContentWrapper>
    </CodePanelPreviewWrapper>
  );
}

const CodePanelPreviewWrapper = styled.div`
  width: 100%;
  padding: var(--spacing-xs) var(--spacing-xs) var(--spacing-xs) var(--spacing-sm);
  border-bottom: 1px solid var(--border-color-secondary);
`;

const PreviewDropdown = styled.div`
  display: flex;
  align-items: center;

  gap: (--spacing-xxs);

  user-select: none;

  font-size: var(--font-size-base);
  cursor: pointer;
`;

const PreviewContentWrapper = styled.div<{ isOpen: boolean }>`
  display: ${({ isOpen }) => (isOpen ? 'grid' : 'none')};
  place-items: center;

  margin: auto 0;

  max-height: 50vh;
  width: 100%;
  max-width: 100%;

  overflow: auto;
`;
