<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { apiGet, apiPost, apiErrorMessage } from "@/api/client";
import { useAuthStore } from "@/stores/auth";
import AppLogo from "@/components/AppLogo.vue";

const route = useRoute();
const router = useRouter();
const authStore = useAuthStore();

const token = computed(() => (route.query.token as string) || "");
const email = ref("");
const username = ref("");
const password = ref("");
const confirmPassword = ref("");
const error = ref("");
const submitting = ref(false);
const validating = ref(true);
const valid = ref(false);

const passwordMismatch = computed(
  () => confirmPassword.value.length > 0 && password.value !== confirmPassword.value
);

const canSubmit = computed(
  () =>
    !submitting.value &&
    !passwordMismatch.value &&
    username.value.trim().length > 0 &&
    password.value.length >= 8 &&
    !!token.value
);

onMounted(async () => {
  if (!token.value) {
    validating.value = false;
    return;
  }
  try {
    const data = await apiGet<{ valid: boolean; email?: string }>(
      `/api/auth/invitation/${token.value}`
    );
    valid.value = data.valid;
    if (data.email) {
      email.value = data.email;
    }
  } catch {
    valid.value = false;
  } finally {
    validating.value = false;
  }
});

async function handleSubmit() {
  if (passwordMismatch.value) {
    error.value = "Passwords do not match";
    return;
  }
  error.value = "";
  submitting.value = true;
  try {
    await apiPost("/api/auth/register-with-invite", {
      token: token.value,
      username: username.value.trim(),
      password: password.value,
    });
    await authStore.checkAuth();
    router.push("/");
  } catch (e: unknown) {
    error.value = apiErrorMessage(e, "Registration failed");
  } finally {
    submitting.value = false;
  }
}
</script>

<template>
  <main class="auth-page">
    <div class="auth-card">
      <div class="auth-brand"><AppLogo :size="32" /><h1>Accept Invitation</h1></div>

      <div v-if="validating" class="auth-loading">Validating invitation...</div>

      <div v-else-if="!token || !valid" class="auth-note">
        <p>This invitation link is invalid or has expired.</p>
        <p class="auth-footer">
          <router-link to="/login">Back to Sign In</router-link>
        </p>
      </div>

      <template v-else>
        <form @submit.prevent="handleSubmit">
          <div class="field">
            <label for="email">Email</label>
            <input
              id="email"
              :value="email"
              type="email"
              class="input"
              disabled
            />
          </div>
          <div class="field">
            <label for="username">Username</label>
            <input
              id="username"
              v-model="username"
              type="text"
              autocomplete="username"
              required
              class="input"
            />
          </div>
          <div class="field">
            <label for="password">Password</label>
            <input
              id="password"
              v-model="password"
              type="password"
              autocomplete="new-password"
              required
              minlength="8"
              class="input"
            />
            <p class="field-hint">Must be at least 8 characters</p>
          </div>
          <div class="field">
            <label for="confirm-password">Confirm Password</label>
            <input
              id="confirm-password"
              v-model="confirmPassword"
              type="password"
              autocomplete="new-password"
              required
              class="input"
              :class="{ 'input-error': passwordMismatch }"
            />
            <p v-if="passwordMismatch" class="error-hint">Passwords do not match</p>
          </div>
          <p v-if="error" class="error-msg">{{ error }}</p>
          <button type="submit" class="btn-primary btn-block" :disabled="!canSubmit">
            {{ submitting ? "Creating Account..." : "Create Account" }}
          </button>
        </form>
      </template>

      <p class="auth-footer">
        <router-link to="/login">Back to Sign In</router-link>
      </p>
    </div>
  </main>
</template>

<style src="@/assets/auth-shared.css" />
