import api from '@/api';
import { validEmail, validName } from '@/mixins/validator';
import { UserForm, User } from '@/types/user';
import { getAll } from './search';

//
// MARK: User creation
//
const createModal: Ref<boolean> = ref(false);
const loadingCreate: Ref<boolean> = ref(false);
const errorCreate: Ref<string> = ref('');
const form: Ref<Partial<UserForm>> = ref({
  ID: 0,
  email: '',
  realName: '',
  groupID: -1,
});
const createUser = async () => {
  if (
    loadingCreate.value ||
    !form.value.email ||
    !form.value.groupID ||
    !form.value.realName ||
    !validEmail(form.value.email) ||
    !validName(form.value.realName)
  ) {
    return;
  }

  resetErrorCreate();
  setLoadingCreate(true);

  const [_, e] = await api.users.create(
    form.value.email,
    form.value.realName,
    form.value.groupID,
  );
  if (e && typeof e === 'string') {
    errorCreate.value = e;
  } else {
    closeModal();
    getAll();
  }

  setLoadingCreate(false);
};
const resetErrorCreate = () => (errorCreate.value = '');
const openModal = () => {
  setDefaultForm();
  setIsEditing(false);
  createModal.value = true;
};
const closeModal = () => (createModal.value = false);
const setLoadingCreate = (state: boolean) => (loadingCreate.value = state);
const setDefaultForm = () =>
  (form.value = {
    ID: 0,
    email: '',
    realName: '',
    groupID: -1,
  });

//
// MARK: Edit user
//
const isEditing: Ref<boolean> = ref(false);
const editUser = async () => {
  if (
    loadingCreate.value ||
    !form.value.ID ||
    !form.value.email ||
    !form.value.realName ||
    !form.value.groupID ||
    !validName(form.value.realName)
  ) {
    return;
  }

  resetErrorCreate();
  setLoadingCreate(true);

  const [_, e] = await api.users.update(
    form.value.ID,
    form.value.email,
    form.value.realName,
    form.value.groupID,
  );
  if (e && typeof e === 'string') {
    errorCreate.value = e;
  } else {
    closeModal();
    getAll();
  }

  setLoadingCreate(false);
};
const startEditUser = async (u: User) => {
  setIsEditing(true);

  form.value = {
    ID: u.ID,
    email: u.email,
    realName: u.realName,
    groupID: u.groupID,
  };
  console.log(form.value, u);
};
const setIsEditing = (state: boolean) => (isEditing.value = state);

export {
  createModal,
  loadingCreate,
  errorCreate,
  form,
  createUser,
  resetErrorCreate,
  openModal,
  closeModal,
  setLoadingCreate,
  setDefaultForm,
  isEditing,
  editUser,
  startEditUser,
  setIsEditing,
};
