<template>
  <div
    class="ivyforms-settings-google-sheets ivyforms-flex ivyforms-flex-1 ivyforms-flex-direction-column ivyforms-pr-20"
  >
    <div class="ivyforms-settings-google-sheets__option-bar ivyforms-pb-8 ivyforms-flex">
      <div class="ivyforms-settings-google-sheets__option-bar__left ivyforms-flex">
        <span class="ivyforms-settings-google-sheets__title medium-18">{{
          getLabel('google_sheets')
        }}</span>
      </div>
    </div>

    <div
      v-if="isInitialized"
      class="ivyforms-settings-google-sheets__content ivyforms-pt-20 ivyforms-flex ivyforms-flex-direction-column ivyforms-flex-1 ivyforms-gap-24"
    >
      <IvyNotification
        v-if="!isConnected"
        type="stripe"
        state="notes"
        :style="'stripe'"
        :show-button="false"
        :show-title-icon="false"
        :show-description-icon="true"
        :description="getLabel('google_sheets_instruction')"
      />

      <div
        class="ivyforms-settings-google-sheets__card ivyforms-p-24 ivyforms-border-radius-16 ivyforms-flex ivyforms-align-items-center ivyforms-justify-content-space-between"
      >
        <div
          class="ivyforms-settings-google-sheets__card-content ivyforms-flex ivyforms-align-items-center ivyforms-gap-16"
        >
          <div
            class="ivyforms-settings-google-sheets__icon-wrapper ivyforms-flex ivyforms-justify-content-center ivyforms-align-items-center"
          >
            <IvyIcon category="integrations" name="google_sheets" size="l" />
          </div>

          <div class="ivyforms-settings-google-sheets__info">
            <div class="ivyforms-settings-google-sheets__card-title medium-16">
              {{ getLabel('google_sheets') }}
            </div>
            <div class="ivyforms-settings-google-sheets__subtitle regular-14">
              {{ isConnected ? accountEmail : getLabel('google_sheets_sync_description') }}
            </div>
          </div>
        </div>

        <div class="ivyforms-settings-google-sheets__action">
          <IvyButtonAction
            v-if="!isConnected"
            priority="secondary"
            :loading="isConnecting"
            class="ivyforms-settings-google-sheets__action-button"
            @click="handleConnect"
          >
            <template v-if="!isConnecting">{{ getLabel('connect_account') }}</template>
          </IvyButtonAction>

          <IvyButtonAction
            v-else
            priority="secondary"
            type="border"
            :loading="isDisconnecting"
            class="ivyforms-settings-google-sheets__action-button"
            @click="showDisconnectConfirmation = true"
          >
            <template v-if="!isDisconnecting">{{ getLabel('disconnect_account') }}</template>
          </IvyButtonAction>
        </div>
      </div>
    </div>

    <IvyDialog
      v-model="showDisconnectConfirmation"
      class="ivyforms-settings-google-sheets__dialog"
      :show-close="true"
      type="fill"
      align-center
      width="352px"
    >
      <template #header>
        <div
          class="ivyforms-settings-google-sheets__dialog-header-icon ivyforms-mb-16 ivyforms-flex ivyforms-justify-content-center ivyforms-align-items-center"
        >
          <IvyIcon
            name="danger"
            type="fill-duo"
            size="l"
            color="var(--map-accent-amber-symbol-0)"
          />
        </div>
        <div
          class="ivyforms-settings-google-sheets__dialog__header__title-wrapper ivyforms-flex ivyforms-flex-direction-column ivyforms-gap-8"
        >
          <div
            class="ivyforms-settings-google-sheets__dialog__header__title ivyforms-flex ivyforms-justify-content-center ivyforms-align-items-center"
          >
            <span class="medium-14">{{ getLabel('disconnect_account_title') }}</span>
          </div>
        </div>
      </template>
      <template #default>
        <div class="ivyforms-settings-google-sheets__dialog__body__title regular-14">
          {{ getLabel('disconnect_account_subtitle') }}
        </div>
      </template>
      <template #footer>
        <IvyButtonAction
          priority="warning"
          type="fill"
          size="d"
          :loading="isDisconnecting"
          class="ivyforms-settings-google-sheets__dialog-button"
          @click="handleDisconnect"
        >
          {{ getLabel('disconnect') }}
        </IvyButtonAction>
        <IvyButtonAction
          priority="tertiary"
          type="fill"
          size="d"
          @click="showDisconnectConfirmation = false"
        >
          {{ getLabel('cancel') }}
        </IvyButtonAction>
      </template>
    </IvyDialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useLabels } from '@/composables/useLabels'
