<template>
  <pn-page-card v-bind="$attrs" @updateScrollPosition="onScroll">
    <template #card-header>
      <pn-action-bar
        v-if="companies.length > 1"
        v-model="search"
        placeholder="chats__search"
        :show-calendar-btn="false"
        :show-filter-btn="false"
        :shadows="isScrolled"
      />
    </template>

    <div
      v-if="companies.length > 2"
      class="w100 flex justify-end q-px-md"
      >
      <q-btn
        @click="maskCompany"
        flat dense no-caps rounded
        class="q-mb-xs"
        >
        <div class="text-caption flex no-wrap items-center q-px-xs text-grey">
          <q-icon class="q-pr-xs" name="mdi-domino-mask" size="xs"/>
          <span>
            {{ $t("companies__mask") }}
          </span>
          
        </div>
      </q-btn>
    </div>

    <q-list v-if="companies.length !== 0">
      <template
        v-for="item in displayCompanies"
        :key="item.id"
        >
        <q-slide-item
          @right="handleSlide($event, item.id)"
          clickable
          v-ripple
          @click="goCompanyInfo(item.id)"
          right-color="red"
          >
          <template #right v-if="item.id !== myCompany?.id">
            <q-icon size="lg" name="mdi-account-multiple-minus-outline"/>
          </template>
          <q-item>
            <q-item-section avatar>
              <pn-auto-avatar
                :img="item.logo"
                :name="item.name"
                type="rounded"
                size="lg"
              />
            </q-item-section>
            <q-item-section>
              <q-item-label lines="1" class="text-caption text-amber-10" v-if="item.id === myCompany?.id">
                <div class="flex items-center">
                  <q-icon name="star" class="q-pr-xs"/>
                  {{ $t('companies__my_company') }}
                </div>
              </q-item-label>
              <q-item-label lines="1" class="text-bold">
                {{ item.name }}
                <q-icon
                  v-if="companiesStore.checkCompanyMasked(item.id)"
                  name="mdi-domino-mask"
                  color="grey"
                  size="sm"
                />
              </q-item-label>
              <q-item-label
                caption lines="2"
                style="max-width: -webkit-fill-available; white-space: pre-line"
                >
                {{ item.description }}
              </q-item-label>
            </q-item-section>
            
            <q-item-section side>
                <div class="flex items-end column">
                  <span class="text-caption flex items-center">
                    <q-icon name="mdi-account-outline" color="grey" />
                    <span>{{ getQtyUsers(item.id) }}</span>
                  </span>
                  <div class="flex items-center row text-caption">
                    <q-icon v-if="item.site" name="mdi-web"/>
                    <q-icon v-if="item.address" name="mdi-map-marker-outline"/>
                    <q-icon v-if="item.phone" name="mdi-phone-outline"/>
                    <q-icon v-if="item.email" name="mdi-email-outline"/>
                  </div>
                </div>
              </q-item-section>
          </q-item>
        </q-slide-item>
      </template>
    </q-list>

    <pn-onboard-btn
      v-if="companies.length <= 1 && companiesInit"
      icon="mdi-account-multiple-plus-outline"
      message1="companies__onboard_msg1"
      message2="companies__onboard_msg2"
      @btn-click="createCompany"
      style="padding-top: 8px"
    />
    <div
      class="column justify-center items-center w100"
      style="position: absolute; bottom: 0;"
      v-if="!companiesInit"
      >
      <q-linear-progress indeterminate />
    </div>
    <template #card-fab>
      <transition
        appear
        enter-active-class="animated zoomIn"
        >
        <pn-glass-btn
          type="fab"
          color="primary"
          >
          <q-btn
            @click="createCompany"
            fab unelevated
            class="shadow-t"
            icon="add"
            color="transparent"
          />
        </pn-glass-btn>
      </transition>
    </template>

    <pn-small-dialog
      v-model="showDialogDeleteCompany"
      icon="mdi-account-multiple-minus-outline"
      color="negative"
      title="companies__dialog_delete_title"
      message1="companies__dialog_delete_message"
      message2="companies__dialog_delete_message2"
      mainBtnLabel="companies__dialog_delete_ok"
      @clickMainBtn="onConfirm()"
      @close="onCancel()"
      @before-hide="onDialogBeforeHide()"
    />
  </pn-page-card>
</template>
    
<script setup lang="ts">
  import { ref, computed } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import { useCompaniesStore } from 'stores/companies'
  import { useUsersStore } from 'stores/users'
  import pnActionBar from 'components/pnActionBar.vue'
  import PnGlassBtn from 'components/pnGlassBtn.vue'
  import type { Company } from 'types/Company'
  
  const router = useRouter()
  const route = useRoute()
  const companiesStore = useCompaniesStore()
  const usersStore = useUsersStore()

  const search = ref('')
  const showDialogDeleteCompany = ref(false)
  const deleteCompanyId = ref<number | undefined>(undefined)
  const currentSlideEvent = ref<SlideEvent | null>(null)
  const closedByUserAction = ref(false)

  interface SlideEvent {
    reset: () => void
  }

  const users = computed(() => usersStore.users)
  const companies = computed(() => companiesStore.companies)
  const companiesInit = computed(() => companiesStore.isInit)

  const myCompany = computed(() => companies.value.find(el => el.is_own))

  const displayCompanies = computed(() => {
    const otherComp = companies.value.filter(el => !el.is_own)
    const c = myCompany.value
      ? [myCompany.value, ...otherComp]
      : otherComp

    return c.filter(searchCompanies)

    function searchCompanies (el: Company) {
      if (!search.value || !(search.value && search.value.trim())) return true
      const searchValue = search.value.trim().toLowerCase()
      return el.name.toLowerCase().includes(searchValue) ||
        el.description && el.description.toLowerCase().includes(searchValue)
    }
  })

  async function maskCompany () {
    await router.push({ name: 'company_mask' })
  }

  async function goCompanyInfo (companyId: number) {
    await router.push({ name: 'company_info', params: { id: route.params.id, companyId }})
  }

  async function createCompany () {
    await router.push({ name: 'add_company' })
  }

  function handleSlide (event: SlideEvent, id: number) {
    currentSlideEvent.value = event
    showDialogDeleteCompany.value = true
    deleteCompanyId.value = id
  }

  function onDialogBeforeHide () {
    if (!closedByUserAction.value) {
      onCancel()
    }
    closedByUserAction.value = false
  }

  async function onConfirm() {
    closedByUserAction.value = true
    if (deleteCompanyId.value) {
      await companiesStore.remove(deleteCompanyId.value)
    }
    currentSlideEvent.value = null
  }

  function onCancel() {
    closedByUserAction.value = true
    if (currentSlideEvent.value) {
      currentSlideEvent.value.reset()
      currentSlideEvent.value = null
    }
  }

  function getQtyUsers (companyId: number) {
    const arr = users.value.filter(el => el.company_id === companyId)
    return arr.length
  }

  const isScrolled = ref(false)
  const onScroll = (pos: number) => {
    isScrolled.value = pos > 1
  }
</script>

<style scoped>
  :deep(.q-slide-item__right) {
    align-self: center;
    height: 98%;
  }

</style>
