<template>
  <LayoutContainer>
    <LayoutCommonSection>
      <h4 class="flex-grow-1 align-self-center">
        {{ $t('your_website') }}
      </h4>

      <UiLoadingPanel v-if="status == 'pending'" />
      <UiForm
        v-else-if="parameters !== null"
        v-model="parameters"
        :model="Parameters"
      >
        <div class="section-header">
          <div class="flex-grow-1">
            <span>{{ $t('your_website_address_is') }} : </span>
            <strong class="ml-2">
              <a :href="organizationProfile.website ?? '#'" target="_blank">
                {{ organizationProfile.website }}
              </a>
            </strong>
          </div>
        </div>

        <div v-if="!organizationProfile.isCmf" class="d-flex justify-left mt-6">
          <LayoutParametersWebsiteActivationSwitch
            :model-value="!parameters.desactivateOpentalentSiteWeb"
            @update:model-value="
              parameters.desactivateOpentalentSiteWeb =
                !parameters.desactivateOpentalentSiteWeb
            "
          />
        </div>

        <!-- les publicationDirectors sont des entités Access -->
        <UiInputAutocompleteAccesses
          v-if="!parameters.desactivateOpentalentSiteWeb"
          v-model="parameters.publicationDirectors"
          field="publicationDirectors"
          multiple
          chips
          class="my-4"
        />

        <UiInputText
          v-model="parameters.website"
          field="website"
          label="otherWebsite"
          class="my-4"
        />
      </UiForm>
    </LayoutCommonSection>

    <LayoutCommonSection v-if="!parameters.desactivateOpentalentSiteWeb">
      <div class="section-header">
        <h4 class="flex-grow-1">
          {{ $t('your_subdomains') }}
        </h4>
      </div>

      <UiLoadingPanel v-if="subdomainsStatus == 'pending'" />
      <div v-else>
        <v-table v-if="subdomains!.items" class="subdomains-table my-2">
          <tbody>
            <tr
              v-for="subdomain in subdomains!.items"
              :key="subdomain.id"
              :title="subdomain.subdomain"
              :class="'subdomainItem' + (subdomain.active ? ' active' : '')"
              @click="goToEditPage(subdomain.id)"
            >
              <td>{{ subdomain.subdomain }}</td>
              <td>
                <span v-if="subdomain.active">
                  <v-icon class="text-success icon"> fa-solid fa-check </v-icon>
                  {{ $t('active') }}
                </span>
              </td>
            </tr>
          </tbody>
        </v-table>
        <span v-else>{{ $t('no_recorded_subdomain') }}</span>

        <div class="d-flex justify-center">
          <v-btn
            :disabled="!canAddNewSubdomain"
            prepend-icon="fa-solid fa-plus"
            class="my-5"
            @click="onAddSubdomainClick"
          >
            {{
              smAndUp
                ? $t('record_a_new_subdomain')
                : $t('record_a_new_subdomain_short')
            }}
          </v-btn>
        </div>

        <div class="explanation flex-column">
          <div class="d-flex flex-row">
            <div class="px-4 d-flex flex-row align-center justify-center py-2">
              <v-icon class="theme-info">fa fa-info</v-icon>
            </div>
            <div
              class="px-2 d-flex flex-row align-center justify-left flex-grow-1"
            >
              {{ $t('a_short_subdomains_definition') }}
            </div>
            <v-img
              src="/images/help/what_is_a_subdomain.png"
              width="180px"
              max-width="180px"
              class="align-self-center mr-4"
            />
          </div>
        </div>
      </div>
    </LayoutCommonSection>
  </LayoutContainer>
</template>

<script setup lang="ts">
import type { AsyncData } from '#app'
import type { ComputedRef, Ref } from 'vue'
import { useDisplay } from 'vuetify'
import { useOrganizationProfileStore } from '~/stores/organizationProfile'
import Parameters from '~/models/Organization/Parameters'
import { useEntityFetch } from '~/composables/data/useEntityFetch'
import Subdomain from '~/models/Organization/Subdomain'
import type ApiResource from '~/models/ApiResource'
import EqualFilter from '~/services/data/Filters/EqualFilter'
import Query from '~/services/data/Query'

definePageMeta({
  name: 'parameters_website_page',
})

const { fetch, fetchCollection } = useEntityFetch()

const organizationProfile = useOrganizationProfileStore()

const { smAndUp } = useDisplay()

if (organizationProfile.parametersId === null) {
  throw new Error('Missing organization parameters id')
}

const { data: parameters, status } = fetch(
  Parameters,
  organizationProfile.parametersId,
) as AsyncData<ApiResource | null, Error | null>

const query = new Query(new EqualFilter('organization', organizationProfile.id))

const { data: subdomains, status: subdomainsStatus } = fetchCollection(
  Subdomain,
  null,
  query,
)

const canAddNewSubdomain: ComputedRef<boolean> = computed(
  () => subdomains.value !== null && subdomains.value.items.length < 3,
)

const goToEditPage = (id: number) => {
  navigateTo(`/parameters/subdomains/${id}`)
}

const onAddSubdomainClick = () => {
  if (!canAddNewSubdomain.value) {
    throw new Error('Max number of subdomains reached')
  }
  navigateTo('/parameters/subdomains/new')
}

onUnmounted(() => {
  useRepo(Parameters).flush()
  useRepo(Subdomain).flush()
})
</script>

<style scoped lang="scss">
.section-header {
  margin: 12px 0 36px 0;
  display: flex;
  flex-direction: column;

  .v-img {
    max-width: 240px;
  }

  @media (max-width: 600px) {
    :deep(.v-btn) {
      height: auto;
      margin: 15px 0;
      white-space: normal;
    }
  }
}

.subdomainItem {
  cursor: pointer;
  border: solid 1px rgb(var(--v-theme-neutral-strong));
}

.subdomainItem:hover {
  background: rgb(var(--v-theme-neutral));
}
.subdomainItem .icon {
  font-size: 12px;
}

.subdomainItem td:first-child {
  border-top: solid 1px rgb(var(--v-theme-neutral));
  border-bottom: solid 1px rgb(var(--v-theme-neutral));
  border-left: solid 2px rgb(var(--v-theme-neutral));
}

.subdomainItem td:last-child {
  border-top: solid 1px rgb(var(--v-theme-neutral));
  border-bottom: solid 1px rgb(var(--v-theme-neutral));
  border-right: solid 1px rgb(var(--v-theme-neutral));
}

.subdomainItem.active td:first-child {
  border-left: solid 2px rgb(var(--v-theme-primary));
}
</style>
