<template>
  <p class="my-10 text-center text-gray-300">
    Je zit momenteel niet in een team. Maak een team aan of wacht tot dat je geinvite wordt
  </p>
  <div class="mb-5 flex w-full justify-center gap-10">
    <span
      class="font-bold text-primary hover:cursor-pointer" :class="{ 'underline underline-offset-4': !createTeam.show }"
      @click="createTeam.show = false"
    >
      Team Invites
    </span>
    <span
      class="font-bold text-primary hover:cursor-pointer" :class="{ 'underline underline-offset-4': createTeam.show }"
      @click="createTeam.show = true"
    >
      Create Team
    </span>
  </div>
  <div v-if="!createTeam.show" class="text-center text-gray-300">
    <h2 v-if="!user.teamInvites.length">You don't have any team invites</h2>
    <div v-else class="mx-auto flex max-w-lg flex-col">
      <div v-for="team in filteredTeams" :key="team._id" class="flex items-center rounded bg-neutral-800 px-3 py-1 text-left" @click="acceptInvite(team)">
        <span>
          {{ team.name }}
        </span>
        <Button class="ml-auto">Accept</Button>
      </div>
    </div>
  </div>
  <div v-else class="flex w-full flex-col items-center gap-5">
    <Input v-model="createTeam.name" class="w-full max-w-sm">Naam</Input>
    <Colorpicker v-model="createTeam.color" class="w-full max-w-sm" />
    <Button @click="handleCreateTeam">Create Team</Button>
  </div>
</template>

<script setup>
const user = useState('user')

const teams = await $fetch('/api/team/all')

const filteredTeams = computed(() => {
  return teams.filter(a => user.value.teamInvites.includes(a._id));
})

const createTeam = ref({
  show: false,
  name: '',
  color: '',
})

const acceptInvite = async (team) => {
  try {
    const response = await $fetch('/api/team/acceptinvite', {
      method: 'POST',
      body: { teamId: team._id }
    })
    
    user.value.team =  { id: response._id, admin: false }

    useToast().success('Succesvol lid geworden van het team')
  } catch (e) {
    console.log(e);
    useToast().error(e.statusMessage)
  }
}

const handleCreateTeam = async () => {
  try {
    const response = await $fetch('/api/team/create', {
      method: 'POST',
      body: { teamName: createTeam.value.name, teamColor: createTeam.value.color }
    })
    
    user.value.team =  { id: response.insertedId.toString(), admin: true }

    useToast().success('Succesvol team gemaakt')

  } catch (e) {
    console.log(e);
    useToast().error(e.statusMessage)
  }
}
</script>
