<script setup lang="ts">
import Controls from "@/components/Controls.vue";
import EntryTable from "@/components/EntryTable.vue";
import type PocketBase from "pocketbase";
import Button from "primevue/button";
import InputText from "primevue/inputtext";
import Select from "primevue/select";
import Toast from "primevue/toast";
import Toolbar from "primevue/toolbar";
import { useToast } from "primevue/usetoast";
import { inject, onMounted, ref, watch } from "vue";
import type { Organisation, Project } from "./types";

const pb = inject("pb") as PocketBase;

const date = ref(new Date());
const email = ref("");
const failedLogin = ref(false);
const isLogged = ref(pb.authStore.isValid);
const organisation = ref("");
const organisations = ref<Organisation[]>([]);
const password = ref("");
const projects = ref<Project[]>([]);
const toast = useToast();

watch(organisation, async () => {
  await getProjects();
});

onMounted(async () => {
  await getOrganisations();
});

async function login() {
  if (email.value === "" || password.value === "") {
    return;
  }

  try {
    await pb.collection("users").authWithPassword(email.value, password.value);
    failedLogin.value = false;
    isLogged.value = true;
    await getOrganisations();
  } catch (error) {
    pb.authStore.clear();
    failedLogin.value = true;
    isLogged.value = false;
    toast.add({ severity: "error", summary: "Error", detail: "Login failed", life: 3000 });
  }

  email.value = "";
  password.value = "";
}

async function logout() {
  pb.authStore.clear();
  failedLogin.value = false;
  isLogged.value = false;
}

async function getProjects() {
  const filter = pb.filter("organisation = {:organisation}", { organisation: organisation.value });

  const records = await pb.collection<Project>("projects").getFullList(500, {
    filter,
    sort: "name",
  });

  projects.value = [...records];
}

async function getOrganisations() {
  const records = await pb.collection<Organisation>("organisations").getFullList();
  organisations.value = [...records];
  if (organisation.value === "" && records.length > 0) {
    organisation.value = records[0].id;
  }
}

function setDate(newDate: Date) {
  date.value = newDate;
}
</script>

<template>
  <Toast />
  <Toolbar>
    <template #center>
      <template v-if="isLogged">
        <Select
          v-model="organisation"
          :options="organisations"
          optionLabel="name"
          optionValue="id"
          placeholder="Organisation"
        />
        <Controls @date="setDate" :projects="projects" :org="organisation" v-if="organisation !== ''" />
      </template>
    </template>
    <template #end>
      <template v-if="isLogged">
        <Button label="log out" @click="logout" />
      </template>
      <template v-else>
        <InputText type="text" v-model="email" placeholder="email" />
        <InputText type="password" v-model="password" placeholder="password" @keypress.enter="login" />
        <Button label="login" @click="login" />
      </template>
    </template>
  </Toolbar>
  <EntryTable
    :org="organisation"
    :date="date"
    :projects="projects"
    v-if="isLogged && organisation !== ''"
  />
</template>
