<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useAuthStore } from '@/stores/auth'
import type { ApiToken } from '@/types'
import Button from '@/components/common/Button.vue'
import Modal from '@/components/common/Modal.vue'
import TokenManager from '@/components/common/TokenManager.vue'

const authStore = useAuthStore()

const tokens = ref<ApiToken[]>([])
const loading = ref(true)
const showCreateModal = ref(false)
const showRevokeModal = ref(false)
const tokenToRevoke = ref<ApiToken | null>(null)
const revoking = ref(false)
const toastMessage = ref('')
const showToast = ref(false)

onMounted(async () => {
  await fetchTokens()
})

async function fetchTokens() {
  loading.value = true
  try {
    tokens.value = await authStore.fetchTokens()
  } catch (e) {
    console.error('Failed to fetch tokens:', e)
  } finally {
    loading.value = false
  }
}

function confirmRevoke(token: ApiToken) {
  tokenToRevoke.value = token
  showRevokeModal.value = true
}

async function revokeToken() {
  if (!tokenToRevoke.value) return

  revoking.value = true
  try {
    await authStore.revokeToken(tokenToRevoke.value.id)
    tokens.value = tokens.value.filter(t => t.id !== tokenToRevoke.value!.id)
    showRevokeModal.value = false
    tokenToRevoke.value = null
    showToastMessage('Token revoked successfully')
  } catch (e) {
    console.error('Failed to revoke token:', e)
  } finally {
    revoking.value = false
  }
}

function showToastMessage(message: string) {
  toastMessage.value = message
  showToast.value = true
  setTimeout(() => {
    showToast.value = false
  }, 3000)
}

function formatDate(dateString: string) {
  const date = new Date(dateString)
  return date.toLocaleDateString('en-US', {
    month: 'short',
    day: 'numeric',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  })
}

function getRoleBadgeClass(role: string) {
  switch (role) {
    case 'researcher':
      return 'badge--blue'
    case 'developer':
      return 'badge--green'
    case 'viewer':
      return 'badge--gray'
    default:
      return ''
  }
}
</script>

<template>
  <div class="settings-tokens">
    <div class="settings-tokens__header">
      <div>
        <h1 class="settings-tokens__title">API Tokens</h1>
        <p class="settings-tokens__subtitle">
          Manage your personal API tokens for programmatic access
        </p>
      </div>
      <Button variant="primary" @click="showCreateModal = true">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <line x1="12" y1="5" x2="12" y2="19"/>
          <line x1="5" y1="12" x2="19" y2="12"/>
        </svg>
        Create Token
      </Button>
    </div>

    <!-- Loading State -->
    <div v-if="loading" class="settings-tokens__loading">
      <div class="settings-tokens__spinner"></div>
      <p>Loading tokens...</p>
    </div>

    <!-- Empty State -->
    <div v-else-if="tokens.length === 0" class="settings-tokens__empty">
      <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
        <path d="M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"/>
      </svg>
      <h2>No API tokens yet</h2>
      <p>Create your first API token to access Claudia Docs programmatically</p>
      <Button variant="primary" @click="showCreateModal = true">
        Create Your First Token
      </Button>
    </div>

    <!-- Tokens Table -->
    <div v-else class="settings-tokens__table-wrapper">
      <table class="settings-tokens__table">
        <thead>
          <tr>
            <th>Name</th>
            <th>Role</th>
            <th>Created</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="token in tokens" :key="token.id">
            <td class="token-name">{{ token.name }}</td>
            <td>
              <span :class="['badge', getRoleBadgeClass(token.role)]">
                {{ token.role }}
              </span>
            </td>
            <td class="token-date">{{ formatDate(token.created_at) }}</td>
            <td>
              <button class="revoke-btn" @click="confirmRevoke(token)">
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                  <polyline points="3 6 5 6 21 6"/>
                  <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
                </svg>
                Revoke
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- Create Token Modal -->
    <TokenManager
      :show="showCreateModal"
      @close="showCreateModal = false"
      @tokens-changed="fetchTokens"
    />

    <!-- Revoke Confirmation Modal -->
    <Modal :show="showRevokeModal" title="Revoke API Token" size="sm" @close="showRevokeModal = false">
      <p class="revoke-confirm__text">
        Are you sure you want to revoke the token <strong>"{{ tokenToRevoke?.name }}"</strong>?
        This action cannot be undone and any applications using this token will lose access.
      </p>
      <template #footer>
        <Button variant="secondary" @click="showRevokeModal = false">Cancel</Button>
        <Button variant="danger" :loading="revoking" @click="revokeToken">Revoke Token</Button>
      </template>
    </Modal>

    <!-- Toast -->
    <Transition name="toast">
      <div v-if="showToast" class="toast">
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <polyline points="20 6 9 17 4 12"/>
        </svg>
        {{ toastMessage }}
      </div>
    </Transition>
  </div>
