import { Button } from '@wordpress/components';
import { __ } from '@wordpress/i18n';
import { useEffect, useState } from '@wordpress/element';
import { linkOff } from '@wordpress/icons';
import ConnectionStatus from './ConnectionStatus';
import LianaAPIFields from './LianaAPIFields';

type LianaMailerSettingsProps = {
	connected: boolean;
	loading: boolean;
	onReset: () => void;
	onSave: ( event: React.FormEvent< HTMLFormElement > ) => void;
	restEndpoint: string;
	settings: LianaAPISettings;
};

export default function LianaMailerSettings( props: LianaMailerSettingsProps ) {
	const { connected, loading, onReset, onSave, restEndpoint, settings } =
		props;
	const [ stateSettings, setStateSettings ] = useState( settings );

	const handleInputChange = ( name: string, value: string ) => {
		setStateSettings( ( prevSettings ) => ( {
			...prevSettings,
			[ name ]: value,
		} ) );
	};

	useEffect( () => {
		if ( ! settings ) {
			setStateSettings( {} );
		} else {
			setStateSettings( settings );
		}
	}, [ settings ] );

	const submitButtonText = loading
		? __( 'Saving…', 'liana-with-growthstack' )
		: __( 'Save Settings', 'liana-with-growthstack' );

	return (
		<div className="gs-box">
			<div className="gs-flex gs-flex--justify-between gs-flex--align-start">
				<div>
					<h2 className="gs-box__title">
						{ __( 'LianaMailer API Settings', 'liana-with-growthstack' ) }
					</h2>
					<p className="gs-box__desc">
						<ConnectionStatus
							connected={ connected }
							settings={ settings }
						/>
					</p>
				</div>
				<Button
					disabled={ loading }
					icon={ linkOff }
					onClick={ onReset }
					type="button"
					variant="tertiary"
				>
					{ __( 'Reset', 'liana-with-growthstack' ) }
				</Button>
			</div>
			<form
				className="gs-settings-form"
				method="post"
				action={ restEndpoint }
				onSubmit={ ( event ) => onSave( event ) }
			>
				<LianaAPIFields
					values={ stateSettings }
					onInputChange={ handleInputChange }
				/>
				<div className="gs-submit-container">
					<Button
						disabled={ loading }
						type="submit"
						variant="primary"
					>
						{ submitButtonText }
					</Button>
				</div>
			</form>
		</div>
	);
}
