import { Page } from '@wordpress/admin-ui';
import { __, _x } from '@wordpress/i18n';
import { useSelect, useDispatch } from '@wordpress/data';
import { store as coreStore } from '@wordpress/core-data';
import { DataForm } from '@wordpress/dataviews';
import { MediaEdit } from '@wordpress/fields';
import { decodeEntities } from '@wordpress/html-entities';
import { useViewConfig } from '@wordpress/views';

// The screen only renders a form, so it requests the `form` of the entity
// view configuration alone.
const VIEW_CONFIG_FIELDS = [ 'form' ];

const fields = [
	{
		id: 'title',
		type: 'text',
		label: __( 'Site Title' ),
		description: __(
			"Displays in your site's layout via the Site Title block."
		),
		getValue: ( { item } ) => decodeEntities( item.title ?? '' ),
	},
	{
		id: 'description',
		type: 'text',
		label: __( 'Site Tagline' ),
		description: __(
			"In a few words, explain what this site is about. Displays in your site's layout via the Site Tagline block."
		),
		getValue: ( { item } ) => decodeEntities( item.description ?? '' ),
	},
	{
		id: 'site_logo',
		type: 'media',
		label: __( 'Site Logo' ),
		description: __(
			"Displays in your site's layout via the Site Logo block."
		),
		placeholder: __( 'Choose logo' ),
		Edit: MediaEdit,
		setValue: ( { value } ) => ( {
			site_logo: value ?? 0,
		} ),
	},
	{
		id: 'site_icon',
		type: 'media',
		label: __( 'Site Icon' ),
		description: __(
			'Shown in browser tabs, bookmarks, and mobile apps. It should be square and at least 512 by 512 pixels.'
		),
		placeholder: __( 'Choose icon' ),
		Edit: MediaEdit,
		setValue: ( { value } ) => ( {
			site_icon: value ?? 0,
		} ),
	},
];

export default function SidebarIdentity() {
	const data = useSelect(
		( select ) =>
			select( coreStore ).getEditedEntityRecord( 'root', 'site' ),
		[]
	);
	const { editEntityRecord } = useDispatch( coreStore );
	const { form } = useViewConfig( {
		kind: 'root',
		name: 'site',
		fields: VIEW_CONFIG_FIELDS,
	} );

	const onChange = ( edits ) => {
		editEntityRecord( 'root', 'site', undefined, edits );
	};

	if ( ! form ) {
		return null;
	}

	return (
		<Page title={ _x( 'Identity', 'site identity' ) } headingLevel={ 2 }>
			<div className="edit-site-sidebar-identity__form">
				<DataForm
					data={ data }
					fields={ fields }
					form={ form }
					onChange={ onChange }
				/>
			</div>
		</Page>
	);
}