</template>

<style scoped>
.settings-tokens {
  max-width: 900px;
  margin: 0 auto;
  padding: 2rem;
}

.settings-tokens__header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 2rem;
}

.settings-tokens__title {
  margin: 0;
  font-size: 1.75rem;
  font-weight: 600;
  color: var(--text-primary);
}

.settings-tokens__subtitle {
  margin: 0.25rem 0 0;
  font-size: 0.9375rem;
  color: var(--text-secondary);
}

.settings-tokens__loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 1rem;
  padding: 4rem;
  color: var(--text-secondary);
}

.settings-tokens__spinner {
  width: 32px;
  height: 32px;
  border: 3px solid var(--border);
  border-top-color: var(--accent);
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.settings-tokens__empty {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 1rem;
  padding: 4rem 2rem;
  text-align: center;
  color: var(--text-secondary);
  background: var(--bg-secondary);
  border: 1px dashed var(--border);
  border-radius: 12px;
}

.settings-tokens__empty h2 {
  margin: 0;
  font-size: 1.25rem;
  color: var(--text-primary);
}

.settings-tokens__empty p {
  margin: 0;
  max-width: 320px;
}

.settings-tokens__table-wrapper {
  background: var(--bg-primary);
  border: 1px solid var(--border);
  border-radius: 12px;
  overflow: hidden;
}

.settings-tokens__table {
  width: 100%;
  border-collapse: collapse;
}

.settings-tokens__table th,
.settings-tokens__table td {
  padding: 1rem 1.25rem;
  text-align: left;
}

.settings-tokens__table th {
  font-size: 0.75rem;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  color: var(--text-secondary);
  background: var(--bg-secondary);
  border-bottom: 1px solid var(--border);
}

.settings-tokens__table td {
  font-size: 0.9375rem;
  color: var(--text-primary);
  border-bottom: 1px solid var(--border);
}

.settings-tokens__table tbody tr:last-child td {
  border-bottom: none;
}

.settings-tokens__table tbody tr:hover {
  background: var(--bg-secondary);
}

.token-name {
  font-weight: 500;
}

.token-date {
  color: var(--text-secondary);
  font-size: 0.875rem;
}

/* Badge Styles */
.badge {
  display: inline-block;
  padding: 0.25rem 0.625rem;
  border-radius: 9999px;
  font-size: 0.75rem;
  font-weight: 500;
  text-transform: capitalize;
}

.badge--blue {
  background: #dbeafe;
  color: #1d4ed8;
}

.badge--green {
  background: #dcfce7;
  color: #16a34a;
}

.badge--gray {
  background: var(--bg-tertiary);
  color: var(--text-secondary);
}

/* Revoke Button */
.revoke-btn {
  display: inline-flex;
  align-items: center;
  gap: 0.375rem;
  padding: 0.375rem 0.75rem;
  background: none;
  border: 1px solid var(--border);
  border-radius: 6px;
  font-size: 0.8125rem;
  font-family: inherit;
  color: var(--text-secondary);
  cursor: pointer;
  transition: all 0.15s;
}

.revoke-btn:hover {
  background: #fef2f2;
  border-color: #ef4444;
  color: #ef4444;
}

/* Revoke Confirmation */
.revoke-confirm__text {
  margin: 0;
  font-size: 0.9375rem;
  line-height: 1.6;
  color: var(--text-primary);
}

.revoke-confirm__text strong {
  font-weight: 600;
}

/* Toast */
.toast {
  position: fixed;
  bottom: 2rem;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.875rem 1.25rem;
  background: var(--text-primary);
  color: var(--bg-primary);
  border-radius: 8px;
  font-size: 0.875rem;
  font-weight: 500;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  z-index: 1000;
}

.toast svg {
  color: #22c55e;
}

.toast-enter-active,
.toast-leave-active {
  transition: opacity 0.2s, transform 0.2s;
}

.toast-enter-from,
.toast-leave-to {
  opacity: 0;
  transform: translateX(-50%) translateY(10px);
}
</style>
