import { useEffect, useState } from '@wordpress/element';
import { saveEditorialTask } from '../api';

const EMPTY = {
	task_id: 0,
	title: '',
	keyword: '',
	notes: '',
	ref_link: '',
	task_date: '',
	author_id: 0,
	lead_days: 7,
	recurrence: 'yearly',
};

export function TaskForm( { open, task, authors, i18n, taskNonce, onClose, onSaved } ) {
	const [ form, setForm ] = useState( EMPTY );
	const [ saving, setSaving ] = useState( false );
	const [ error, setError ] = useState( '' );

	useEffect( () => {
		if ( ! open ) {
			return;
		}
		if ( task ) {
			setForm( {
				task_id: task.id || 0,
				title: task.title || '',
				keyword: task.keyword || '',
				notes: task.notes || '',
				ref_link: task.refLink || '',
				task_date: task.taskDate || '',
				author_id: task.authorId || 0,
				lead_days: task.leadDays || 7,
				recurrence: task.recurrence || 'yearly',
			} );
		} else {
			const today = new Date();
			const iso = today.toISOString().slice( 0, 10 );
			setForm( { ...EMPTY, task_date: iso } );
		}
		setError( '' );
	}, [ open, task ] );

	if ( ! open ) {
		return null;
	}

	const set = ( key, val ) => setForm( ( prev ) => ( { ...prev, [ key ]: val } ) );

	const onSubmit = async ( e ) => {
		e.preventDefault();
		setSaving( true );
		setError( '' );
		try {
			const res = await saveEditorialTask( form, taskNonce );
			onSaved( res.tasks || [] );
			onClose();
		} catch ( err ) {
			setError( err?.message || 'error' );
		} finally {
			setSaving( false );
		}
	};

	return (
		<div className="nros-modal-backdrop" role="presentation" onClick={ onClose }>
			<div className="nros-modal nros-bento-card" role="dialog" onClick={ ( ev ) => ev.stopPropagation() }>
				<header className="nros-modal__head">
					<h3>{ task ? i18n.edit_task : i18n.new_task }</h3>
					<button type="button" className="nros-modal__close" onClick={ onClose }>×</button>
				</header>
				<form className="nros-task-form" onSubmit={ onSubmit }>
					<label>
						<span>{ i18n.task_title }</span>
						<input type="text" required value={ form.title } onChange={ ( e ) => set( 'title', e.target.value ) } />
					</label>
					<div className="nros-task-form__row">
						<label>
							<span>{ i18n.task_date }</span>
							<input type="date" required value={ form.task_date } onChange={ ( e ) => set( 'task_date', e.target.value ) } />
						</label>
						<label>
							<span>{ i18n.task_recurrence }</span>
							<select value={ form.recurrence } onChange={ ( e ) => set( 'recurrence', e.target.value ) }>
								<option value="none">{ i18n.rec_none }</option>
								<option value="yearly">{ i18n.rec_yearly }</option>
								<option value="monthly">{ i18n.rec_monthly }</option>
							</select>
						</label>
					</div>
					<div className="nros-task-form__row">
						<label>
							<span>{ i18n.task_author }</span>
							<select value={ form.author_id } onChange={ ( e ) => set( 'author_id', Number( e.target.value ) ) }>
								{ ( authors || [] ).map( ( a ) => (
									<option key={ a.id } value={ a.id }>{ a.name }</option>
								) ) }
							</select>
						</label>
						<label>
							<span>{ i18n.task_lead }</span>
							<input type="number" min="1" max="90" value={ form.lead_days } onChange={ ( e ) => set( 'lead_days', Number( e.target.value ) ) } />
						</label>
					</div>
					<label>
						<span>{ i18n.task_keyword }</span>
						<input type="text" value={ form.keyword } onChange={ ( e ) => set( 'keyword', e.target.value ) } />
					</label>
					<label>
						<span>{ i18n.task_ref }</span>
						<input type="url" value={ form.ref_link } onChange={ ( e ) => set( 'ref_link', e.target.value ) } />
					</label>
					<label>
						<span>{ i18n.task_notes }</span>
						<textarea rows={ 4 } value={ form.notes } onChange={ ( e ) => set( 'notes', e.target.value ) } />
					</label>
					{ error && <p className="nros-form-error">{ error }</p> }
					<div className="nros-modal__actions">
						<button type="button" className="button" onClick={ onClose }>{ i18n.cancel }</button>
						<button type="submit" className="button button-primary" disabled={ saving }>{ i18n.save_task }</button>
					</div>
				</form>
			</div>
		</div>
	);
}
