import { useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { useController, useFormContext } from 'react-hook-form';
import { ModuleCard } from './ModuleCard';

/**
 * A Modules-tab card for a module that's real in this codebase (AdSense, Ad Blocker) and has its own toggle field. Activate/Deactivate flips the field and submits through the same save path the page's header "Save Changes" button uses — every currently-dirty field, not just this one — so nothing unsaved is ever at risk, and the resulting schema refetch (see Settings.jsx) picks up the module's own settings tab appearing/disappearing.
 *
 * @param {Object}   props
 * @param {string}   props.fieldId     Settings field id for the module toggle.
 * @param {Function} props.icon        Icon component.
 * @param {string}   props.label       Module label.
 * @param {string}   props.description Module description.
 * @param {Function} props.onSave      Saves the current form state.
 */
export function ActiveModuleCard( {
	fieldId,
	icon,
	label,
	description,
	onSave,
} ) {
	const { control, formState } = useFormContext();
	const { field } = useController( { name: fieldId, control } );
	const [ error, setError ] = useState( null );
	const [ saving, setSaving ] = useState( false );

	const handleToggle = async () => {
		field.onChange( ! field.value );
		setError( null );
		setSaving( true );

		try {
			await onSave();
		} catch {
			setError(
				__( 'Could not save. Please try again.', 'advanced-ads' )
			);
		} finally {
			setSaving( false );
		}
	};

	return (
		<ModuleCard
			icon={ icon }
			label={ label }
			description={ description }
			active={ !! field.value }
			saving={ saving }
			error={ error }
			onToggle={ handleToggle }
		/>
	);
}
