import React, { useState } from 'react';
import { ArrowPathIcon } from '@heroicons/react/24/outline';
interface CheckOptionOpts {
	checked?: boolean;
	disabled?: boolean;
	onChange: Function;
	name: string;
	title: string;
	description?: string;
	loading?: boolean;
}
export default function CheckOption( {
	checked,
	disabled,
	onChange,
	name,
	title,
	description,
	loading = false,
}: CheckOptionOpts ) {
	const toggleCheck = ( e: any ) => {
		const newChecked = ! checked;
		setOurChecked( newChecked );
		onChange( newChecked );
		e.preventDefault();
	};
	const [ ourChecked, setOurChecked ] = useState( checked );
	return (
		// this is bonkers -  same render for both checked options, however wihtout without the conditional
		// the compoenent will not re-render - deel like I'm missing something
		// label will also not activate the input
		// think this is because onchange we need to re-render the component...
		<div className="relative flex items-start">
			<div className="flex h-6 items-center">
				{ ( ourChecked !== checked || loading ) && (
					<ArrowPathIcon className="w-4 h-4 animate-spin inline" />
				) }
				{ ourChecked === checked && checked && ! loading && (
					<input
						id={ name }
						name={ name }
						disabled={ disabled }
						type="checkbox"
						defaultChecked={ checked }
						onChange={ toggleCheck }
						aria-describedby={ name + '-description' }
						className="h-4 w-4 rounded border-zinc-300 text-sky-600 focus:ring-sky-600"
					/>
				) }
				{ ourChecked === checked && ! checked && ! loading && (
					<input
						id={ name }
						name={ name }
						disabled={ disabled }
						type="checkbox"
						defaultChecked={ checked }
						onChange={ toggleCheck }
						aria-describedby={ name + '-description' }
						className="h-4 w-4 rounded border-zinc-300 text-sky-600 focus:ring-sky-600"
					/>
				) }
			</div>
			<div className="ml-3 text-sm/6">
				<button className="text-left" onClick={ toggleCheck }>
					<label htmlFor={ name } className="font-medium text-white">
						{ title }
					</label>

					{ undefined !== description && (
						<p className="text-sky-100">{ description }</p>
					) }
				</button>
			</div>
		</div>
	);
}
