import { m as Alpine } from './vendor-ui-CflGdlft.js';
import { apiGet, apiPost } from './app-api.js';

function register() {
  if (window.__ssaUsersRegistered) return;
  window.__ssaUsersRegistered = true;

  Alpine.data('learnersTable', () => ({
    users: [],
    filteredUsers: [],
    selectedUsers: [],
    currentPage: 1,
    itemsPerPage: 10,
    searchQuery: '',
    statusFilter: '',
    roleFilter: '',
    sortField: 'name',
    sortDirection: 'asc',
    isLoading: false,

    async init() {
      try {
        await this.refresh();
        await this.loadCharts();
      } catch (e) {
        const msg = e?.message ? String(e.message) : 'Failed to load learners';
        if (window.AdminApp?.notificationManager?.error) window.AdminApp.notificationManager.error(msg);
        else alert(msg);
      }
    },

    async refresh() {
      this.isLoading = true;
      try {
        const res = await apiGet('/learners');
        this.users = (res.data || []).map(l => ({
          id: l.id,
          name: `${l.first_name} ${l.last_name}`.trim(),
          email: l.email || l.guardian_email || '',
          role: 'learner',
          status: l.status || 'active',
          lastActive: l.learner_code,
          joinDate: (l.created_at || '').slice(0, 10),
          avatar: './assets/images/avatar-placeholder.svg',
          phone: l.phone || l.guardian_phone || '',
          department: l.guardian_name || '—',
          _raw: l,
        }));
        this.filterUsers();
        await this.loadCharts();
      } catch (e) {
        const msg = e?.message ? String(e.message) : 'Failed to load learners';
        if (window.AdminApp?.notificationManager?.error) window.AdminApp.notificationManager.error(msg);
        else alert(msg);
        throw e;
      } finally {
        this.isLoading = false;
      }
    },

    charts: {
      newLearners: null,
    },

    async loadCharts() {
      try {
        const res = await apiGet('/stats/new-learners?months=6');
        this.renderNewLearnersChart(res.data || []);
      } catch {
        // non-critical
      }
    },

    renderNewLearnersChart(rows) {
      const el = document.getElementById('newLearnersChart');
      if (!el || typeof ApexCharts === 'undefined') return;

      const categories = rows.map(r => r.ym);
      const series = rows.map(r => Number(r.count || 0));

      const options = {
        series: [{ name: 'New Learners', data: series }],
        chart: { type: 'bar', height: 260, toolbar: { show: false } },
        dataLabels: { enabled: false },
        xaxis: { categories },
        yaxis: { labels: { formatter: v => Number(v).toFixed(0) } },
        colors: ['#6366f1'],
      };

      if (this.charts.newLearners) {
        this.charts.newLearners.updateOptions(options);
      } else {
        this.charts.newLearners = new ApexCharts(el, options);
        this.charts.newLearners.render();
      }
    },

    filterUsers() {
      this.filteredUsers = this.users.filter(u => {
        const q = this.searchQuery.trim().toLowerCase();
        const matchesSearch = q === '' ||
          (u.name || '').toLowerCase().includes(q) ||
          (u.email || '').toLowerCase().includes(q) ||
          (u.phone || '').toLowerCase().includes(q) ||
          (u.lastActive || '').toLowerCase().includes(q) ||
          (u.department || '').toLowerCase().includes(q);

        const matchesStatus = this.statusFilter === '' || u.status === this.statusFilter;
        const matchesRole = this.roleFilter === '' || u.role === this.roleFilter;
        return matchesSearch && matchesStatus && matchesRole;
      });

      this.sortUsers();
      this.currentPage = 1;
    },

    sortBy(field) {
      if (this.sortField === field) {
        this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';
      } else {
        this.sortField = field;
        this.sortDirection = 'asc';
      }
      this.sortUsers();
    },

    sortUsers() {
      this.filteredUsers.sort((a, b) => {
        let aVal = a[this.sortField];
        let bVal = b[this.sortField];

        if (typeof aVal === 'string') aVal = aVal.toLowerCase();
        if (typeof bVal === 'string') bVal = bVal.toLowerCase();

        if (this.sortDirection === 'asc') return aVal > bVal ? 1 : -1;
        return aVal < bVal ? 1 : -1;
      });
    },

    get paginatedUsers() {
      const start = (this.currentPage - 1) * this.itemsPerPage;
      const end = start + this.itemsPerPage;
      return this.filteredUsers.slice(start, end);
    },

    get totalPages() {
      return Math.ceil(this.filteredUsers.length / this.itemsPerPage);
    },

    get visiblePages() {
      const delta = 2;
      const range = [];
      const rangeWithDots = [];

      for (let i = Math.max(2, this.currentPage - delta); i <= Math.min(this.totalPages - 1, this.currentPage + delta); i++) {
        range.push(i);
      }

      if (this.currentPage - delta > 2) rangeWithDots.push(1, '...');
      else rangeWithDots.push(1);

      rangeWithDots.push(...range);

      if (this.currentPage + delta < this.totalPages - 1) rangeWithDots.push('...', this.totalPages);
      else if (this.totalPages > 1) rangeWithDots.push(this.totalPages);

      return rangeWithDots.filter((v, i, a) => a.indexOf(v) === i && v <= this.totalPages);
    },

    goToPage(page) {
      if (page >= 1 && page <= this.totalPages) this.currentPage = page;
    },

    toggleAll(checked) {
      this.selectedUsers = checked ? this.paginatedUsers.map(u => u.id) : [];
    },

    createUser(userData) {
      this._createLearner(userData);
    },

    async _createLearner(userData) {
      const guardianName = userData.department || '';
      const guardianPhone = userData.phone || '';
      const guardianEmail = userData.email || '';

      const g = await apiPost('/guardians', {
        full_name: guardianName || `${userData.firstName || ''} Guardian`.trim(),
        phone: guardianPhone || null,
        email: guardianEmail || null,
        relationship: 'guardian',
      });

      const code = `SSA-${Date.now()}`;
      await apiPost('/learners', {
        guardian_id: g.id,
        learner_code: code,
        first_name: userData.firstName,
        last_name: userData.lastName,
        phone: userData.phone || null,
        email: userData.email || null,
        status: 'active',
      });

      await this.refresh();
      window.AdminApp?.notificationManager?.success('Learner created');
    },

    editUser() {
      window.AdminApp?.notificationManager?.info('Editing is not wired yet');
    },

    viewUser(user) {
      window.AdminApp?.notificationManager?.info(`Learner: ${user.name}`);
    },

    deleteUser() {
      window.AdminApp?.notificationManager?.warning('Delete is not wired yet');
    },

    exportUsers() {
      const headers = ['Learner', 'Learner Code', 'Guardian', 'Phone', 'Email', 'Status'];
      const rows = this.filteredUsers.map(u => [
        u.name,
        u.lastActive,
        u.department,
        u.phone,
        u.email,
        u.status,
      ]);
      const csv = [headers, ...rows].map(r => r.map(v => String(v ?? '').replaceAll(',', ' ')).join(',')).join('\n');
      const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
      const link = document.createElement('a');
      link.href = URL.createObjectURL(blob);
      link.download = 'learners-export.csv';
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },

    sendBulkInvites() {
      window.AdminApp?.notificationManager?.info('Bulk reminders are on Reports (Owing) page');
    },

    get stats() {
      const active = this.users.filter(u => u.status === 'active').length;
      const inactive = this.users.filter(u => u.status === 'inactive').length;
      return {
        total: this.users.length,
        active,
        pending: 0,
        inactive,
        newThisMonth: 0,
        activePercentage: this.users.length > 0 ? (active / this.users.length) * 100 : 0,
      };
    },

    get departmentStats() {
      return [];
    },

    get recentActivities() {
      return [];
    },

    get systemAlerts() {
      return [];
    },

    initCharts() {},
  }));

  Alpine.data('learnerForm', () => ({
    guardianMode: 'new',
    selectedGuardianId: '',
    guardians: [],
    form: {
      learnerFirstName: '',
      learnerLastName: '',
      learnerPhone: '',
      learnerEmail: '',
      learnerDob: '',
      learnerGender: '',
      learnerAddress: '',
      learnerStatus: 'active',
      guardianName: '',
      guardianPhone: '',
      guardianPhoneAlt: '',
      guardianEmail: '',
      guardianAddress: '',
      guardianRelationship: 'guardian',
      guardianStatus: 'active',
    },

    async init() {
      try {
        const res = await apiGet('/guardians');
        this.guardians = res.data || [];
      } catch {
        this.guardians = [];
      }
    },

    async saveUser() {
      try {
        if (!this.form.learnerFirstName || !this.form.learnerLastName) {
          window.AdminApp?.notificationManager?.warning('Learner first name and last name are required');
          return;
        }

        let guardianId = null;
        if (this.guardianMode === 'existing') {
          const id = Number(this.selectedGuardianId);
          if (!Number.isFinite(id) || id <= 0) {
            window.AdminApp?.notificationManager?.warning('Select an existing guardian');
            return;
          }
          guardianId = id;
        } else {
          if (!this.form.guardianName) {
            window.AdminApp?.notificationManager?.warning('Guardian name is required');
            return;
          }
          const g = await apiPost('/guardians', {
            full_name: this.form.guardianName,
            phone: this.form.guardianPhone || null,
            phone_alt: this.form.guardianPhoneAlt || null,
            email: this.form.guardianEmail || null,
            address: this.form.guardianAddress || null,
            relationship: this.form.guardianRelationship || 'guardian',
            status: this.form.guardianStatus || 'active',
          });
          guardianId = g.id;
        }

        const code = `SSA-${Date.now()}`;
        await apiPost('/learners', {
          guardian_id: guardianId,
          learner_code: code,
          first_name: this.form.learnerFirstName,
          last_name: this.form.learnerLastName,
          phone: this.form.learnerPhone || null,
          email: this.form.learnerEmail || null,
          date_of_birth: this.form.learnerDob || null,
          gender: this.form.learnerGender || null,
          address: this.form.learnerAddress || null,
          status: this.form.learnerStatus || 'active',
        });

        try {
          const tableRoot = document.querySelector('[x-data="learnersTable"]');
          const userTable = tableRoot ? Alpine.$data(tableRoot) : null;
          if (userTable && typeof userTable.refresh === 'function') {
            await userTable.refresh();
          }
        } catch {
          // non-critical: table refresh
        }

        const modalEl = document.getElementById('userModal');
        if (modalEl && window.bootstrap?.Modal) {
          window.bootstrap.Modal.getOrCreateInstance(modalEl).hide();
        }

        this.form = {
          learnerFirstName: '',
          learnerLastName: '',
          learnerPhone: '',
          learnerEmail: '',
          learnerDob: '',
          learnerGender: '',
          learnerAddress: '',
          learnerStatus: 'active',
          guardianName: '',
          guardianPhone: '',
          guardianPhoneAlt: '',
          guardianEmail: '',
          guardianAddress: '',
          guardianRelationship: 'guardian',
          guardianStatus: 'active',
        };

        this.guardianMode = 'new';
        this.selectedGuardianId = '';

        if (window.AdminApp?.notificationManager?.success) {
          window.AdminApp.notificationManager.success('Learner saved');
        } else {
          alert('Learner saved');
        }
      } catch (e) {
        window.AdminApp?.notificationManager?.error(e.message);
      }
    },
  }));
}

document.addEventListener('alpine:init', register);
register();