import IvyMessage from '@/views/_components/message/ivyMessage'
import IvyButtonAction from '@/views/_components/button/IvyButtonAction.vue'
import IvyIcon from '@/views/_components/icon/IvyIcon.vue'
import IvyDialog from '@/views/_components/dialog/IvyDialog.vue'
import IvyNotification from '@/views/_components/notification/IvyNotification.vue'
import { useGoogleSheetsConnection } from '@/integrations/google-sheets/composables/useGoogleSheetsConnection'

const { getLabel } = useLabels()

const {
  isConnected,
  isConnecting,
  isDisconnecting,
  isInitialized,
  accountEmail,
  checkConnectionStatus,
  connectGoogleSheets,
  disconnectGoogleSheets,
  resetConnectUiState,
} = useGoogleSheetsConnection()

const showDisconnectConfirmation = ref(false)

const clearOAuthQueryParams = () => {
  const url = new URL(window.location.href)
  url.searchParams.delete('google_sheets_connected')
  url.searchParams.delete('google_sheets_error')
  window.history.replaceState({}, '', url.toString())
}

const checkOAuthCallback = () => {
  const urlParams = new URLSearchParams(window.location.search)
  const googleSheetsError = urlParams.get('google_sheets_error')
  const googleSheetsConnected = urlParams.get('google_sheets_connected')

  if (googleSheetsError === '1') {
    isConnected.value = false
    resetConnectUiState()
    IvyMessage({
      type: 'error',
      message: getLabel('google_sheets_connection_error'),
    })
    clearOAuthQueryParams()
    return
  }

  if (googleSheetsConnected === '1') {
    isConnected.value = true
    isInitialized.value = true
    IvyMessage({
      type: 'success',
      message: getLabel('google_sheets_connection_success'),
    })
    clearOAuthQueryParams()
  }
}

const handleConnect = async () => {
  resetConnectUiState()

  const { success, errorMessage } = await connectGoogleSheets()

  if (!success) {
    resetConnectUiState()
    IvyMessage({
      type: 'error',
      message: errorMessage || getLabel('google_sheets_connection_error'),
    })
  }
}

const handleDisconnect = async () => {
  await disconnectGoogleSheets()
  showDisconnectConfirmation.value = false
}

onMounted(async () => {
  checkOAuthCallback()
  await checkConnectionStatus()
})
</script>

<style lang="scss">
.ivyforms-settings-google-sheets {
  &__option-bar {
    border-bottom: 1px solid var(--map-divider);
    background: var(--map-ground-level-1-foreground);

    &__left {
      align-items: center;
    }
  }

  &__title,
  &__card-title {
    color: var(--map-base-text-0);
  }

  &__card {
    border: 1px solid var(--map-divider);
    background: var(--map-ground-level-1-foreground);
  }

  &__icon-wrapper {
    background-color: var(--map-base-dusk-o10);
    border-radius: 50%;
    width: 48px;
    height: 48px;
    flex-shrink: 0;
  }

  &__info {
    display: flex;
    flex-direction: column;
    gap: 4px;
  }

  &__subtitle {
    color: var(--map-base-text-1);
  }

  &__card-content {
    flex: 1;
  }

  &__action-button button {
    min-width: 155px;
  }
}

.ivyforms-settings-google-sheets__dialog {
  .ivyforms-dialog {
    .ivyforms-settings-google-sheets__dialog__header__title {
      color: var(--map-base-text-0);
      text-align: center;
    }

    .ivyforms-settings-google-sheets__dialog__body__title {
      color: var(--map-base-text-1);
      text-align: center;
    }

    .el-dialog__body {
      .ivyforms-dialog__body {
        padding: 0 !important;
      }
    }

    .el-dialog__footer {
      border-top: none;
      justify-content: center;
      gap: 8px;
      padding: 16px;
    }
  }

  &-button button {
    min-width: 120px;
  }
}
</style>
