/**
 * WordPress dependencies
 */
import {
	NoticeList,
	Popover,
	SlotFillProvider,
} from '@safe-wordpress/components';
import { useSelect, useDispatch } from '@safe-wordpress/data';
import { StrictMode } from '@safe-wordpress/element';
import { store as NOTICES } from '@safe-wordpress/notices';

/**
 * External dependencies
 */
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { PremiumDialog } from '@nelio-content/components';
import { withSubscriptionCheck } from '@nelio-content/data';

/**
 * Internal dependencies
 */
import './style.scss';
import { useAreStatusesDirty } from '~/nelio-content-pages/settings/custom-statuses/hooks';
import { useUnsavedExitEffect } from '~/nelio-content-pages/settings/automations/hooks';

import { StatusesList } from '../statuses-list';
import { StatusEditor } from '../status-editor';

export const Layout = (): JSX.Element => (
	<StrictMode>
		<SlotFillProvider>
			<InternalLayout />
			<PremiumDialog />
			<Popover.Slot />
		</SlotFillProvider>
	</StrictMode>
);

const InternalLayout = withSubscriptionCheck( 'raw/custom-statuses', () => {
	const { notices, removeNotice } = useNotices();
	const isDirty = useAreStatusesDirty();

	useUnsavedExitEffect( isDirty );

	return (
		<div className="nelio-content-custom-statuses-settings-layout">
			<NoticeList
				notices={ notices }
				className="components-editor-notices__pinned"
				onRemove={ removeNotice }
			/>
			<DndProviderHelper>
				<StatusesList />
			</DndProviderHelper>
			<StatusEditor />
		</div>
	);
} );

// =====
// HOOKS
// =====

const useNotices = () => {
	const notices = useSelect(
		( select ) => select( NOTICES ).getNotices(),
		[]
	);
	const { removeNotice } = useDispatch( NOTICES );
	return { notices, removeNotice };
};

// NOTE: This is a TS workaround.
const DndProviderHelper = ( { children }: { children: JSX.Element } ) => (
	// eslint-disable-next-line @typescript-eslint/ban-ts-comment
	// @ts-ignore:next-line
	<DndProvider backend={ HTML5Backend }>{ children }</DndProvider>
);
