<script setup lang="ts">
import { ref } from "vue";
import { useRouter } from "vue-router";
import { showToast } from "vant";
import { taskApi } from "../generated/api";
import { useModelApi } from "../composables/useModelApi";
import EmployeeSelect from "../components/EmployeeSelect.vue";

const router = useRouter();
const newTaskName = ref("");
const selectedAuthorId = ref(0);
const selectedResponsibleId = ref(0);

const {
  creating,
  error,
  create: createTaskApi,
} = useModelApi(taskApi, {
  createErrorMessage: "Не удалось создать задачу",
  autoLoad: false,
  autoLoadOnFilterChange: false,
});

async function createTask() {
  const name = newTaskName.value.trim();
  if (!name) {
    showToast("Введите название задачи");
    return;
  }

  const task = await createTaskApi({
    name,
    author_id: selectedAuthorId.value || null,
    responsible_id: selectedResponsibleId.value || null,
  });

  if (task) {
    showToast("Задача создана");
    router.push("/tasks");
  }
}

</script>

<template>
  <van-notice-bar
    v-if="error"
    class="notice"
    color="#991b1b"
    background="#fee2e2"
    left-icon="warning-o"
    wrapable
    :scrollable="false"
    :text="error"
  />

  <van-form class="card" @submit="createTask">
    <van-field
      v-model="newTaskName"
      name="name"
      label="Название"
      placeholder="Например: Купить молоко"
      clearable
      :disabled="creating"
    />
    <van-field label="Автор">
      <template #input>
        <EmployeeSelect v-model="selectedAuthorId" />
      </template>
    </van-field>
    <van-field label="Ответственный">
      <template #input>
        <EmployeeSelect v-model="selectedResponsibleId" />
      </template>
    </van-field>
    <div class="form-actions stacked-actions">
      <van-button
        block
        round
        type="primary"
        native-type="submit"
        :loading="creating"
        :disabled="!newTaskName.trim()"
      >
        Создать задачу
      </van-button>
      <van-button block round plain type="default" @click="router.back()">Отмена</van-button>
    </div>
  </van-form>

</template>
