import React from 'react';
import type { ComponentEvent, RestAction } from '../../types/project';
import { assignPageOnLoad, getPageOnLoadActionId } from './pageEventUtils';
import styles from './VisualEditor.module.css';

type Props = { events: ComponentEvent[] | undefined; actions: RestAction[]; onChange: (events: ComponentEvent[]) => void };

export default function PageEventEditor({ events, actions, onChange }: Props): React.ReactElement {
  const actionId = getPageOnLoadActionId(events);
  const enterActionId = events?.find(event => event.event === 'onEnter')?.actionId ?? '';
  const setEnter = (nextActionId: string) => onChange([
    ...(events ?? []).filter(event => event.event !== 'onEnter'),
    ...(nextActionId ? [{ event: 'onEnter', actionId: nextActionId }] : []),
  ]);
  const missingReference = actionId !== '' && !actions.some((action) => action.id === actionId);
  return (
    <div className={styles.pageEventEditor} data-testid="page-onload-editor">
      <label className={styles.pageEventLabel} htmlFor="page-onload-action">On load</label>
      <select id="page-onload-action" data-testid="page-onload-action" className={styles.pageEventSelect}
        value={actionId} onChange={(event) => onChange(assignPageOnLoad(events, event.target.value))}
        style={missingReference ? { borderColor: '#b91c1c' } : undefined}>
        <option value="">No action</option>
        {missingReference && <option value={actionId}>Missing action: {actionId}</option>}
        {actions.map((action) => <option key={action.id} value={action.id}>{action.name} ({action.id})</option>)}
      </select>
      <label className={styles.pageEventLabel} htmlFor="page-onenter-action">On enter</label>
      <select id="page-onenter-action" aria-label="On enter action" className={styles.pageEventSelect} value={enterActionId} onChange={event => setEnter(event.target.value)}>
        <option value="">No action</option>
        {actions.map(action => <option key={action.id} value={action.id}>{action.name} ({action.id})</option>)}
      </select>
      {actions.length === 0 && !missingReference && <span className={styles.pageEventHint}>Create a REST action first.</span>}
      {missingReference && <span className={styles.pageEventError} role="alert">Missing action &quot;{actionId}&quot;.</span>}
    </div>
  );
}
