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

export function NewScheme() {
  const createScheme = useCreateScheme();
  const navigate = useNavigate();
  const [schemeType, setSchemeType] = useState<SchemeTypeOption['value']>('q_scheme');
  const [errors, formAction] = useActionState<{ [key: string]: string }, FormData>(
    (_prevState, formData): { [key: string]: string } => {
      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 schemeType = (formData.get('type') ?? 'q_scheme') as SchemeTypeOption['value'];
        const newId = createScheme(name, schemeType, description);
        navigate(`../${newId}`);
      } catch (error) {
        return error as { [key: string]: string };
      }
      return {} as { [key: string]: string };
    },
    {},
  );

  return (
    <form action={formAction} className={styles.create_scheme_form_layout}>
      <div className={styles.form_row}>
        <label>
          Scheme Type <span>*</span>
        </label>
        <VSegmentedControl
          options={SchemeTypeOptions}
          extendClassName={styles.custom_segment}
          value={schemeType}
          onChange={(v) => setSchemeType(v as SchemeTypeOption['value'])}
        />
        <input type="hidden" name="type" value={schemeType} />
      </div>
      <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>
  );
}
