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

interface Props {
  show: boolean
}

defineProps<Props>()

const emit = defineEmits<{
  close: []
  tokensChanged: []
}>()

const authStore = useAuthStore()

const step = ref<'form' | 'result'>('form')
const tokenName = ref('')
const tokenRole = ref<TokenRole>('viewer')
const creating = ref(false)
const generatedToken = ref<ApiTokenGenerateResponse | null>(null)
const copied = ref(false)
const error = ref('')

const roles: { value: TokenRole; label: string }[] = [
  { value: 'researcher', label: 'Researcher' },
  { value: 'developer', label: 'Developer' },
  { value: 'viewer', label: 'Viewer' }
]

function reset() {
  step.value = 'form'
  tokenName.value = ''
  tokenRole.value = 'viewer'
  creating.value = false
  generatedToken.value = null
  copied.value = false
  error.value = ''
}

function handleClose() {
  reset()
  emit('close')
}

async function createToken() {
  if (!tokenName.value.trim()) {
    error.value = 'Token name is required'
    return
  }

  creating.value = true
  error.value = ''

  try {
    generatedToken.value = await authStore.generateToken({
      name: tokenName.value.trim(),
      role: tokenRole.value
    })
    step.value = 'result'
    emit('tokensChanged')
  } catch (e: unknown) {
    error.value = e instanceof Error ? e.message : 'Failed to create token'
  } finally {
    creating.value = false
  }
}

async function copyToken() {
  if (!generatedToken.value) return

  try {
    await navigator.clipboard.writeText(generatedToken.value.token)
    copied.value = true
    setTimeout(() => {
      copied.value = false
    }, 2000)
  } catch {
    // Fallback for older browsers
    const textarea = document.createElement('textarea')
    textarea.value = generatedToken.value.token
    document.body.appendChild(textarea)
    textarea.select()
    document.execCommand('copy')
    document.body.removeChild(textarea)
    copied.value = true
    setTimeout(() => {
      copied.value = false
    }, 2000)
  }
}
</script>

<template>
  <Modal :show="show" title="Create API Token" size="sm" @close="handleClose">
    <!-- Form Step -->
    <form v-if="step === 'form'" @submit.prevent="createToken">
      <div class="form__field">
        <label for="token-name" class="form__label">Token Name</label>
        <input
          id="token-name"
          v-model="tokenName"
          type="text"
          class="form__input"
          placeholder="e.g., Production API Key"
          autofocus
        />
      </div>

      <div class="form__field">
        <label for="token-role" class="form__label">Role</label>
        <select id="token-role" v-model="tokenRole" class="form__select">
          <option v-for="role in roles" :key="role.value" :value="role.value">
            {{ role.label }}
          </option>
        </select>
      </div>

      <p v-if="error" class="form__error">{{ error }}</p>
    </form>

    <!-- Result Step -->
    <div v-else-if="step === 'result' && generatedToken" class="token-result">
      <div class="token-result__warning">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>
          <line x1="12" y1="9" x2="12" y2="13"/>
          <line x1="12" y1="17" x2="12.01" y2="17"/>
        </svg>
        <p>Make sure to copy your token now. <strong>You won't be able to see it again!</strong></p>
      </div>

      <div class="token-result__field">
        <label class="form__label">Your API Token</label>
        <div class="token-result__token">
          <code>{{ generatedToken.token }}</code>
          <button class="token-result__copy" @click="copyToken" type="button">
            <svg v-if="!copied" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>
              <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
            </svg>
            <svg v-else 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>
            {{ copied ? 'Copied!' : 'Copy' }}
          </button>
        </div>
      </div>
    </div>

    <template #footer>
      <Button v-if="step === 'form'" variant="secondary" @click="handleClose">Cancel</Button>
      <Button v-if="step === 'form'" variant="primary" :loading="creating" @click="createToken">
        Generate Token
      </Button>
      <Button v-else variant="primary" @click="handleClose">Done</Button>
    </template>
  </Modal>
</template>

<style scoped>
.form__field {
  margin-bottom: 1.25rem;
}

.form__field:last-child {
  margin-bottom: 0;
}

.form__label {
  display: block;
  margin-bottom: 0.5rem;
  font-size: 0.875rem;
  font-weight: 500;
  color: var(--text-primary);
}

.form__input,
.form__select {
  width: 100%;
  padding: 0.75rem 1rem;
  background: var(--bg-secondary);
  border: 1px solid var(--border);
  border-radius: 8px;
  font-size: 0.9375rem;
  font-family: inherit;
  color: var(--text-primary);
  outline: none;
  transition: border-color 0.15s, box-shadow 0.15s;
  box-sizing: border-box;
}

.form__input::placeholder {
  color: var(--text-secondary);
}

.form__input:focus,
.form__select:focus {
  border-color: var(--accent);
  box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
}

.form__select {
  cursor: pointer;
}

.form__error {
  margin: 0.5rem 0 0;
  font-size: 0.875rem;
  color: #ef4444;
}

/* Token Result Styles */
.token-result__warning {
  display: flex;
  gap: 0.75rem;
  padding: 0.875rem 1rem;
  background: #fef3c7;
  border: 1px solid #f59e0b;
  border-radius: 8px;
  margin-bottom: 1.25rem;
  color: #92400e;
}

.token-result__warning svg {
  flex-shrink: 0;
  margin-top: 0.125rem;
}

.token-result__warning p {
  margin: 0;
  font-size: 0.875rem;
  line-height: 1.4;
}

.token-result__warning strong {
  font-weight: 600;
}

.token-result__field {
  margin-bottom: 0;
}

.token-result__token {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.75rem 1rem;
  background: var(--bg-secondary);
  border: 1px solid var(--border);
  border-radius: 8px;
}

.token-result__token code {
  flex: 1;
  font-family: 'Fira Code', 'Consolas', monospace;
  font-size: 0.8125rem;
  color: var(--text-primary);
  word-break: break-all;
}

.token-result__copy {
  flex-shrink: 0;
  display: flex;
  align-items: center;
  gap: 0.375rem;
  padding: 0.5rem 0.75rem;
  background: var(--bg-tertiary);
  border: 1px solid var(--border);
  border-radius: 6px;
  font-size: 0.8125rem;
  font-family: inherit;
  color: var(--text-primary);
  cursor: pointer;
  transition: all 0.15s;
}

.token-result__copy:hover {
  background: var(--accent);
  border-color: var(--accent);
  color: white;
}
</style>
