import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import { useSearchParams } from 'react-router-dom';

import type { JSX } from 'react';

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

export function OIDCForbidden(): JSX.Element {
  const { useTranslate } = useThemeHooks();
  const { translate } = useTranslate();
  const [searchParams, setSearchParams] = useSearchParams();
  const [errorDescription, setErrorDescription] = useState<string>('');

  // use whatever you want here
  const URL_REGEX =
    /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/;

  const renderText = (text: string) =>
    text.split(' ').map((part: string) =>
      URL_REGEX.test(part) ? (
        <ErrorDescriptionLink key={part} href={part}>
          {part}{' '}
        </ErrorDescriptionLink>
      ) : (
        part + ' '
      ),
    );

  useEffect(() => {
    if (Array.from(searchParams).length) {
      setErrorDescription(searchParams.get('error_description') || searchParams.get('error') || '');
      setSearchParams({});
    }
  }, [searchParams, setSearchParams]);

  return (
    <Wrapper data-component-name="Pages/OIDCForbidden">
      <Header>403</Header>
      <Description data-translation-key="page.forbidden.title">
        {translate('page.forbidden.title', 'Access forbidden')}
      </Description>
      {errorDescription && <ErrorDescription>{renderText(errorDescription)}</ErrorDescription>}
    </Wrapper>
  );
}

const Wrapper = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 25px auto;
  font-family: var(--page-403-font-family);
  text-align: center;
`;

const Header = styled.div`
  color: var(--page-403-header-text-color);
  margin: var(--page-403-header-margin);
  font-size: var(--page-403-header-font-size);
  line-height: var(--page-403-header-line-height);
  font-weight: var(--page-403-header-font-weight);
`;

const Description = styled.div`
  color: var(--page-403-description-text-color);
  margin: var(--page-403-description-margin);
  font-size: var(--page-403-description-font-size);
  line-height: var(--page-403-description-line-height);
  font-weight: var(--page-403-description-font-weight);
`;

const ErrorDescription = styled.div`
  margin: var(--page-403-oidc-description-margin);
  font-size: var(--page-403-oidc-description-font-size);
  color: var(--page-403-description-text-color);
  line-height: var(--page-403-description-line-height);
  font-weight: var(--page-403-description-font-weight);
`;

const ErrorDescriptionLink = styled.a`
  color: var(--link-color-primary);

  &:hover {
    color: var(--link-color-primary-hover);
  }
`;
