/**
 * External dependencies
 */
import { WebhookSettingsControl } from '@nelio-content/components';
import { isEmpty } from '@nelio-content/utils';
import type { WebhookSettings as WebhookSettingsType } from '@nelio-content/types';

/**
 * Internal dependencies
 */
import './style.scss';
import {
	useActiveNetwork,
	useActiveProfile,
	useRelatedPost,
	useWebhookSettingsInProfile,
} from '../../hooks';

export type WebhookSettingsProps = {
	readonly disabled: boolean;
};

export const WebhookSettings = ( {
	disabled,
}: WebhookSettingsProps ): JSX.Element | null => {
	const [ activeNetwork ] = useActiveNetwork();
	const activeProfile = useActiveProfile();
	const [ post ] = useRelatedPost();
	const [ webhookSettings, setWebhookSettings ] =
		useWebhookSettingsInProfile( activeProfile );

	const settings = { ...INIT_SETTINGS, ...webhookSettings };

	if ( activeNetwork !== 'webhook' || ! activeProfile ) {
		return null;
	}

	return (
		<WebhookSettingsControl
			className="nelio-content-social-message-editor__webhook-settings"
			isDisabled={ disabled }
			settings={ settings }
			type={ post?.type }
			hidePlaceholders={ isEmpty( post ) }
			onChange={ setWebhookSettings }
		/>
	);
};

const INIT_SETTINGS: WebhookSettingsType = {
	url: '',
	method: 'GET',
	headers: [],
	bodyType: 'none',
};
