/**
 * Custom link editor — URL, label, open-in-new-tab (no WordPress LinkControl).
 */
import { Button } from '@wordpress/components';
import { useEffect, useState } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { normalizeLink } from '../../interpolate';

/**
 * @param {object}   props
 * @param {object}   [props.value]
 * @param {Function} props.onChange
 * @param {Function} [props.onApply]     Called with normalized link on Apply (format toolbar).
 * @param {Function} [props.onRemove]    When set, shows a Remove action.
 * @param {Function} [props.onDone]      Optional Done (closes popover).
 * @param {boolean}  [props.showApply]   Format-toolbar mode: draft until Apply/Done.
 * @param {Function} [props.onDraftChange] Live draft updates (preview patch; no attrs).
 * @param {string}   [props.className]
 * @param {string}   [props.labelPlaceholder]
 * @param {boolean}  [props.compact]     Tighter layout for format toolbar.
 */
export default function LinkEditorForm( {
	value = {},
	onChange,
	onApply,
	onRemove,
	onDone,
	showApply = false,
	onDraftChange,
	className = '',
	labelPlaceholder,
	compact = false,
} ) {
	const initial = normalizeLink( value || {} );
	const [ draft, setDraft ] = useState( initial );

	useEffect( () => {
		setDraft( normalizeLink( value || {} ) );
	}, [ value?.title, value?.url, value?.opensInNewTab ] );

	const patch = ( partial ) => {
		const next = normalizeLink( { ...draft, ...partial } );
		setDraft( next );
		onDraftChange?.( next );

		if ( ! showApply ) {
			// Button / field editors: commit live (label, URL, new tab).
			onChange?.( next );
			return;
		}

		// Format-toolbar mode: keep label draft-only to avoid CE flicker, but
		// sync URL + open-in-new-tab into controlled value immediately.
		// Do not call onApply here — that commits into the contenteditable and
		// closes the panel.
		const keys = Object.keys( partial || {} );
		const touchesLive =
			keys.includes( 'url' ) || keys.includes( 'opensInNewTab' );
		if ( touchesLive ) {
			onChange?.( next );
		}
	};

	const apply = () => {
		const next = normalizeLink( draft );
		onChange?.( next );
		onApply?.( next );
		return next;
	};

	const finish = () => {
		// Commit any pending draft (e.g. label) before closing.
		apply();
		onDone?.();
	};

	return (
		<div
			className={
				'bm-link-editor' +
				( compact ? ' bm-link-editor--compact' : '' ) +
				( className ? ` ${ className }` : '' )
			}
		>
			<label className="bm-link-editor__field">
				<span className="bm-link-editor__label">
					{ __( 'Label', 'joc-blockora-morph' ) }
				</span>
				<input
					className="bm-field-input bm-link-editor__input"
					type="text"
					placeholder={
						labelPlaceholder ||
						__( 'Link text', 'joc-blockora-morph' )
					}
					value={ draft.title }
					onChange={ ( e ) => patch( { title: e.target.value } ) }
				/>
			</label>
			<label className="bm-link-editor__field">
				<span className="bm-link-editor__label">
					{ __( 'URL', 'joc-blockora-morph' ) }
				</span>
				<input
					className="bm-field-input bm-link-editor__input"
					type="url"
					placeholder={ __( 'https://', 'joc-blockora-morph' ) }
					value={ draft.url }
					onChange={ ( e ) => patch( { url: e.target.value } ) }
				/>
			</label>
			<label className="bm-link-editor__check">
				<input
					type="checkbox"
					checked={ draft.opensInNewTab }
					onChange={ ( e ) =>
						patch( { opensInNewTab: e.target.checked } )
					}
				/>
				{ __( 'Open in new tab', 'joc-blockora-morph' ) }
			</label>
			<div className="bm-link-editor__actions">
				{ typeof onRemove === 'function' ? (
					<Button
						variant="tertiary"
						isDestructive
						size="small"
						onClick={ onRemove }
					>
						{ __( 'Remove', 'joc-blockora-morph' ) }
					</Button>
				) : (
					<span />
				) }
				<div className="bm-link-editor__actions-end">
					{ showApply ? (
						<Button
							variant="primary"
							size="small"
							onClick={ apply }
						>
							{ __( 'Apply', 'joc-blockora-morph' ) }
						</Button>
					) : null }
					{ typeof onDone === 'function' ? (
						<Button
							variant={ showApply ? 'secondary' : 'primary' }
							size="small"
							onClick={ finish }
						>
							{ __( 'Done', 'joc-blockora-morph' ) }
						</Button>
					) : null }
				</div>
			</div>
		</div>
	);
}
