<template>
  <p class="mx-auto mb-10 mt-20 max-w-sm text-center">
    Je zit momenteel niet in een team. Maak een team aan of wacht tot dat je geinvite wordt
  </p>
  <div class="mb-8 flex justify-center gap-x-10">
    <div class="text-primary-400 select-none font-bold hover:cursor-pointer " :class="{ 'underline underline-offset-4': !createTeam.show }" @click="createTeam.show = false">
      Team Invites
    </div>
    <div class="text-primary-400 select-none font-bold hover:cursor-pointer" :class="{ 'underline underline-offset-4': createTeam.show }" @click="createTeam.show = true">
      Create Team
    </div>
  </div>
  <div v-if="!createTeam.show" class="mx-auto flex max-w-lg flex-col divide-y divide-gray-500 rounded-lg bg-gray-800 px-5 py-3">
    <div v-for="team in teamInvites" :key="team._id" class="flex w-full items-center py-3">
      {{ team.name }}
      <UButton :disabled="disableButtons" color="red" variant="ghost" class="ml-auto mr-5">Reject</UButton>
      <UButton color="green" @click="acceptInvite(team._id)">Accept</UButton>
    </div>
    <div v-if="!teamInvites[0]" class="p-5">
      There are no team invites
    </div>
  </div>
  <div v-else class="mx-auto flex max-w-lg flex-col gap-y-5 rounded-lg bg-gray-800 p-5">
    <form class="flex flex-col gap-y-5">
      <UFormGroup name="name" label="Name" :error="teamNameError">
        <UInput v-model="createTeam.name" placeholder=" " />
      </UFormGroup>
      <UFormGroup name="color" label="Color" :error="teamColorError">
        <div class="flex">
          <input v-model="createTeam.color" type="color" class="mr-2">
          <UInput v-model="createTeam.color" placeholder=" " class="w-full" />
        </div>
      </UFormGroup>
    </form>
    <UButton class="mx-auto" @click="submitCreateTeam">Create Team</UButton>
  </div>
</template>

<script lang="ts" setup>
const createTeam = ref({
  show: false,
  name: '',
  color: ''
})

const disableButtons = ref(false)

const user = useState<IUser>('user')
const { data: teamInvites } = useFetch('/api/users/@me/teamInvites')

const teamNameError = computed(() => {
  if (!createTeam.value.name) {
    return ''
  }
  if (!/^[a-zA-Z0-9]+$/.test(createTeam.value.name)) {
    return 'Team name must only include alfanumeric characters'
  }
  if (createTeam.value.name.length < 3 || createTeam.value.name.length > 16) {
    return 'Team name must be between 3 and 16 characters'
  }
})

const teamColorError = computed(() => {
  if (!createTeam.value.color) {
    return ''
  }
  if (!/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(createTeam.value.color)) {
    return 'Team color is not a valid hex code'
  }
})

const submitCreateTeam = async () => {
  disableButtons.value = true

  try {
    const response: any = await $fetch('/api/teams', {
      method: 'POST',
      body: {
        name: createTeam.value.name,
        color: createTeam.value.color
      }
    })

    user.value.team = response

    useToast().add({ title: 'Successfully created team', color: 'green' })
  } catch (e: any) {
    console.error(e)

    useToast().add({ title: e.statusMessage, color: 'red' })
  }

  disableButtons.value = false
}

const acceptInvite = async (teamId: string) => {
  disableButtons.value = true

  try {
    const response: any = await $fetch(`/api/teams/${teamId}/members`, {
      method: 'POST',
      body: {
        userId: user.value._id
      }
    })

    user.value.team = response

    useToast().add({ title: 'Successfully joined team', color: 'green' })
  } catch (e: any) {
    console.error(e)

    useToast().add({ title: e.statusMessage, color: 'red' })
  }

  disableButtons.value = false
}
</script>
