<template>
  <div class="min-h-screen bg-gray-50 flex flex-col justify-center py-12 sm:px-6 lg:px-8">
    <div class="sm:mx-auto sm:w-full sm:max-w-md">
      <h2 class="mt-6 text-center text-3xl font-extrabold text-gray-900">Create New Account</h2>
      <p class="mt-2 text-center text-sm text-gray-600">
        Already have an account?
        <router-link to="/login" class="font-medium text-green-600 hover:text-green-500">Login Now</router-link>
      </p>
    </div>

    <div class="mt-8 sm:mx-auto sm:w-full sm:max-w-md">
      <div class="bg-white py-8 px-4 shadow sm:rounded-lg sm:px-10">
        <form @submit.prevent="register" class="space-y-6">
          <div>
            <label for="username" class="block text-sm font-medium text-gray-700">Username</label>
            <div class="mt-1">
              <input
                v-model="username"
                id="username"
                name="username"
                type="text"
                required
                class="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-green-500 focus:border-green-500"
              />
            </div>
          </div>

          <div>
            <label for="email" class="block text-sm font-medium text-gray-700">Email</label>
            <div class="mt-1">
              <input
                v-model="email"
                id="email"
                name="email"
                type="email"
                required
                class="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-green-500 focus:border-green-500"
              />
            </div>
          </div>

          <div>
            <label for="password" class="block text-sm font-medium text-gray-700">Password</label>
            <div class="mt-1">
              <input
                v-model="password"
                id="password"
                name="password"
                type="password"
                required
                minlength="8"
                class="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-green-500 focus:border-green-500"
              />
              <p class="mt-1 text-sm text-gray-500">Password must be at least 8 characters long</p>
            </div>
          </div>

          <div>
            <label for="confirmPassword" class="block text-sm font-medium text-gray-700">Confirm Password</label>
            <div class="mt-1">
              <input
                v-model="confirmPassword"
                id="confirmPassword"
                name="confirmPassword"
                type="password"
                required
                class="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-green-500 focus:border-green-500"
              />
            </div>
          </div>

          <div class="flex items-center">
            <input
              id="agree-terms"
              name="agree-terms"
              type="checkbox"
              v-model="agreeTerms"
              required
              class="h-4 w-4 text-green-600 focus:ring-green-500 border-gray-300 rounded"
            />
            <label for="agree-terms" class="ml-2 block text-sm text-gray-900">
              I agree to the
              <a href="#" class="font-medium text-green-600 hover:text-green-500">Terms of Service</a>
              and
              <a href="#" class="font-medium text-green-600 hover:text-green-500">Privacy Policy</a>
            </label>
          </div>

          <div>
            <button
              type="submit"
              class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-green-600 hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500"
            >
              Register
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useToast } from '../composables/useToast'

const router = useRouter()
const { showToast } = useToast()
const email = ref('')
const password = ref('')
const confirmPassword = ref('')
const username = ref('')
const agreeTerms = ref(false)

const register = async () => {
  try {
    if (password.value !== confirmPassword.value) {
      showToast('Passwords do not match', 'error')
      return
    }

    if (!agreeTerms.value) {
      showToast('Please agree to the Terms of Service and Privacy Policy', 'error')
      return
    }

    const response = await fetch('https://domaintestaccount.store/api/v1/auth/register', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email: email.value,
        password: password.value,
        username: username.value,
      }),
    });

    if (!response.ok) {
      const error = await response.json();
      if (error.detail && Array.isArray(error.detail)) {
        // 处理验证错误
        const errorMessages = error.detail.map(err => {
          // 获取字段名
          const field = err.loc[err.loc.length - 1];
          
          // 根据不同的错误类型返回友好的错误消息
          switch (err.type) {
            case 'value_error.any_str.min_length':
              return `${field} must be at least ${err.ctx.limit_value} characters long`;
            case 'value_error.email':
              return 'Please enter a valid email address';
            case 'value_error.missing':
              return `${field} is required`;
            default:
              return err.msg;
          }
        });
        showToast(errorMessages.join('\n'), 'error');
      } else {
        // 处理其他类型的错误
        showToast(error.detail || 'Registration failed. Please try again.', 'error');
      }
      return;
    }

    showToast('Registration successful! Please login.', 'success');
    // 注册成功后跳转到登录页
    router.push('/login')
  } catch (error) {
    console.error('Registration failed:', error)
    showToast('An error occurred during registration. Please try again.', 'error');
  }
}
</script>
