<template>
  <LayoutContainer>
    <UiLoadingPanel v-if="pending" />
    <UiForm
      v-else-if="parameters !== null"
      :model="Parameters"
      :entity="parameters"
      action-position="bottom"
    >
      <v-row>
        <v-col cols="12">
          <div class="my-5">
            <span>{{ $t('your_opentalent_website_address_is') }} : </span>
            <strong class="ml-2">
              <a :href="organizationProfile.website ?? '#'" target="_blank">
                {{ organizationProfile.website }}
              </a>
            </strong>
          </div>

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

          <div>
            <UiInputText
              v-model="parameters.otherWebsite"
              field="otherWebsite"
              variant="underlined"
              class="my-4"
            />
          </div>

          <v-divider class="my-10" />

          <div class="mb-6">
            <div>
              <h4>{{ $t('your_subdomains') }} :</h4>
            </div>
            <UiLoadingPanel v-if="subdomainsPending" />
            <div v-else>
              <v-table v-if="subdomains" 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 flex-row justify-center w-100">
                <v-btn
                  :disabled="!canAddNewSubdomain"
                  class="my-5"
                  @click="onAddSubdomainClick"
                >
                  {{ $t('record_a_new_subdomain') }}
                </v-btn>
              </div>
            </div>
          </div>

          <div v-if="!organizationProfile.isCmf">
            <v-divider class="my-10" />

            <div
              v-if="!organizationProfile.isCmf"
              class="my-8 d-flex flex-row justify-center w-100"
            >
              <v-btn
                v-if="!parameters.desactivateOpentalentSiteWeb"
                color="error"
                @click="showWebsiteDeactivationDialog = true"
              >
                {{ $t('deactivateOpentalentSiteWeb') }}
              </v-btn>
              <v-btn v-else color="primary" @click="reactivateWebsite">
                {{ $t('reactivateOpentalentSiteWeb') }}
              </v-btn>

              <LazyLayoutDialog :show="showWebsiteDeactivationDialog">
                <template #dialogTitle>
                  {{ $t('please_confirm') }}
                </template>
                <template #dialogText>
                  <v-col>
                    <div>
                      {{
                        $t(
                          'yourOpentalentWebsiteWillBeDeactivatedOnceYouLlHaveSaved',
                        )
                      }}.
                    </div>
                    <span>{{ $t('doYouWantToContinue') }} ?</span>
                  </v-col>
                </template>
                <template #dialogBtn>
                  <v-btn
                    class="theme-neutral-soft mr-4"
                    @click="showWebsiteDeactivationDialog = false"
                  >
                    {{ $t('cancel') }}
                  </v-btn>

                  <v-btn class="theme-primary" @click="onDialogYesBtnClick">
                    {{ $t('yes') }}
                  </v-btn>
                </template>
              </LazyLayoutDialog>
            </div>
          </div>
        </v-col>
      </v-row>
    </UiForm>
  </LayoutContainer>
</template>

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

const { fetch, fetchCollection } = useEntityFetch()

const organizationProfile = useOrganizationProfileStore()

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

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

const { data: subdomains, pending: subdomainsPending } = fetchCollection(
  Subdomain,
  null,
  ref({ organization: organizationProfile.id }),
)

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

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

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

const showWebsiteDeactivationDialog: Ref<boolean> = ref(false)

const deactivateWebsite = () => {
  parameters.value!.desactivateOpentalentSiteWeb = true
}

const reactivateWebsite = () => {
  parameters.value!.desactivateOpentalentSiteWeb = false
}

const onDialogYesBtnClick = () => {
  showWebsiteDeactivationDialog.value = false
  deactivateWebsite()
}
</script>

<style scoped lang="scss">
.subdomains-table {
  max-width: 450px;
}

.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-left: solid 2px rgb(var(--v-theme-neutral));
}

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