<script setup>

import dayjs from "dayjs";

const props = defineProps({
  queryStringData: {
    type: String
  },
  item: {
    type: Object,
    required: true
  },
  topLevelType: {
    type: String,
    required: true
  },
  platform: {
    type: String,
    required: true
  }
})

const emit = defineEmits(["updateNeeded"]);

const router = useRouter()
const profileStore = useProfileStore()
const supabase = useSupabaseClient()

const renderedPhases = computed(() => {
  if(props.topLevelType === "projects" && props.item.phases) {
    return props.item.phases.map((phase,index,array) => {

      let isAvailable = false

      if(phase.active) {
        isAvailable = true
      } else if(index > 0 && array[index-1].active ){
        isAvailable = true
      } else if(index > 1 && array[index-1].optional && array[index-2].active){
        isAvailable = true
      } else if(array.findIndex(i => i.active) > index) {
        isAvailable = true
      } else if(phase.label === "Abgeschlossen") {
        isAvailable = true
      }


      return {
        ...phase,
        label: phase.optional ? `${phase.label}(optional)`: phase.label,
        disabled: !isAvailable,
        defaultOpen: phase.active ? true : false
      }
    })
  } else {
    return []
  }
})

const changeActivePhase = async (key) => {
  let item = await useSupabaseSelectSingle("projects",props.item.id,'*')

  let phaseLabel = ""

  item.phases = item.phases.map(p => {
    if(p.active) p.active = false

    if(p.key === key) {
      p.active = true
      p.activated_at = dayjs().format()
      p.activated_by = profileStore.activeProfile.id
      phaseLabel = p.label
    }

    return p
  })

  const {error:updateError} = await supabase.from("projects").update({phases: item.phases}).eq("id",item.id)



  const {error} = await supabase.from("historyitems").insert({
    createdBy: profileStore.activeProfile.id,
    tenant: profileStore.currentTenant,
    text: `Aktive Phase zu "${phaseLabel}" gewechselt`,
    project: item.id
  })

  emit("updateNeeded")

}


</script>

<template>
  <UCard class="mt-5 scroll" :style="props.platform !== 'mobile' ? 'height: 80vh' : ''">
    <template #header v-if="props.platform === 'mobile'">
      <span>Phasen</span>
    </template>
    <UAccordion
        :items="renderedPhases"
    >
      <template #default="{item,index,open}">
        <UButton
            variant="ghost"
            :color="item.active ? 'primary' : 'white'"
            class="mb-1"
            :disabled="true"
        >
          <template #leading>
            <div class="w-6 h-6  flex items-center justify-center -my-1">
              <UIcon :name="item.icon" class="w-4 h-4 " />
            </div>
          </template>

          <span class="truncate"> {{item.label}}</span>

          <template #trailing>
            <UIcon
                name="i-heroicons-chevron-right-20-solid"
                class="w-5 h-5 ms-auto transform transition-transform duration-200"
                :class="[open && 'rotate-90']"
            />
          </template>

        </UButton>
      </template>
      <template #item="{item, index}">
        <UCard class="mx-5">
          <template #header>
            <span class="dark:text-white text-black">{{item.label}}</span>
          </template>
          <InputGroup>
            <!-- TODO: Reactive Change Phase                  -->
            <UButton
                v-if="!item.activated_at && index !== 0 "
                @click="changeActivePhase(item.key)"
            >
              Phase aktivieren
            </UButton>
            <UButton
                v-if="item.active"
                v-for="button in item.quickactions"
                @click="router.push(`${button.link}&${props.queryStringData}`)"
            >
              {{button.label}}
            </UButton>
          </InputGroup>

          <div>
            <p v-if="item.activated_at" class="dark:text-white text-black">Aktiviert am: {{dayjs(item.activated_at).format("DD.MM.YY HH:mm")}} Uhr</p>
            <p v-if="item.activated_by" class="dark:text-white text-black">Aktiviert durch: {{profileStore.getProfileById(item.activated_by).fullName}}</p>
            <p v-if="item.description" class="dark:text-white text-black">Beschreibung: {{item.description}}</p>
          </div>
        </UCard>


      </template>
    </UAccordion>
  </UCard>

</template>

<style scoped>

</style>