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

import { CodeWalkthroughControlsStateContext } from '@redocly/theme/core/contexts';
import { StepWrapper } from '@redocly/theme/markdoc/components/CodeWalkthrough/CodeStep';
import { Switch } from '@redocly/theme/components/Switch/Switch';

export type CodeToggleProps = React.PropsWithChildren<{
  id: string;
  label: string;
  description?: React.ReactNode[];
}>;

export function CodeToggle(props: CodeToggleProps) {
  const { id, label, description, children } = props;
  const { getControlState, changeControlState } = useContext(CodeWalkthroughControlsStateContext);

  const toggleState = getControlState(id);

  if (!(toggleState && toggleState.render && typeof toggleState.value === 'boolean')) {
    return null;
  }
  const checked = toggleState.value;

  return (
    <ToggleWrapper data-component-name="Markdoc/CodeWalkthrough/CodeToggle">
      <ToggleContentWrapper>
        <ToggleSubtitle>
          <Switch
            value={checked}
            onChange={(newValue) => changeControlState(id, newValue)}
            stopPropagation
          />
          <div>{label}</div>
        </ToggleSubtitle>
        {description ? (
          <div>
            {description.map((paragraph, idx) => (
              <React.Fragment key={idx}>{paragraph}</React.Fragment>
            ))}
          </div>
        ) : null}
      </ToggleContentWrapper>
      {checked ? children : null}
    </ToggleWrapper>
  );
}

export const ToggleWrapper = styled.div`
  ${StepWrapper} {
    margin-left: 0;
  }
`;

export const ToggleSubtitle = styled.div`
  display: flex;
  gap: var(--spacing-sm);
  align-items: center;
  font-weight: var(--font-weight-bold);
`;

const ToggleContentWrapper = styled.div`
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xs);
  padding: var(--spacing-xs) 0;
`;
