'use strict';

(async () => {
  if (!VegApi.getToken(true)) {
    window.location.replace('/admin/login.html');
    return;
  }

  let admin;
  try {
    admin = (await VegApi.request('/api/auth/admin/me', { admin: true })).admin;
  } catch (_) {
    return;
  }
  document.getElementById('adminName').textContent = admin.username;

  const permissionLabels = {
    prices: 'أسعار الخضار',
    custody: 'تسجيل العهدة',
    files: 'ملفات الخضار',
  };
  const usersLoading = document.getElementById('usersLoading');
  const usersEmpty = document.getElementById('usersEmpty');
  const usersWrap = document.getElementById('usersTableWrap');
  const usersBody = document.getElementById('usersBody');
  const userModal = document.getElementById('userModal');
  const userForm = document.getElementById('userForm');
  const userModalTitle = document.getElementById('userModalTitle');
  const editingUserId = document.getElementById('editingUserId');
  const userUsername = document.getElementById('userUsername');
  const userPassword = document.getElementById('userPassword');
  const newPasswordGroup = document.getElementById('newPasswordGroup');
  const userCategory = document.getElementById('userCategorySelect');
  const saveUserButton = document.getElementById('saveUserButton');
  const passwordModal = document.getElementById('passwordModal');
  const passwordForm = document.getElementById('passwordForm');
  const passwordUserId = document.getElementById('passwordUserId');
  const selectedUsername = document.getElementById('selectedUsername');
  const newUserPassword = document.getElementById('newUserPassword');
  let users = [];

  function selectedPermissions() {
    return [...userForm.querySelectorAll('input[name="permission"]:checked')].map((input) => input.value);
  }

  function setSelectedPermissions(values) {
    userForm.querySelectorAll('input[name="permission"]').forEach((input) => {
      input.checked = values.includes(input.value);
    });
  }

  function openUserModal(user = null) {
    userForm.reset();
    editingUserId.value = user?.id || '';
    userModalTitle.textContent = user ? 'تعديل المستخدم' : 'إضافة مستخدم';
    userUsername.value = user?.username || '';
    userCategory.value = user?.category || '';
    setSelectedPermissions(user?.permissions || []);
    newPasswordGroup.hidden = Boolean(user);
    userPassword.required = !user;
    userPassword.value = '';
    userModal.hidden = false;
    setTimeout(() => userUsername.focus(), 0);
  }

  function closeUserModal() {
    userModal.hidden = true;
    userForm.reset();
  }

  function openPasswordModal(user) {
    passwordForm.reset();
    passwordUserId.value = user.id;
    selectedUsername.value = user.username;
    passwordModal.hidden = false;
    setTimeout(() => newUserPassword.focus(), 0);
  }

  async function loadStats() {
    try {
      const stats = await VegApi.request('/api/admin/stats', { admin: true });
      document.getElementById('statUsers').textContent = stats.users;
      document.getElementById('statCustodies').textContent = stats.custodies;
      document.getElementById('statLatest').textContent = stats.latestCustody ? VegApi.formatDate(stats.latestCustody.custody_date) : 'لا يوجد';
    } catch (error) {
      VegApi.toast(error.message, 'error');
    }
  }

  async function loadUsers() {
    usersLoading.hidden = false;
    usersEmpty.hidden = true;
    usersWrap.hidden = true;
    try {
      const result = await VegApi.request('/api/admin/users', { admin: true });
      users = result.users;
      usersLoading.hidden = true;
      if (!users.length) {
        usersEmpty.hidden = false;
        return;
      }
      usersBody.innerHTML = users.map((user) => `
        <tr>
          <td class="cell-title text-right" data-label="اسم المستخدم"><strong>${VegApi.escapeHtml(user.username)}</strong></td>
          <td data-label="الفئة">${VegApi.escapeHtml(user.category)}</td>
          <td class="text-right" data-label="القوائم الظاهرة"><div class="permission-chips">${user.permissions.map((key) => `<span class="permission-chip">${VegApi.escapeHtml(permissionLabels[key] || key)}</span>`).join('')}</div></td>
          <td data-label="تاريخ الإضافة">${VegApi.formatDateTime(user.created_at)}</td>
          <td class="cell-actions" data-label="الإجراءات"><div class="actions"><button class="btn btn-small" data-action="edit" data-id="${user.id}" type="button">تعديل</button><button class="btn btn-small" data-action="password" data-id="${user.id}" type="button">كلمة المرور</button><button class="btn btn-danger btn-small" data-action="delete" data-id="${user.id}" type="button">حذف</button></div></td>
        </tr>`).join('');
      usersWrap.hidden = false;
    } catch (error) {
      usersLoading.textContent = error.message;
    }
  }

  document.getElementById('openAddUserButton').addEventListener('click', () => openUserModal());
  document.getElementById('openAddUserButtonMobile')?.addEventListener('click', () => openUserModal());
  document.getElementById('closeUserModal').addEventListener('click', closeUserModal);
  document.getElementById('closePasswordModal').addEventListener('click', () => { passwordModal.hidden = true; });
  userModal.addEventListener('click', (event) => { if (event.target === userModal) closeUserModal(); });
  passwordModal.addEventListener('click', (event) => { if (event.target === passwordModal) passwordModal.hidden = true; });

  usersBody.addEventListener('click', async (event) => {
    const button = event.target.closest('[data-action]');
    if (!button) return;
    const user = users.find((item) => item.id === Number(button.dataset.id));
    if (!user) return;
    if (button.dataset.action === 'edit') openUserModal(user);
    if (button.dataset.action === 'password') openPasswordModal(user);
    if (button.dataset.action === 'delete') {
      if (!confirm(`حذف المستخدم "${user.username}"؟ سيتم إنهاء جميع جلساته فورًا، ولن تتأثر العهد المحفوظة.`)) return;
      VegApi.setButtonLoading(button, true, 'جاري الحذف...');
      try {
        const result = await VegApi.request(`/api/admin/users/${user.id}`, { method: 'DELETE', admin: true });
        VegApi.toast(result.message);
        await Promise.all([loadUsers(), loadStats()]);
      } catch (error) {
        VegApi.toast(error.message, 'error');
      } finally {
        VegApi.setButtonLoading(button, false);
      }
    }
  });

  userForm.addEventListener('submit', async (event) => {
    event.preventDefault();
    const id = Number(editingUserId.value || 0);
    const permissions = selectedPermissions();
    if (!permissions.length) {
      VegApi.toast('اختر قائمة واحدة على الأقل للمستخدم.', 'error');
      return;
    }
    const body = { username: userUsername.value, category: userCategory.value, permissions };
    if (!id) body.password = userPassword.value;
    VegApi.setButtonLoading(saveUserButton, true, 'جاري الحفظ...');
    try {
      const result = await VegApi.request(id ? `/api/admin/users/${id}` : '/api/admin/users', {
        method: id ? 'PUT' : 'POST', admin: true, body,
      });
      VegApi.toast(result.message);
      closeUserModal();
      await Promise.all([loadUsers(), loadStats()]);
    } catch (error) {
      VegApi.toast(error.message, 'error');
    } finally {
      VegApi.setButtonLoading(saveUserButton, false);
    }
  });

  passwordForm.addEventListener('submit', async (event) => {
    event.preventDefault();
    const submitButton = passwordForm.querySelector('button[type="submit"]');
    VegApi.setButtonLoading(submitButton, true, 'جاري التغيير...');
    try {
      const result = await VegApi.request(`/api/admin/users/${passwordUserId.value}/password`, {
        method: 'PUT', admin: true, body: { password: newUserPassword.value },
      });
      VegApi.toast(result.message);
      passwordModal.hidden = true;
    } catch (error) {
      VegApi.toast(error.message, 'error');
    } finally {
      VegApi.setButtonLoading(submitButton, false);
    }
  });

  document.getElementById('adminPasswordForm').addEventListener('submit', async (event) => {
    event.preventDefault();
    const form = event.currentTarget;
    const button = form.querySelector('button[type="submit"]');
    VegApi.setButtonLoading(button, true, 'جاري الحفظ...');
    try {
      const result = await VegApi.request('/api/admin/password', {
        method: 'PUT', admin: true,
        body: {
          currentPassword: document.getElementById('currentAdminPassword').value,
          newPassword: document.getElementById('newAdminPassword').value,
        },
      });
      VegApi.toast(result.message);
      form.reset();
    } catch (error) {
      VegApi.toast(error.message, 'error');
    } finally {
      VegApi.setButtonLoading(button, false);
    }
  });

  async function logoutAdmin() {
    if (!confirm('هل تريد تسجيل الخروج من الإدارة؟')) return;
    try { await VegApi.request('/api/auth/admin/logout', { method: 'POST', admin: true }); } catch (_) {}
    VegApi.clearToken(true);
    window.location.replace('/admin/login.html');
  }

  document.getElementById('adminLogoutButton').addEventListener('click', logoutAdmin);
  document.getElementById('adminMobileLogout')?.addEventListener('click', logoutAdmin);

  await Promise.all([loadUsers(), loadStats()]);
})();
