/**
 * External dependencies.
 */
import { __ } from '@wordpress/i18n';
import { useSelect } from '@wordpress/data';

/**
 * Internal dependencies.
 */
import CustomSelectControl from '@spectra-pro-components/CustomSelectControl';

/**
 * Renders a select control for choosing a post type.
 *
 * Fetches all available post types and displays them in a dropdown.
 * Updates the dynamic content settings with the selected post type.
 *
 * @since x.x.x
 *
 * @param {Object}   props               - The component props.
 * @param {Object}   props.settings      - The dynamic content settings from the context.
 * @param {Function} props.updateSetting - Function to update settings in the context.
 * @return {Element|null} The post type selector control or null if source is not 'post_type'.
 */
const PostTypeSelector = ( { settings, updateSetting } ) => {
	// Fetch available post types.
	const postTypes = useSelect( ( select ) => {
		const types = select( 'core' ).getPostTypes( { per_page: -1 } );
		
		if ( ! types ) {
			return [];
		}

		// Filter out some internal post types and format for select options.
		return types
			.filter( ( type ) => 
				type.viewable && 
				! [ 'attachment', 'wp_block', 'wp_template', 'wp_template_part', 'wp_navigation' ].includes( type.slug )
			)
			.map( ( type ) => ( {
				value: type.slug,
				label: type.labels.singular_name || type.name,
			} ) );
	}, [] );

	// Return null if source is not 'post_type'.
	if ( settings.source.type !== 'post_type' ) return null;

	// Set default post type if not set.
	const currentPostType = settings.source.postType || 'post';

	return (
		<CustomSelectControl
			label={ __( 'Post Type', 'spectra-pro' ) }
			value={ currentPostType }
			options={ postTypes }
			onChange={ ( newValue ) => {
				updateSetting( 'source.postType', newValue );
				// Reset post ID when post type changes.
				updateSetting( 'source.postId', 0 );
			} }
		/>
	);
};

export default PostTypeSelector;