<template>
  <!-- Form side -->
  <div class="container">
    <div class="row">
      <div class="col-md-10 offset-md-1 col-lg-10 offset-lg-1 col-xl-6 offset-xl-3 nm-st nm-st-md">
        <form @submit.prevent="handleSignup">
          <div class="nm-mb-2 nm-mb-md-2">
            <h2>Create your free account now!</h2>
            <p>Already have an account? <router-link to="/login" class="nm-fs-1 nm-fw-bd underline">Log In</router-link></p>
          </div>
          
          <div class="input-group nm-gp">
            <span class="nm-gp-pp"><i class="fas fa-user"></i></span>
            <input 
              type="text" 
              v-model="formData.name"
              class="form-control" 
              id="inputName" 
              tabindex="1" 
              placeholder="Full Name" 
              required
            >
          </div>

          <div class="input-group nm-gp">
            <span class="nm-gp-pp"><i class="fas fa-envelope-open"></i></span>
            <input 
              type="email" 
              v-model="formData.email"
              class="form-control" 
              id="inputEmail" 
              tabindex="2" 
              placeholder="Email" 
              required
            >
          </div>
          
          <div class="input-group nm-gp">
            <span class="nm-gp-pp"><i class="fas fa-lock"></i></span>
            <input 
              :type="showPassword ? 'text' : 'password'"
              v-model="formData.password"
              class="form-control" 
              id="inputPassword" 
              tabindex="3" 
              placeholder="Password" 
              required
            >
          </div>

          <div class="input-group nm-gp">
            <span class="nm-gp-pp"><i class="fas fa-lock"></i></span>
            <input 
              :type="showPassword ? 'text' : 'password'"
              v-model="formData.password_confirmation"
              class="form-control" 
              id="inputPasswordConfirm" 
              tabindex="4" 
              placeholder="Confirm Password" 
              required
            >
          </div>

          <!-- Error Message -->
          <div v-if="errorMessage" class="alert alert-danger" role="alert">
            {{ errorMessage }}
          </div>

          <!-- Success Message -->
          <div v-if="successMessage" class="alert alert-success" role="alert">
            {{ successMessage }}
          </div>

          <div class="row nm-aic nm-mb-2">
            <div class="col-sm-6 nm-mb-1 nm-mb-sm-0">
              <span class="nm-fs-1 nm-tm">Show password</span>
              <label class="nm-sw-pd">
                <input 
                  type="checkbox" 
                  v-model="showPassword"
                  id="toggle-password" 
                  class="d-none"
                >
                <span class="slider round"></span>
              </label>
            </div>
            
            <div class="col-sm-6 nm-sm-tr">
              <button 
                type="submit" 
                class="btn btn-primary nm-hvr nm-btn-1"
                :disabled="isLoading"
              >
                {{ isLoading ? 'Creating Account...' : 'Sign Up' }}
              </button>
            </div>
          </div>

          <div class="row nm-row-ct nm-tp-3">
            <div class="form-group form-check">
              <input 
                type="checkbox" 
                v-model="formData.terms"
                class="form-check-input" 
                id="termsAndConditions"
                required
              >
              <label class="form-check-label nm-check" for="termsAndConditions">
                I agree to the <a class="nm-fs-1 nm-fw-bd" href="#">Terms & Conditions</a>
              </label>
            </div>
          </div>

          <div class="row nm-row-ct nm-tp-5">
            <p>
              © 2025 All Rights Reserved. <router-link to="/" class="heading" aria-label="Doctors Hero">DOCTORS HERO</router-link> by Orbizen Limited. 
              <a class="heading" href="#" aria-label="Terms & Conditions">Terms & Conditions</a>, 
              <a class="heading" href="#" aria-label="Privacy">Privacy Settings</a>.
            </p>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()

// Reactive data
const showPassword = ref(false)
const isLoading = ref(false)
const errorMessage = ref('')
const successMessage = ref('')

const formData = reactive({
  name: '',
  email: '',
  password: '',
  password_confirmation: '',
  terms: false
})

// Signup handler
const handleSignup = async () => {
  isLoading.value = true
  errorMessage.value = ''
  successMessage.value = ''

  // Client-side validation
  if (formData.password !== formData.password_confirmation) {
    errorMessage.value = 'Passwords do not match.'
    isLoading.value = false
    return
  }

  if (!formData.terms) {
    errorMessage.value = 'You must agree to the Terms & Conditions.'
    isLoading.value = false
    return
  }

  try {
    const response = await axios.post('/api/register', {
      name: formData.name,
      email: formData.email,
      password: formData.password,
      password_confirmation: formData.password_confirmation
    })

    if (response.data.success) {
      successMessage.value = 'Account created successfully! Redirecting to dashboard...'
      
      // Store auth data
      localStorage.setItem('authToken', response.data.token)
      localStorage.setItem('userRole', response.data.user.role)
      localStorage.setItem('user', JSON.stringify(response.data.user))

      // Redirect after short delay
      setTimeout(() => {
        window.location.href = response.data.redirect || '/dashboard'
      }, 1500)
    } else {
      errorMessage.value = response.data.message || 'Registration failed. Please try again.'
    }
  } catch (error) {
    console.error('Signup error:', error)
    
    if (error.response && error.response.data && error.response.data.message) {
      errorMessage.value = error.response.data.message
    } else if (error.response && error.response.data && error.response.data.errors) {
      // Handle validation errors
      const errors = error.response.data.errors
      errorMessage.value = Object.values(errors).flat().join(', ')
    } else {
      errorMessage.value = 'An unexpected error occurred. Please try again.'
    }
  } finally {
    isLoading.value = false
  }
}
</script>

<style scoped>
/* Component-specific styles */
.alert {
  margin-bottom: 1rem;
  border-radius: 8px;
}

.heading {
  text-decoration: none;
  color: inherit;
}

.heading:hover {
  text-decoration: underline;
}

.underline {
  text-decoration: underline;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
</style>