import { DataForm } from '@wordpress/dataviews';
import type { Field, Form } from '@wordpress/dataviews';
import { useCallback, useEffect, useMemo, useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
// Dashboard is still experimental.
import {
	// eslint-disable-next-line @wordpress/use-recommended-components
	Button,
	// eslint-disable-next-line @wordpress/use-recommended-components
	Drawer,
} from '@wordpress/ui';
import { useDashboardInternalContext } from '../../context/dashboard-context';
import { useDashboardUIContext } from '../../context/ui-context';
import { getWidgetSettingsTitle } from './utils';
import styles from './widget-settings.module.css';
import type { WidgetAttributeValues } from '../../types';

/**
 * Side drawer that edits one instance's attributes, mounted once at the
 * dashboard root. It resolves the active instance from `settingsWidgetUuid`
 * in the UI context (set by the per-instance settings trigger), renders the
 * type's declarative `attributes` through `DataForm`, and enters from the
 * inline-end edge.
 *
 * Edits write to the staging layer, so they preview live behind the drawer
 * and are published on Save or reverted on any other exit. Available in
 * normal mode only; the settings entry point is hidden while the layout is
 * being edited.
 */
export function WidgetSettings(): React.ReactNode {
	const {
		layout,
		onLayoutChange,
		widgetTypes,
		commit,
		cancel: cancelStaging,
		hasUncommittedChanges,
		canPerform,
	} = useDashboardInternalContext();
	const { settingsWidgetUuid, setSettingsWidgetUuid } =
		useDashboardUIContext();

	// A trigger composed by the host can ask for any instance; the surface
	// itself checks the policy, so a denied `edit` never opens it.
	const requestedWidget = settingsWidgetUuid
		? layout.find( ( instance ) => instance.uuid === settingsWidgetUuid )
		: undefined;
	const open =
		!! requestedWidget &&
		canPerform( {
			operation: 'edit',
			widget: requestedWidget,
			widgetType: widgetTypes.find(
				( type ) => type.name === requestedWidget.type
			),
		} );

	// Keep the last opened instance resolved while the drawer animates
	// closed so its form and title don't blank out mid-transition. While
	// open the live `settingsWidgetUuid` wins, so opening shows no stale
	// frame.
	const [ lastWidgetUuid, setLastWidgetUuid ] = useState< string | null >(
		settingsWidgetUuid
	);
	useEffect( () => {
		if ( settingsWidgetUuid ) {
			setLastWidgetUuid( settingsWidgetUuid );
		}
	}, [ settingsWidgetUuid ] );

	const activeUuid = settingsWidgetUuid ?? lastWidgetUuid;
	const widget = activeUuid
		? layout.find( ( instance ) => instance.uuid === activeUuid )
		: undefined;
	const widgetType = widget
		? widgetTypes.find( ( type ) => type.name === widget.type )
		: undefined;

	const fields = useMemo< Field< WidgetAttributeValues >[] >(
		() =>
			( widgetType?.attributes ??
				[] ) as Field< WidgetAttributeValues >[],
		[ widgetType?.attributes ]
	);

	const form = useMemo< Form >(
		() => ( {
			layout: { type: 'regular', labelPosition: 'top' },
			fields: fields.map( ( field ) => field.id ),
		} ),
		[ fields ]
	);

	const handleChange = useCallback(
		( edits: Record< string, unknown > ) => {
			if ( ! widget ) {
				return;
			}
			onLayoutChange(
				layout.map( ( instance ) =>
					instance.uuid === widget.uuid
						? {
								...instance,
								attributes: {
									...( instance.attributes as object ),
									...edits,
								},
							}
						: instance
				)
			);
		},
		[ layout, onLayoutChange, widget ]
	);

	const close = useCallback(
		() => setSettingsWidgetUuid( null ),
		[ setSettingsWidgetUuid ]
	);

	const handleSave = useCallback( () => {
		commit();
		close();
	}, [ commit, close ] );

	const handleOpenChange = useCallback(
		( nextOpen: boolean ) => {
			// Any path out of the drawer other than Save discards the
			// staged edits.
			if ( ! nextOpen ) {
				cancelStaging();
				close();
			}
		},
		[ cancelStaging, close ]
	);

	// A denied `edit` closes the surface by prop, outside `handleOpenChange`.
	// Discard its staged edits the same way, so a later grant reopens clean.
	useEffect( () => {
		if ( requestedWidget && ! open ) {
			cancelStaging();
			close();
		}
	}, [ requestedWidget, open, cancelStaging, close ] );

	const hasForm = !! widget && !! widgetType && fields.length > 0;

	if ( ! hasForm ) {
		return null;
	}

	const title = getWidgetSettingsTitle( widgetType );
	const data = ( widget?.attributes ??
		widgetType?.example?.attributes ??
		{} ) as WidgetAttributeValues;

	return (
		<Drawer.Root
			open={ open }
			onOpenChange={ handleOpenChange }
			swipeDirection="right"
			modal={ false }
			disablePointerDismissal
		>
			<Drawer.Popup size="medium" className={ styles.popup }>
				<Drawer.Header>
					<Drawer.Title>{ title }</Drawer.Title>
					<Drawer.CloseIconButton />
				</Drawer.Header>

				<Drawer.Content>
					<DataForm< WidgetAttributeValues >
						data={ data }
						fields={ fields }
						form={ form }
						onChange={ handleChange }
					/>
				</Drawer.Content>

				<Drawer.Footer>
					<Button
						variant="minimal"
						tone="brand"
						size="compact"
						onClick={ () => handleOpenChange( false ) }
					>
						{ __( 'Cancel' ) }
					</Button>
					<Button
						variant="solid"
						tone="brand"
						size="compact"
						onClick={ handleSave }
						disabled={ ! hasUncommittedChanges }
					>
						{ __( 'Save' ) }
					</Button>
				</Drawer.Footer>
			</Drawer.Popup>
		</Drawer.Root>
	);
}
