<template>
  <q-form @submit="onSubmit" class="q-gutter-md">
    <q-input
      filled
      v-model="modifiedTask.title"
      label="Task Title"
      hint="A short description of the task"
      lazy-rules
      :rules="[
            (val: string | any[]) =>
              (val && val.length > 0) || 'Please enter a title for the task',
          ]"
    />
    <q-editor
      filled
      v-model="modifiedTask.description"
      label="Detailed Description"
      hint="A detailed description of the task"
      lazy-rules
      placeholder="Enter a detailed description..."
    />

    <q-input
      filled
      v-model="modifiedTask.due_date"
      mask="date"
      :rules="[dateRule]"
      hint="Enter the due date"
      lazy-rules
    >
      <template v-slot:append>
        <q-icon name="event" class="cursor-pointer">
          <q-popup-proxy cover transition-show="scale" transition-hide="scale">
            <q-date
              v-model="modifiedTask.due_date"
              @input="updateDateISO"
              today-btn
            >
              <div class="row items-center justify-end">
                <q-btn v-close-popup label="Close" color="primary" flat />
              </div>
            </q-date>
          </q-popup-proxy>
        </q-icon>
      </template>
    </q-input>
    <div>
      <q-select
        label="Skills Required"
        hint="Add a list of required skills, to help people find things in their ability"
        v-model="modifiedTask.required_skills"
        use-input
        use-chips
        multiple
        clearable
        emit-value
        map-options
        input-debounce="250"
        :options="skillTagOptions"
        option-label="name"
        option-value="$id"
        @filter="filterSkillTags"
      >
      </q-select>
    </div>
    <div>
      <q-select
        label="Tags"
        hint="Add Tags to help with searching"
        v-model="modifiedTask.tags"
        use-input
        use-chips
        multiple
        clearable
        emit-value
        map-options
        input-debounce="250"
        :options="taskTagOptions"
        option-label="name"
        option-value="$id"
        @filter="filterTaskTags"
      >
      </q-select>
    </div>
    <q-input
      label="Estimated Duration"
      v-model.number="modifiedTask.duration"
      type="number"
      filled
      suffix="hrs"
      style="max-width: 200px"
    />
    <q-input
      label="Number of Required Volunteers"
      v-model.number="modifiedTask.volunteers_required"
      type="number"
      filled
      style="max-width: 200px"
    />
    <q-select
      label="Status of Task"
      v-model="modifiedTask.status"
      :options="TASKSTATUS"
    >
    </q-select>
    <div>
      <q-select
        label="Dependencies"
        hint="Add a list of tasks that need to be complete before this one"
        v-model="modifiedTask.depends_on"
        use-input
        multiple
        clearable
        emit-value
        map-options
        input-debounce="250"
        :options="tasks"
        option-label="title"
        option-value="$id"
        @filter="filterTasks"
      >
      </q-select>
    </div>
    <div>
      <q-select
        label="Boat"
        hint="Add a boat, if applicable"
        v-model="modifiedTask.boat"
        use-input
        clearable
        emit-value
        map-options
        input-debounce="250"
        :options="boatList"
        option-label="name"
        option-value="$id"
      >
      </q-select>
    </div>
    <div>
      <q-btn
        label="Submit"
        type="submit"
        color="primary"
        flat
        class="q-ml-sm"
      />
      <q-btn
        label="Cancel"
        color="secondary"
        flat
        class="q-ml-sm"
        @click="$router.go(-1)"
      />
    </div>
  </q-form>
</template>

<script setup lang="ts">
import { computed, reactive, ref, Ref } from 'vue';
import { useRouter } from 'vue-router';
import { useTaskStore, TASKSTATUS } from 'src/stores/task';
import type { TaskTag, SkillTag, Task } from 'src/stores/task';
import { date } from 'quasar';
import { Boat, useBoatStore } from 'src/stores/boat';

const props = defineProps<{ taskId?: string }>();
const taskStore = useTaskStore();

const defaultTask = <Task>{
  description: '',
  due_date: date.formatDate(Date.now(), 'YYYY-MM-DD'),
  required_skills: [],
  title: '',
  tags: [],
  duration: 0,
  volunteers: [],
  volunteers_required: 0,
  status: 'ready',
  depends_on: [],
};

taskStore.fetchTasks();

const { taskId } = props;
const targetTask = taskId && taskStore.tasks.find((t) => t.$id === taskId);
const modifiedTask = reactive(targetTask ? targetTask : defaultTask);

let tasks = taskStore.tasks;
const boatList = ref<Boat[]>(useBoatStore().boats);

const skillTagOptions = ref<SkillTag[]>(taskStore.skillTags);
const taskTagOptions = ref<TaskTag[]>(taskStore.taskTags);

const filterSkillTags = computed(
  () =>
    (val: string, update: (cb: () => void) => void): void => {
      return filterTags(skillTagOptions, taskStore.skillTags, val, update);
    }
);
const filterTaskTags = computed(
  () =>
    (val: string, update: (cb: () => void) => void): void => {
      return filterTags(taskTagOptions, taskStore.taskTags, val, update);
    }
);
const filterTasks = computed(
  () =>
    (val: string, update: (cb: () => void) => void): void => {
      if (val === '') {
        update(() => {
          tasks = taskStore.tasks;
        });
        return;
      }

      update(() => {
        tasks = taskStore.filterTasksByTitle(val);
      });
    }
);

function filterTags(
  optionVar: Ref<(SkillTag | TaskTag)[] | undefined>,
  optionSrc: SkillTag[] | TaskTag[],
  val: string,
  update: (cb: () => void) => void
): void {
  if (val === '') {
    update(() => {
      optionVar.value = optionSrc;
    });
    return;
  }

  update(() => {
    optionVar.value = optionSrc.filter((v) =>
      v.name.toLowerCase().includes(val.toLowerCase())
    );
  });
}

// Method to update the model in ISO 8601 format
const updateDateISO = (value: string) => {
  modifiedTask.due_date = date.formatDate(value, 'YYYY-MM-DD');
};
const dateRule = (val: string) => {
  // Check if the date is valid using Quasar's date utils if needed
  // For simplicity, we are directly checking the date string validity
  return (val && !isNaN(Date.parse(val))) || 'Please enter a valid date';
};
const router = useRouter();

async function onSubmit() {
  //console.log(modifiedTask);
  try {
    if (modifiedTask.$id) {
      await taskStore.updateTask(modifiedTask);
      console.log('Updated Task: ' + modifiedTask.$id);
    } else {
      await taskStore.addTask(modifiedTask);
      console.log('Created Task');
    }
    router.go(-1);
  } catch (error) {
    console.error('Failed to create new Task: ', error);
  }
}
</script>
