import React, { useState } from 'react';
import { black, Clickable, Flex, secondary, Text, Title, Wrapper } from 'dot-design-system';
import CircleIconButton from '../elements/CircleIconButton';
import { useStoreActions, useStoreState } from '../store/store.hooks';
import { ajaxAction } from '../ajax/ajax.utils';
import { AjaxState } from '../ajax/ajax.model';
// @ts-ignore
import mobilesImgSrc from '../assets/dot-mobiles.png';
import { getGlobal } from '../utils/wp';

interface Props {}

function CreateAccount({}: Props) {
	const hasToken = useStoreState((state) => state.authentication.hasToken);
	const setToken = useStoreActions((actions) => actions.authentication.setToken);
	const [isLoading, setIsLoading] = useState(false);

	const handleClick = async (e: any) => {
		e.preventDefault();

		if (!hasToken) {
			const anchor = e.target.closest('a');
			if (anchor) {
				window.open(anchor.href, 'DOT Audiences Portal', 'resizable,height=800,width=800');
			}
		}

		setIsLoading(true);
		const result = await ajaxAction({ action: 'dot_press_delete_token', method: 'post' });

		if (result !== AjaxState.Error) {
			setToken('');
		}
		setIsLoading(false);
	};

	return (
		<Flex
			justifyContent={'space-between'}
			css={`
				@media (max-width: 775px) {
					justify-content: unset;
					flex-direction: column;
				}
			`}
		>
			<Wrapper opacity={(isLoading && 0.5) || 1} mr={20} mb={50}>
				{hasToken && (
					<Flex alignItems={'flex-start'} itemGap={5} mt={50}>
						<Wrapper
							background={secondary}
							borderRadius={'50%'}
							width={12}
							height={12}
							mt={3}
							border={`0.5px solid ${black}`}
						/>
						<Wrapper>
							<Title mt={0} mb={5}>
								DOT Account Connected
							</Title>
							<Text mt={0}>
								(Click{' '}
								<Clickable
									onClick={handleClick}
									component={'span'}
									css={`
										text-decoration: underline;

										&:hover {
											text-decoration: none;
										}
									`}
								>
									here
								</Clickable>{' '}
								to disconnect)
							</Text>
						</Wrapper>
					</Flex>
				)}
				{!hasToken && (
					<CircleIconButton
						component={'a'}
						href={`${process.env.APP_URL}/choose-sign-up?host=${window.location.host}`}
						onClick={handleClick}
						mt={(hasToken && 10) || 50}
					>
						Click here to Create Account/Login
					</CircleIconButton>
				)}
			</Wrapper>
			<Wrapper>
				<Wrapper
					component={'img'}
					width={'100%'}
					src={getGlobal().jsUrlPath + mobilesImgSrc}
					alt='DOT'
					css={`
						max-width: 550px;

						@media (min-width: 775px) {
							transform: translateY(-30px);
						}
					`}
				/>
			</Wrapper>
		</Flex>
	);
}

export default CreateAccount;
