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

import type { AuthProviderType } from '@redocly/realm/dist/shared/types/global-data';

import { withPathPrefix } from '@redocly/theme/core/utils';
import { Button } from '@redocly/theme/components/Button/Button';
import { H1 } from '@redocly/theme/components/Typography/H1';

import { GraviteeSsoError, LOGIN_CALLBACK_SLUG } from './constants';

export type LoginProps = {
  authIdps?: {
    idpId: string;
    type: AuthProviderType;
    title?: string;
  }[];
};

export default function (): JSX.Element {
  const [idpId, setIdpId] = React.useState<string | undefined>();
  const [redirectTo, setRedirectTo] = React.useState<string | undefined>();
  const [pathname, setPathname] = React.useState('');
  const [error, setError] = React.useState<GraviteeSsoError | string | undefined>();

  React.useEffect(() => {
    const searchParams = new URLSearchParams(window.location.search);

    const idpId = searchParams.get('idpId') || undefined;
    const redirectTo = searchParams.get('redirectTo') || undefined;
    const error = searchParams.get('error') || undefined;

    setIdpId(idpId);
    setRedirectTo(redirectTo);
    setError(error);
    setPathname(window.location.pathname);
  }, []);

  const searchParams = new URLSearchParams({
    idpId: idpId || '',
    redirectTo: redirectTo || '',
    loginPagePathname: pathname,
  });

  const errorMessage = getErrorMessage(error);

  return (
    <Wrapper
      action={`${withPathPrefix(LOGIN_CALLBACK_SLUG)}?${searchParams.toString()}`}
      method="POST"
    >
      <Header>Log in</Header>
      <Input type="text" id="username" name="username" placeholder="Username" autoFocus />
      <Input type="password" placeholder="Password" id="password" name="password" />
      {errorMessage ? <ErrorMessage>{errorMessage}</ErrorMessage> : null}
      <Button type="submit" variant="primary">
        Log in
      </Button>
    </Wrapper>
  );
}

const getErrorMessage = (error: GraviteeSsoError | string | undefined) => {
  if (error === GraviteeSsoError.INVALID_CREDENTIALS) {
    return 'Invalid username or password';
  } else if (error === GraviteeSsoError.UNKNOWN_ERROR) {
    return 'Something went wrong. Please try again';
  } else {
    return undefined;
  }
};

const Header = styled(H1)`
  color: var(--color-primary-base);
`;

const Wrapper = styled.form`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;

  gap: 20px;

  color: var(--text-color-primary);

  a {
    text-decoration: none;
  }
`;

const Input = styled.input`
  display: flex;
  outline: none;
  width: 360px;
  padding: var(--spacing-xs) var(--spacing-sm);
  align-items: center;
  gap: 10px;

  border: 1px solid var(--border-color-primary);
  border-radius: var(--border-radius-md);

  font-size: var(--font-size-base);
  line-height: var(--line-height-sm);

  background-color: var(--bg-color);

  &::placeholder {
    font-size: var(--font-size-base);
    color: var(--input-content-placeholder-color);
  }
`;

const ErrorMessage = styled.i`
  font-size: var(--font-size-sm);
  color: var(--color-error-base);
  width: 360px;
`;
