import React, { useMemo } from 'react';
import { Box, Text, color } from 'folds';
import { Link, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useAuthFlows } from '../../../hooks/useAuthFlows';
import { useAuthServer } from '../../../hooks/useAuthServer';
import { useParsedLoginFlows } from '../../../hooks/useParsedLoginFlows';
import { PasswordLoginForm } from './PasswordLoginForm';
import { getRegisterPath } from '../../pathUtils';
import { LoginPathSearchParams } from '../../paths';
import * as css from '../styles.css';

const useLoginSearchParams = (searchParams: URLSearchParams): LoginPathSearchParams =>
  useMemo(
    () => ({
      username: searchParams.get('username') ?? undefined,
      email: searchParams.get('email') ?? undefined,
    }),
    [searchParams]
  );

export function Login() {
  const { t } = useTranslation();
  const server = useAuthServer();
  const { loginFlows } = useAuthFlows();
  const [searchParams] = useSearchParams();
  const loginSearchParams = useLoginSearchParams(searchParams);

  const parsedFlows = useParsedLoginFlows(loginFlows.flows);

  return (
    <Box direction="Column" gap="500">
      {parsedFlows.password && (
        <PasswordLoginForm
          defaultUsername={loginSearchParams.username}
          defaultEmail={loginSearchParams.email}
        />
      )}
      {!parsedFlows.password && (
        <Text style={{ color: color.Critical.Main }}>
          {t('Auth.error_client_unsupported', { server })}
        </Text>
      )}
      <Text
        align="Center"
        className={css.AuthBottomLink}
        style={{ color: 'rgba(232, 228, 223, 0.55)' }}
      >
        {t('Auth.new_here')}{' '}
        <Link to={getRegisterPath(server)} style={{ fontWeight: 600 }}>
          {t('Auth.create_account')}
        </Link>
      </Text>
    </Box>
  );
}
