<h2 class="text-2xl font-bold text-gray-900 text-center mb-2">
  Change Password
</h2>
<p class="text-center text-gray-600 text-sm mb-8">
  Enter your current password and choose a new one.
</p>

<div id="change-form" class="space-y-6">
  <div>
    <label for="current-password" class="block text-sm font-medium text-gray-700">
      Current Password
    </label>
    <div class="mt-1">
      <input type="password" id="current-password" placeholder="Enter current 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-blue-500 focus:border-blue-500 sm:text-sm">
    </div>
  </div>

  <div>
    <label for="new-password" class="block text-sm font-medium text-gray-700">
      New Password
    </label>
    <div class="mt-1">
      <input type="password" id="new-password" placeholder="Enter new password (min 6 characters)" 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-blue-500 focus:border-blue-500 sm:text-sm">
    </div>
    <p class="mt-1 text-xs text-gray-500">Password must be at least 6 characters long.</p>
  </div>

  <div>
    <label for="confirm-password" class="block text-sm font-medium text-gray-700">
      Confirm New Password
    </label>
    <div class="mt-1">
      <input type="password" id="confirm-password" placeholder="Confirm new 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-blue-500 focus:border-blue-500 sm:text-sm">
    </div>
  </div>

  <div>
    <button id="change-button" type="button"
            class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed">
      Change Password
    </button>
  </div>

  <div id="message"></div>
</div>

<div class="mt-6 text-center">
  <%= link_to "Back to Admin", "/admin",
      class: "text-sm font-medium text-blue-600 hover:text-blue-500" %>
</div>

<script src="https://www.gstatic.com/firebasejs/9.22.0/firebase-app-compat.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.22.0/firebase-auth-compat.js"></script>

<script>
  // Firebase configuration
  const firebaseConfig = {
    apiKey: "<%= ENV['FIREBASE_API_KEY'] %>",
    authDomain: "<%= ENV['FIREBASE_PROJECT_ID'] %>.firebaseapp.com",
    projectId: "<%= ENV['FIREBASE_PROJECT_ID'] %>",
  };

  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);
  const auth = firebase.auth();

  document.getElementById('change-button').addEventListener('click', function() {
    const currentPassword = document.getElementById('current-password').value;
    const newPassword = document.getElementById('new-password').value;
    const confirmPassword = document.getElementById('confirm-password').value;
    const messageDiv = document.getElementById('message');
    const button = document.getElementById('change-button');

    // Validation
    if (!currentPassword || !newPassword || !confirmPassword) {
      messageDiv.innerHTML = '<div class="bg-red-50 border-l-4 border-red-400 p-4 text-red-700 text-sm">Please fill in all fields.</div>';
      return;
    }

    if (newPassword !== confirmPassword) {
      messageDiv.innerHTML = '<div class="bg-red-50 border-l-4 border-red-400 p-4 text-red-700 text-sm">New passwords do not match.</div>';
      return;
    }

    if (newPassword.length < 6) {
      messageDiv.innerHTML = '<div class="bg-red-50 border-l-4 border-red-400 p-4 text-red-700 text-sm">Password must be at least 6 characters long.</div>';
      return;
    }

    if (currentPassword === newPassword) {
      messageDiv.innerHTML = '<div class="bg-red-50 border-l-4 border-red-400 p-4 text-red-700 text-sm">New password must be different from current password.</div>';
      return;
    }

    // Disable button and show loading
    button.disabled = true;
    button.innerHTML = '<svg class="animate-spin -ml-1 mr-2 h-4 w-4 text-white inline" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg> Changing...';
    messageDiv.innerHTML = '';

    const user = auth.currentUser;

    if (!user) {
      messageDiv.innerHTML = '<div class="bg-red-50 border-l-4 border-red-400 p-4 text-red-700 text-sm">You must be logged in to change your password.</div>';
      button.innerHTML = 'Change Password';
      button.disabled = false;
      return;
    }

    // Re-authenticate user before changing password
    const credential = firebase.auth.EmailAuthProvider.credential(
      user.email,
      currentPassword
    );

    user.reauthenticateWithCredential(credential)
      .then(function() {
        // Update password
        return user.updatePassword(newPassword);
      })
      .then(function() {
        messageDiv.innerHTML = '<div class="bg-green-50 border-l-4 border-green-400 p-4 text-green-700 text-sm">Password changed successfully! You can now use your new password to log in.</div>';
        // Clear form
        document.getElementById('current-password').value = '';
        document.getElementById('new-password').value = '';
        document.getElementById('confirm-password').value = '';
        button.innerHTML = 'Change Password';
        button.disabled = false;
      })
      .catch(function(error) {
        let errorMessage = 'An error occurred. Please try again.';

        switch(error.code) {
          case 'auth/wrong-password':
            errorMessage = 'Current password is incorrect.';
            break;
          case 'auth/weak-password':
            errorMessage = 'Password is too weak. Please choose a stronger password.';
            break;
          case 'auth/requires-recent-login':
            errorMessage = 'Please log out and log in again before changing your password.';
            break;
          default:
            errorMessage = error.message;
        }

        messageDiv.innerHTML = '<div class="bg-red-50 border-l-4 border-red-400 p-4 text-red-700 text-sm">' + errorMessage + '</div>';
        button.innerHTML = 'Change Password';
        button.disabled = false;
      });
  });
</script>
