//export const Dialogue: React.FC<Props> = ({children, close, isVisible, title}: Props) => {
// import { useRef } from 'react'

import { useState, useEffect } from 'react'; //, useCallback, useSyncExternalStore, useMemo
import { WpInlineScript } from '../../interfaces';
import queryString from 'query-string';
import { ArrowPathIcon } from '@heroicons/react/24/outline';
import { Transition } from '@headlessui/react';

declare const webEngineAccount: WpInlineScript;

export default function Credits( { testMode = false } ) {
	const [ loaded, setLoaded ] = useState( false );
	const [ balance, setBalance ] = useState(); // if !loaded then 0 is just a placeholder!
	useEffect( () => {
		// Anything in here is fired on component mount.
		// init();
		setLoaded( false );

		if ( true === testMode ) {
			setBalance( undefined );
			setLoaded( true );
			return;
		}

		const idata = {
			action: 'we360cloud_account',
			token: webEngineAccount.token,
			route: 'balance',
		};
		fetch( webEngineAccount.url, {
			method: 'POST',
			headers: {
				'content-type': 'application/x-www-form-urlencoded',
			},
			body: queryString.stringify( idata ),
		} )
			.then( ( response ) => response.json() )
			.then( ( data ) => {
				// const timeout = setTimeout(() => {
				if ( false === data || undefined === data.payload ) {
					setBalance( undefined );
				} else {
					setBalance( data.payload.balance );
				}
				setLoaded( true );
			} );
		return () => {
			// Anything in here is fired on component unmount.
		};
	}, [ testMode ] );
	return (
		<div>
			<div className="bg-black/10 p-4 rounded-md shadow-inner">
				<legend className="text-white mb-2">Available credit</legend>
				<div className="space-y-5">
					<div className="bg-black/10 p-4 py-8 rounded-md text-center shadow-inner">
						<div className="h-8">
							{ ! loaded && (
								<ArrowPathIcon className="w-8 h-8 animate-spin inline" />
							) }

							<Transition
								as="div"
								show={ loaded }
								enter="transform transition duration-300 ease-out"
								enterFrom="opacity-0"
								enterTo="opacity-100"
								leave="hidden"
							>
								<p className="order-first text-3xl tracking-tight font-black text">
									{ undefined === balance
										? '-'
										: Math.max(
												0,
												Number( balance )
										  ).toLocaleString() }
								</p>
							</Transition>
						</div>
					</div>
					<p className="mt-2">
						Visit the service site to manage your balance.
					</p>
				</div>
			</div>
		</div>
	);
}
