var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
/* eslint-disable react-hooks/exhaustive-deps */
import { transparentize } from 'polished';
import { useEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router';
import styled from '@darajs/styled-components';
import { Button } from '@darajs/ui-components';
import DefaultFallback from '../../components/fallback/default';
import { useRouterContext } from '../../router/context';
import Center from '../../shared/center/center';
import { requestSessionToken, verifySessionToken } from '../auth';
const Wrapper = styled.div `
    display: flex;
    flex: 1 1 0%;
    flex-direction: column;
    justify-content: center;

    min-height: 100%;

    background: ${(props) => `radial-gradient(circle closest-corner at 50% 40%, ${transparentize(0.9, props.theme.colors.background)} 0%, ${transparentize(0.8, props.theme.colors.blue4)} 70%),radial-gradient(circle closest-corner at 20% 150%, ${transparentize(0.8, props.theme.colors.error)} 0%, ${transparentize(0.2, props.theme.colors.blue4)} 230%)`};
`;
const Card = styled.div `
    padding: 1.5rem;

    color: ${(props) => props.theme.colors.text};

    background-color: ${(props) => props.theme.colors.blue1};
    border-radius: 1rem;
    box-shadow: ${(props) => props.theme.shadow.medium};

    @media (width >= 640px) {
        width: 100%;
        max-width: 24rem;
        margin-right: auto;
        margin-left: auto;
    }
`;
const FormWrapper = styled.div `
    margin-top: 1.5rem;
`;
const Form = styled.form `
    > * + * {
        margin-top: 1.5rem;
    }
`;
const ErrorText = styled.h3 `
    margin: 0;

    font-size: 0.875rem;
    font-weight: 500;
    line-height: 1.25rem;
    color: ${(props) => props.theme.colors.error};
    letter-spacing: 0.025em;

    visibility: ${(props) => (props.$hidden ? 'hidden' : 'visible')};
`;
const Label = styled.label `
    font-weight: 500;
    line-height: 1.5rem;
`;
const StyledInput = styled.input `
    display: flex;
    display: block;
    align-items: center;

    width: 100%;
    height: 2.5rem;
    margin-top: 0.5rem;
    padding: 0 1rem;

    font-size: 1rem;
    line-height: 1.5rem;
    color: ${(props) => props.theme.colors.text};

    background-color: ${(props) => props.theme.colors.blue1};
    border: none;
    border-radius: 0.25rem;
    outline: none;
    box-shadow:
        inset 0 0 0 0 ${(props) => props.theme.colors.blue1},
        inset 0 0 0 1px ${(props) => (props.$error ? props.theme.colors.error : props.theme.colors.grey2)},
        0 1px 2px 0 rgb(0 0 0 / 5%);

    :active,
    :focus {
        box-shadow:
            inset 0 0 0 0 ${(props) => props.theme.colors.blue1},
            inset 0 0 0 2px ${(props) => (props.$error ? props.theme.colors.error : props.theme.colors.primary)},
            0 1px 2px 0 rgb(0 0 0 / 5%);
    }
`;
const StyledButton = styled(Button) `
    width: 100%;
    font-weight: 600;
    line-height: 1.5rem;
    box-shadow: 0 1px 2px 0 rgb(0 0 0 / 5%);

    :active,
    :focus {
        outline-color: ${(props) => props.theme.colors.primary};
        outline-width: 2px;
        outline-offset: 2px;
    }
`;
/**
 * The Login component gets the username and password from the user and generates a session token.
 */
function BasicAuthLogin() {
    var _a;
    const [isVerifyingToken, setIsVerifyingToken] = useState(true);
    const [isLoggingIn, setIsLoggingIn] = useState(false);
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [isError, setIsError] = useState(false);
    const location = useLocation();
    const navigate = useNavigate();
    const { defaultPath } = useRouterContext();
    const queryParams = new URLSearchParams(location.search);
    const previousLocation = (_a = queryParams.get('referrer')) !== null && _a !== void 0 ? _a : defaultPath;
    const login = () => __awaiter(this, void 0, void 0, function* () {
        setIsLoggingIn(true);
        setIsError(false);
        try {
            const sessionCreated = yield requestSessionToken({ password, username });
            if (sessionCreated) {
                navigate(decodeURIComponent(previousLocation));
            }
        }
        catch (_a) {
            setIsError(true);
        }
        setIsLoggingIn(false);
    });
    useEffect(() => {
        // If we landed on this page with a valid session already, redirect.
        verifySessionToken().then((verificationResult) => {
            if (verificationResult === 'verified') {
                navigate(decodeURIComponent(previousLocation), { replace: true });
            }
            else if (verificationResult === 'login_required') {
                setIsVerifyingToken(false);
            }
        });
    }, []);
    // Don't show the form yet until we check existing token
    if (isVerifyingToken) {
        return (_jsx(Center, { children: _jsx(DefaultFallback, {}) }));
    }
    return (_jsx(Wrapper, { children: _jsx(Card, { children: _jsx(FormWrapper, { children: _jsxs(Form, { onSubmit: (e) => {
                        e.preventDefault();
                        login();
                    }, children: [_jsxs("div", { children: [_jsx(Label, { htmlFor: "username", children: "Username" }), _jsx(StyledInput, { "$error": isError, id: "username", onChange: (e) => setUsername(e.target.value), required: true, type: "text", value: username })] }), _jsxs("div", { children: [_jsx(Label, { htmlFor: "password", children: "Password" }), _jsx(StyledInput, { "$error": isError, id: "password", onChange: (e) => setPassword(e.target.value), required: true, type: "password", value: password })] }), _jsx(ErrorText, { "$hidden": !isError, style: { marginTop: '1rem' }, children: "Incorrect Username or Password" }), _jsx("div", { children: _jsx(StyledButton, { loading: isLoggingIn, style: { color: 'white' }, styling: "primary", type: "submit", children: "Sign in" }) })] }) }) }) }));
}
export default BasicAuthLogin;
//# sourceMappingURL=basic-auth-login.js.map