import cx from 'clsx';
import { isEmpty, isNil } from 'lodash-es';
import { useActionState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useCreateScheme } from '../stores/schemes';
import styles from './NewScheme.module.css';

export function NewScheme() {
  const createScheme = useCreateScheme();
  const navigate = useNavigate();
  const [errors, formAction] = useActionState((prevState, formData) => {
    try {
      const name = formData.get('name') as string;
      if (isNil(name) || isEmpty(name)) {
        throw { name: 'Name is required' };
      }
      const description = (formData.get('description') ?? null) as string | null;
      const newId = createScheme(name, description);
      navigate(`../${newId}`);
    } catch (error) {
      return error;
    }
    return {};
  }, {});

  return (
    <form action={formAction} className={styles.create_scheme_form_layout}>
      <div className={styles.form_row}>
        <label>
          Name <span>*</span>
        </label>
        <input type="text" name="name" className={styles.name_input} />
        {errors.name && <div className={styles.error_message}>{errors.name}</div>}
      </div>
      <div className={styles.form_row}>
        <label>Description</label>
        <textarea rows={5} name="description" className={styles.description_input} />
      </div>
      <div className={styles.form_row}>
        <button type="submit" className={cx('primary')}>
          Create
        </button>
      </div>
    </form>
  );
}
