<script setup lang="ts">
import { ref, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useApi } from '@/composables/useApi'
import { useAuthStore } from '@/stores/auth'
import type { AuthResponse } from '@/types'
import Logo from '@/components/ds/brand/Logo.vue'
import Input from '@/components/ds/forms/Input.vue'
import Button from '@/components/ds/core/Button.vue'
import Alert from '@/components/ds/feedback/Alert.vue'

const router = useRouter()
const api = useApi()
const authStore = useAuthStore()

const email = ref('')
const password = ref('')
const loading = ref(false)
const error = ref('')

// TOTP state
const showTotpInput = ref(false)
const totpCode = ref('')
const totpInputEl = ref<HTMLInputElement | null>(null)

async function handleLogin() {
  error.value = ''
  loading.value = true

  try {
    const response = await api.post<AuthResponse>('/auth/login', {
      email: email.value,
      password: password.value,
    })

    if (response.requires_totp) {
      // Credentials verified — server is waiting for the TOTP code.
      // Show the TOTP input and focus it.
      showTotpInput.value = true
      await nextTick()
      totpInputEl.value?.focus()
      return
    }

    authStore.setAuth(response)
    if (response.license) {
      authStore.setLicense(response.license)
    }
    router.push('/')
  } catch (err: unknown) {
    if (err instanceof Error) {
      error.value = err.message
    } else {
      error.value = 'An unexpected error occurred'
    }
  } finally {
    loading.value = false
  }
}

async function handleTotpVerify() {
  if (totpCode.value.length !== 6 || loading.value) return

  error.value = ''
  loading.value = true

  try {
    // Re-POST to /auth/login with the same credentials plus the TOTP code.
    // The backend LoginDto accepts an optional totp_code field and returns full
    // tokens when the code is valid.
    const response = await api.post<AuthResponse>('/auth/login', {
      email: email.value,
      password: password.value,
      totp_code: totpCode.value,
    })

    authStore.setAuth(response)
    if (response.license) {
      authStore.setLicense(response.license)
    }
    router.push('/')
  } catch (err: unknown) {
    totpCode.value = ''
    if (err instanceof Error) {
      error.value = err.message
    } else {
      error.value = 'Invalid authentication code. Please try again.'
    }
    // Keep the TOTP screen visible so the user can retry
  } finally {
    loading.value = false
  }
}

function handleBackToLogin() {
  showTotpInput.value = false
  totpCode.value = ''
  error.value = ''
}
</script>

<template>
  <div class="auth-shell">
    <div class="auth-card">
      <!-- Branding -->
      <div class="auth-brand">
        <div class="auth-brand__mark">
          <Logo :size="40" :glow="true" tagline="by Corrosion" />
        </div>
      </div>

      <!-- Error message -->
      <Alert v-if="error" tone="danger" class="auth-alert">{{ error }}</Alert>

      <!-- Login form -->
      <form v-if="!showTotpInput" class="auth-form" @submit.prevent="handleLogin">
        <Input
          v-model="email"
          id="email"
          label="Email"
          type="email"
          placeholder="admin@example.com"
          autocomplete="email"
          :required="true"
        />

        <Input
          v-model="password"
          id="password"
          label="Password"
          type="password"
          placeholder="Enter your password"
          autocomplete="current-password"
          :required="true"
        />

        <Button
          type="submit"
          :loading="loading"
          :block="true"
          size="md"
        >
          Sign in
        </Button>
      </form>

      <!-- TOTP verification -->
      <div v-else class="auth-form">
        <div class="auth-totp-hint">
          <p class="auth-totp-hint__text">Enter the 6-digit code from your authenticator app.</p>
        </div>

        <div class="auth-totp-field">
          <label class="auth-totp-field__label" for="totp">Authentication code</label>
          <input
            id="totp"
            ref="totpInputEl"
            v-model="totpCode"
            type="text"
            inputmode="numeric"
            autocomplete="one-time-code"
            placeholder="000000"
            maxlength="6"
            class="auth-totp-input"
            @keydown.enter="handleTotpVerify"
          />
        </div>

        <Button
          type="button"
          :loading="loading"
          :disabled="totpCode.length !== 6"
          :block="true"
          size="md"
          @click="handleTotpVerify"
        >
          Verify code
        </Button>

        <button
          type="button"
          :disabled="loading"
          class="auth-back-link"
          @click="handleBackToLogin"
        >
          Back to sign in
        </button>
      </div>

      <!-- Register link -->
      <p v-if="!showTotpInput" class="auth-footer">
        No account?
        <router-link to="/register" class="auth-footer__link">Create one</router-link>
        ·
        <router-link to="/forgot-password" class="auth-footer__link">Forgot password?</router-link>
      </p>
    </div>
  </div>
</template>

<style scoped>
.auth-shell {
  min-height: 100vh;
  background: var(--surface-canvas);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: var(--space-4);
}

.auth-card {
  width: 100%;
  max-width: 400px;
  background: var(--surface-base);
  border-radius: var(--radius-lg);
  box-shadow: var(--ring-default), var(--shadow-lg);
  padding: var(--space-8);
  display: flex;
  flex-direction: column;
  gap: var(--space-5);
}

.auth-brand {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: var(--space-3);
  padding-bottom: var(--space-2);
}

.auth-brand__mark {
  color: var(--accent);
}

.auth-alert {
  /* Alert component handles its own layout */
}

.auth-form {
  display: flex;
  flex-direction: column;
  gap: var(--space-4);
}

/* TOTP hint text */
.auth-totp-hint {
  text-align: center;
}
.auth-totp-hint__text {
  font-size: var(--text-sm);
  color: var(--text-secondary);
  line-height: var(--leading-normal);
  margin: 0;
}

/* TOTP bare input — monospace, centered, large tracking */
.auth-totp-field {
  display: flex;
  flex-direction: column;
  gap: var(--space-1-5);
}
.auth-totp-field__label {
  font-size: var(--text-xs);
  font-weight: 600;
  color: var(--text-secondary);
}
.auth-totp-input {
  width: 100%;
  height: var(--control-h-md);
  padding: 0 var(--space-3);
  background: var(--surface-inset);
  border: none;
  border-radius: var(--radius-md);
  box-shadow: var(--ring-default);
  color: var(--text-primary);
  font-family: var(--font-mono);
  font-size: var(--text-xl);
  font-weight: 600;
  letter-spacing: 0.35em;
  text-align: center;
  outline: none;
  box-sizing: border-box;
  transition: box-shadow 120ms ease;
}
.auth-totp-input:focus {
  box-shadow: inset 0 0 0 1px var(--accent), var(--glow-accent-sm);
}
.auth-totp-input::placeholder {
  color: var(--text-muted);
  letter-spacing: 0.35em;
}

/* Ghost back link */
.auth-back-link {
  background: transparent;
  border: none;
  cursor: pointer;
  font-family: var(--font-sans);
  font-size: var(--text-sm);
  color: var(--text-muted);
  text-align: center;
  padding: 0;
  transition: color 120ms ease;
}
.auth-back-link:hover { color: var(--text-secondary); }
.auth-back-link:disabled { opacity: 0.45; pointer-events: none; }

/* Footer link row */
.auth-footer {
  margin: 0;
  text-align: center;
  font-size: var(--text-sm);
  color: var(--text-muted);
}
.auth-footer__link {
  color: var(--accent-text);
  text-decoration: none;
  font-weight: 600;
  margin-left: 4px;
}
.auth-footer__link:hover { color: var(--accent-hover); }
</style>
