import React, { useState, useEffect } from 'react';
import Communications from './Communications';
import Credits from '../panel/Credits';
import { Transition } from '@headlessui/react';
import User from '../panel/User';
import { EnvelopeIcon } from '@heroicons/react/20/solid';
import queryString from 'query-string';
import { WpInlineScript } from '../../interfaces';
declare const webEngineAccount: WpInlineScript;

interface ManageArgs {
	pin?: String;
	registrationEmail?: string;
	registrationName?: string;
	onStep: Function;
	commAdministrative?: boolean;
	commNews?: boolean;
	commDeveloper?: boolean;
	onCommNews: Function;
	onCommAdministrative: Function;
	onCommDeveloper: Function;
	testMode?: boolean;
	logged: boolean;
	expires: number;
}

function forHumans( seconds: number ) {
	const levels = [
		[ Math.floor( seconds / 31536000 ), 'years' ],
		[ Math.floor( ( seconds % 31536000 ) / 86400 ), 'days' ],
		[ Math.floor( ( ( seconds % 31536000 ) % 86400 ) / 3600 ), 'hours' ],
		[
			Math.floor( ( ( ( seconds % 31536000 ) % 86400 ) % 3600 ) / 60 ),
			'minutes',
		],
		[ ( ( ( seconds % 31536000 ) % 86400 ) % 3600 ) % 60, 'seconds' ],
	];
	let returntext = '';

	for ( let i = 0, max = levels.length; i < max; i++ ) {
		if ( levels[ i ][ 0 ] === 0 ) {
			continue;
		}
		returntext +=
			' ' +
			levels[ i ][ 0 ] +
			' ' +
			( levels[ i ][ 0 ] === 1
				? ( levels[ i ][ 1 ] as string ).slice( 0, -1 )
				: levels[ i ][ 1 ] );
	}
	return returntext.trim();
}
export default function Manage( {
	registrationEmail,
	registrationName,
	onStep,
	commAdministrative,
	commNews,
	commDeveloper,
	onCommAdministrative,
	onCommNews,
	onCommDeveloper,
	testMode,
	logged,
	expires,
}: ManageArgs ) {
	const [ remainingTime, setRemainingTime ] = useState( expires );

	useEffect( () => {
		const interval = setInterval( () => {
			setRemainingTime( ( prevTime ) =>
				prevTime > 0 ? prevTime - 1 : 0
			);
		}, 1000 );

		return () => clearInterval( interval );
	}, [] );

	function resend() {
		const psdata = {
			action: 'we360cloud_account',
			token: webEngineAccount.token,
			route: 'resetemail',
			name: registrationName,
			email: registrationEmail,
		};
		fetch( webEngineAccount.url, {
			method: 'POST',
			headers: {
				'content-type': 'application/x-www-form-urlencoded',
			},
			body: queryString.stringify( psdata ),
		} )
			.then( ( response ) => response.json() )
			.then( ( json ) => {
				// email sent, set to 2 (success)
				if ( true === json.success ) {
					setRemainingTime( 3600 );
				}
			} );
	}

	return (
		<div className="text-white text-left">
			<div className="grid grid-cols-3 gap-4 mb-4 relative max-w-[512px]">
				{ /* TODO - add confirm step here - */ }
				<button
					type="button"
					onClick={ () => onStep( 'authenticated' ) }
					className="inline-flex w-full mt-4 justify-center rounded-md bg-cyan-500 px-3 py-2 text-sm font-semibold text-white shadow-lg hover:bg-cyan-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-cyan-500"
				>
					Configure
				</button>
				<button
					type="button"
					onClick={ () => onStep( 'documentation' ) }
					className="inline-flex w-full mt-4 justify-center rounded-md bg-cyan-500 px-3 py-2 text-sm font-semibold text-white shadow-lg hover:bg-cyan-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-cyan-500"
				>
					Documentation
				</button>
				<button
					type="button"
					disabled={ true }
					className="inline-flex w-full mt-4 justify-center rounded-md bg-gradient-to-t from-black/10 to-transparent px-3 py-2 text-sm font-semibold [text-shadow:_0_1px_10px_rgb(0_0_0_/_50%)]"
				>
					Manage account
				</button>
			</div>
			<User
				registrationName={ registrationName }
				registrationEmail={ registrationEmail }
				testMode={ testMode }
				logged={ logged }
			/>
			<Transition
				as="div"
				appear={ true }
				show={ true }
				enter="transform transition duration-300 ease-out"
				enterFrom="opacity-0"
				enterTo="opacity-100"
				leave="transform transition duration-300 transition ease-in"
				leaveFrom="opacity-100"
				leaveTo="opacity-0"
			>
				<div className="grid grid-cols-2 gap-4 mt-4">
					<Communications
						registrationStep={ 'register' }
						commAdministrative={ commAdministrative }
						commNews={ commNews }
						commDeveloper={ commDeveloper }
						onCommAdministrative={ ( opt: boolean ) => {
							onCommAdministrative( opt );
						} }
						onCommNews={ ( opt: boolean ) => {
							onCommNews( opt );
						} }
						onCommDeveloper={ ( opt: boolean ) => {
							onCommDeveloper( opt );
						} }
					/>
					<div>
						{ logged ? (
							<>
								<Credits testMode={ testMode } />
								{ testMode ? (
									<p className="mt-4">
										Test mode allows you to observe how the
										plugin functions in a test environment.
									</p>
								) : (
									<p className="mt-4">
										Credits are charges for successfully
										solving enhanced challenges or for
										premium add on services such as mail or
										text based checks.
									</p>
								) }
							</>
						) : (
							<div className="rounded-md bg-black/10 p-4">
								<p className="flex mb-2">
									<EnvelopeIcon
										aria-hidden="true"
										className="-ml-0.5 mr-2 size-5 text-white"
									/>
									Basic account
								</p>
								{ remainingTime > 0 ? (
									<p>
										Please check your inbox for instructions
										on how to finish setting up your
										Web-Engine cloud account to utilise the
										premium features - note this email will{ ' ' }
										<b>
											expire in{ ' ' }
											{ forHumans( remainingTime ) }
										</b>
										.<br />
										<button
											onClick={ () => location.reload() }
											className="mt-2 justify-center rounded-md bg-cyan-500 px-3 py-2 text-sm font-semibold text-white shadow-lg hover:bg-cyan-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-cyan-500"
										>
											Done
										</button>
									</p>
								) : (
									<p>
										Your invitation to complete registration
										has expired.
										<br />
										<button
											onClick={ () => resend() }
											className="mt-2 justify-center rounded-md bg-cyan-500 px-3 py-2 text-sm font-semibold text-white shadow-lg hover:bg-cyan-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-cyan-500"
										>
											Resend email
										</button>
									</p>
								) }
							</div>
						) }

						<button
							type="button"
							onClick={ () =>
								testMode ? null : onStep( 'unregister' )
							}
							className={
								'w-1/2 inline-flex mt-4 justify-center rounded-md bg-pink-700 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-pink-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-pink-600 ' +
								( testMode && 'opacity-50' )
							}
						>
							Disconnect
						</button>
					</div>
				</div>
			</Transition>
		</div>
	);
}
