<script setup lang="ts">
/**
 * Linked OAuth account card component.
 *
 * Displays information about a linked OAuth provider (Google or Discord)
 * including the email/username, when it was linked, and an unlink button.
 * The unlink button is disabled if this is the only linked account.
 */
import { computed } from 'vue'

import type { OAuthProvider, LinkedAccount } from '@/composables/useProfile'

const props = defineProps<{
  /** The linked account data */
  account: LinkedAccount
  /** Whether this is the only linked account (cannot unlink) */
  isOnlyAccount: boolean
  /** Whether an unlink operation is in progress */
  isUnlinking: boolean
}>()

const emit = defineEmits<{
  /** Emitted when user clicks unlink button */
  unlink: [provider: OAuthProvider]
}>()

/** Provider display configuration */
const providerConfig = computed(() => {
  const configs = {
    google: {
      name: 'Google',
      icon: '🔵',
      color: 'border-blue-500',
      bgColor: 'bg-blue-500/10',
    },
    discord: {
      name: 'Discord',
      icon: '🟣',
      color: 'border-indigo-500',
      bgColor: 'bg-indigo-500/10',
    },
  }
  return configs[props.account.provider]
})

/** Format the linked date for display */
const linkedDateFormatted = computed(() => {
  const date = new Date(props.account.linkedAt)
  return date.toLocaleDateString(undefined, {
    year: 'numeric',
    month: 'short',
    day: 'numeric',
  })
})

/** Display text (email or provider ID) */
const displayText = computed(() => {
  return props.account.email || `${providerConfig.value.name} Account`
})

function handleUnlink(): void {
  if (!props.isOnlyAccount && !props.isUnlinking) {
    emit('unlink', props.account.provider)
  }
}
</script>

<template>
  <div
    class="flex items-center justify-between p-4 rounded-lg border-l-4"
    :class="[providerConfig.bgColor, providerConfig.color]"
  >
    <!-- Provider info -->
    <div class="flex items-center gap-3">
      <span class="text-2xl">{{ providerConfig.icon }}</span>
      <div>
        <div class="font-medium text-white">
          {{ providerConfig.name }}
        </div>
        <div class="text-sm text-gray-400">
          {{ displayText }}
        </div>
        <div class="text-xs text-gray-500 mt-0.5">
          Linked {{ linkedDateFormatted }}
        </div>
      </div>
    </div>

    <!-- Unlink button -->
    <button
      class="px-3 py-1.5 text-sm rounded transition-colors"
      :class="[
        isOnlyAccount
          ? 'bg-gray-700 text-gray-500 cursor-not-allowed'
          : 'bg-gray-700 text-gray-300 hover:bg-gray-600 hover:text-white'
      ]"
      :disabled="isOnlyAccount || isUnlinking"
      :title="isOnlyAccount ? 'Cannot unlink the only linked account' : 'Unlink this account'"
      @click="handleUnlink"
    >
      <span v-if="isUnlinking">Unlinking...</span>
      <span v-else>Unlink</span>
    </button>
  </div>
</template>
