<script setup lang="ts">
import type { Account } from '../../../types'

const { t } = useI18n()
const localePath = useLocalePath()
const { showStatus } = useStatus()

// Fetch connected OAuth accounts
const { data: accountsData, pending, error, refresh } = await useApiFetch<Account[]>('/api/user/accounts', {
  method: 'GET'
})

const accounts = computed<Account[]>(() => {
  const accountsDataValue = accountsData.value
  return Array.isArray(accountsDataValue) ? accountsDataValue : []
})

const { socialProviders } = useSocialProviders()
const connectedProviderIds = computed(() =>
  accounts.value.map((acc: { providerId: string }) => acc.providerId)
)
const unconnectedProviders = computed(() =>
  socialProviders.value.filter(provider => !connectedProviderIds.value.includes(provider))
)

// Modal state
const deletingAccountId = ref<string | null>(null)
const isDeleteModalOpen = ref(false)
const accountToDelete = ref<{ id: string, name: string } | null>(null)

// Delete account with confirmation
const confirmDelete = (accountId: string, providerName: string) => {
  accountToDelete.value = { id: accountId, name: providerName }
  isDeleteModalOpen.value = true
}

const closeDeleteModal = () => {
  isDeleteModalOpen.value = false
  accountToDelete.value = null
}

const deleteAccount = async () => {
  if (!accountToDelete.value) return

  try {
    deletingAccountId.value = accountToDelete.value.id

    const apiCall = useApiCall()
    await apiCall(`/api/user/accounts/${accountToDelete.value.id}`, {
      method: 'DELETE'
    })

    // If we get here, the deletion was successful
    showStatus(t('account.accountDisconnected'), '', 'success')
    await refresh()
    closeDeleteModal()
  } catch (error: unknown) {
    // Check if it's a "last account" error (status 400)
    const is400Error = error && typeof error === 'object' && 'statusCode' in error && error.statusCode === 400
    const errorMessage = is400Error
      ? t('account.cannotDisconnectLast')
      : (error as { message?: string })?.message || t('account.disconnectFailed')

    showStatus(t('account.disconnectFailed'), errorMessage, 'error')
    closeDeleteModal()
  } finally {
    deletingAccountId.value = null
  }
}

// Check if this is the last account (disable delete button)
const isLastAccount = computed(() => accounts.value.length <= 1)
</script>

<template>
  <NuxtLayout
    :page-title="t('account.settings')"
    :parent="{
      label: t('account.title'),
      to: localePath('/dashboard/account')
    }"
    name="dashboard"
    type="account"
  >
    <UPageBody>
      <PageRefresh :on-refresh="refresh" />
      <PageMainCard
        :title="t('account.connectedAccounts')"
        :description="t('account.connectedAccountsDescription')"
        :icon="useSolarIcon('link')"
        :loading="pending"
        :on-refresh="refresh"
      >
        <div
          v-if="pending"
          class="flex justify-center py-7"
        >
          <UIcon
            name="lucide:loader"
            class="animate-spin h-6 w-6 text-muted"
          />
        </div>

        <div
          v-else-if="error"
          class="text-red-500 py-4"
        >
          {{ error?.message }}
        </div>

        <div
          v-else-if="accounts.length === 0"
          class="text-muted py-8 text-center"
        >
          <UIcon
            :name="useSolarIcon('link-broken')"
            class="h-12 w-12 mx-auto mb-3 opacity-50"
          />
          <p>{{ t('account.noConnectedAccounts') }}</p>
        </div>

        <div
          v-else
          class="space-y-3"
        >
          <AccountConnectedAccountCard
            v-for="account in accounts"
            :key="account.id"
            :account="account"
            :is-last-account="isLastAccount"
            :is-deleting="deletingAccountId === account.id"
            @disconnect="confirmDelete"
          />
        </div>
      </PageMainCard>

      <!-- Connect New Account Section -->
      <PageMainCard
        :title="t('account.availableProviders')"
        :description="t('account.connectAccount')"
        :icon="useSolarIcon('link')"
        :show-refresh-button="false"
      >
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <AccountConnectProviderButton
            v-for="provider in unconnectedProviders"
            :key="provider"
            :provider="provider"
          />
          <div v-if="unconnectedProviders.length === 0">
            {{ t('account.noAvailableProviders') }}
          </div>
        </div>
      </PageMainCard>

      <!-- Danger Zone -->
      <div class="mt-4">
        <AccountDangerZone />
      </div>
    </UPageBody>

    <!-- Delete Confirmation Modal -->
    <AccountConfirmationModal
      v-model:open="isDeleteModalOpen"
      :title="t('account.disconnectAccount')"
      :description="t('account.disconnectAccountConfirm')"
      :confirm-label="t('account.disconnect')"
      :cancel-label="t('common.cancel')"
      :is-loading="deletingAccountId === accountToDelete?.id"
      :item-name="accountToDelete?.name"
      @confirm="deleteAccount"
      @cancel="closeDeleteModal"
    />
  </NuxtLayout>
</template>
