import React from 'react';
import styled from 'styled-components';
import { saveAs } from 'file-saver';
import { Button, CodeBlock, H1, useThemeHooks } from '@redocly/theme';

// @ts-ignore
import { DocumentationLayout } from '@redocly/theme/layouts/DocumentationLayout';

type PageProps = {
  title: string;
  wsdl?: string;
  request?: string;
  description?: string;
};

type SoapDocsProps = {
  pageProps: PageProps;
};

const Template: React.FC<SoapDocsProps> = ({ pageProps }: SoapDocsProps) => {
  const { useSidebarSiblingsData, useCodeHighlight } = useThemeHooks();
  const { nextPage, prevPage } = useSidebarSiblingsData() || {};
  const { highlight } = useCodeHighlight() || {};

  const downloadWSDL = () => {
    const wsdlContent = pageProps.wsdl || '';
    const blob = new Blob([wsdlContent], { type: 'application/wsdl+xml' });

    saveAs(blob, `${pageProps.title || 'wsdl'}.wsdl`);
  };

  return (
    <DocumentationLayout
      tableOfContent={undefined}
      feedback={undefined}
      nextPage={nextPage}
      prevPage={prevPage}
    >
      <>
        {/* Render page with general information*/}
        {!pageProps.request ? (
          <>
            <H1>{pageProps.title}</H1>
            <MainPageContainer>
              <DownloadButton variant="primary" size="small" onClick={downloadWSDL}>
                Download WSDL
              </DownloadButton>
              <CodeBlock
                header={{
                  controls: {
                    copy: {},
                  },
                  title: pageProps.title,
                }}
                lang="xml"
                source={pageProps.wsdl}
                highlightedHtml={highlight(pageProps.wsdl || '', 'xml')}
              />
            </MainPageContainer>
          </>
        ) : (
          <>
            {/* Render a page with operation information */}
            <H1>{pageProps.title}</H1>
            {pageProps.description ? <Description>{pageProps.description}</Description> : null}

            <CodeBlock
              header={{
                controls: {
                  copy: {},
                },
                title: 'Request example',
              }}
              lang="xml"
              source={pageProps.request}
              highlightedHtml={highlight(pageProps.request || '')}
            />
          </>
        )}
      </>
    </DocumentationLayout>
  );
};

export default Template;

const MainPageContainer = styled.div`
  display: flex;
  flex-direction: column;
  gap: var(--spacing-base);
`;

const Description = styled.div`
  margin-bottom: var(--spacing-base);
`;

const DownloadButton = styled(Button)`
  align-self: flex-end;
`;
