import React, { useState } from 'react';
import { black, LoadingWrapper, Text, Wrapper } from 'dot-design-system';
import { fontSizes } from '../styles/typography';
import { useStoreActions, useStoreState } from '../store/store.hooks';
import { ajaxAction } from '../ajax/ajax.utils';
import { timeout } from 'dot-utils';

function Authenticate({}: any) {
	const [loading, setLoading] = useState(false);
	const [success, setSuccess] = useState(false);
	const token = useStoreState((state) => state.authentication.token);
	const setToken = useStoreActions((actions) => actions.authentication.setToken);
	const setMessage = useStoreActions((actions) => actions.admin.setMessage);

	const handleSubmit = async (e: any) => {
		e.preventDefault();
		setLoading(true);
		const input = e.target.querySelector(`textarea`) as HTMLInputElement;

		if (!input || !input.value) {
			return;
		}

		const result = await ajaxAction({
			action: 'dot_press_save_token',
			data: {
				token: input.value,
			},
		});

		if (result) {
			setToken(input.value);
			setSuccess(true);
			await timeout(1000);
			setMessage({
				title: 'Success!',
				content: 'You have successfully connected your Dot Account.',
			});
		}

		await timeout(3000);
		setLoading(false);
		setSuccess(false);
	};

	const handleLinkOpen = (e: any) => {
		e.preventDefault();
		const anchor = e.target.closest('a');
		if (anchor) {
			window.open(anchor.href, 'DOT Audiences Portal', 'resizable,height=400,width=400');
		}
	};

	return (
		<Wrapper>
			<Text>
				<a
					href={`${process.env.APP_URL}/external-token/${window.location.host}`}
					onClick={handleLinkOpen}
				>
					Click here
				</a>{' '}
				to generate your unique DOT Press authentication token.
			</Text>
			<Wrapper
				component={'form'}
				onSubmit={handleSubmit}
				css={`
					max-width: 400px;
				`}
			>
				<Wrapper
					component={'textarea'}
					name={'dot-press-authentication-token'}
					defaultValue={token}
					css={`
						display: block;
					`}
					width={'100%'}
					height={200}
					placeholder={'Enter access code here'}
				/>
				<Wrapper
					component={'button'}
					type={'submit'}
					textAlign={'right'}
					width={'100%'}
					fontSize={fontSizes.theta}
					background={black}
					color={'#fff'}
				>
					<LoadingWrapper
						p={10}
						isLoading={loading}
						isSuccess={success}
						display={'inline-block'}
					>
						Save
					</LoadingWrapper>
				</Wrapper>
			</Wrapper>
		</Wrapper>
	);
}

export default Authenticate;
