/**
 * Alpine Component: Staff Page
 */
import { requestJson } from '../helpers';

export function registerStaffPage(Alpine) {
    Alpine.data('staffPage', () => ({
        page: 1,
        pageSize: 10,
        totalItems: 0,
        totalPages: 1,
        rows: [],
        filters: { keyword: '' },
        loading: false,
        editingId: null,
        deletingId: null,
        currentUserId: '',
        currentUserRole: '',
        _addFormBound: false,
        _editFormBound: false,

        init() {
            const root = document.getElementById('staff-page');
            this.currentUserId = root?.dataset?.currentUserId || '';
            this.currentUserRole = root?.dataset?.currentUserRole || '';
            this.loadRows();
            this._bindAddForm();
            this._bindEditForm();
        },

        get startItem() { return this.totalItems === 0 ? 0 : (this.page - 1) * this.pageSize + 1; },
        get endItem() { return Math.min(this.page * this.pageSize, this.totalItems); },
        get visiblePages() {
            const pages = [];
            const s = Math.max(1, this.page - 2);
            const e = Math.min(this.totalPages, this.page + 2);
            for (let i = s; i <= e; i++) pages.push(i);
            return pages;
        },

        async loadRows() {
            this.loading = true;
            try {
                const params = new URLSearchParams();
                params.set('page', this.page);
                params.set('per_page', this.pageSize);
                if (this.filters.keyword) params.set('keyword', this.filters.keyword);

                const root = document.getElementById('staff-page');
                const baseUrl = root?.dataset?.dataUrl || '/staff/data';
                const data = await requestJson(baseUrl + '?' + params.toString(), { method: 'GET' });
                const pagination = data.pagination || {};
                this.totalItems = pagination.total || 0;
                this.totalPages = pagination.last_page || 1;
                this.page = pagination.current_page || this.page;
                this.pageSize = pagination.per_page || this.pageSize || 10;
                this.rows = Array.isArray(data.data) ? data.data : [];
            } catch (e) {
                showError('Lỗi', 'Không thể tải danh sách nhân viên');
            } finally {
                this.loading = false;
            }
        },

        openAddModal() {
            const form = document.getElementById('addStaffForm');
            if (form) form.reset();
            modalOpen('addStaffModal');
        },

        openEditModal(row) {
            this.editingId = row.id;
            const form = document.getElementById('editStaffForm');
            if (!form) return;
            const nameInput = form.querySelector('input[name="name"]');
            const displayNameInput = form.querySelector('input[name="display_name"]');
            const emailInput = form.querySelector('input[name="email"]');
            const roleInputs = form.querySelectorAll('input[name="role"]');
            if (nameInput) nameInput.value = row.name || '';
            if (displayNameInput) displayNameInput.value = row.display_name || '';
            if (emailInput) emailInput.value = row.email || '';
            const isOwnerSelf = row.role === 'owner'
                && this.currentUserRole === 'owner'
                && row.id === this.currentUserId;
            roleInputs.forEach(input => {
                input.disabled = isOwnerSelf;
                if (isOwnerSelf) {
                    input.checked = false;
                } else {
                    input.checked = input.value === (row.role || 'staff');
                }
            });
            modalOpen('editStaffModal');
        },

        confirmDelete(rowId) {
            this.deletingId = rowId;
            modalOpen('deleteStaffConfirmModal');
        },

        submitAddStaff: window.withSubmitGuard('staff_add', async function (e) {
            e.preventDefault();
            const form = document.getElementById('addStaffForm');
            if (!form) return;
            const payload = Object.fromEntries(new FormData(form).entries());
            try {
                await requestJson('/staff', { method: 'POST', body: JSON.stringify(payload) });
                modalClose('addStaffModal');
                form.reset();
                showSuccess('Thành công', 'Thêm nhân viên thành công');
                this.page = 1;
                await this.loadRows();
            } catch (err) {
                showError('Lỗi', err.message || 'Không thể thêm nhân viên');
            }
        }),

        submitEditStaff: window.withSubmitGuard('staff_edit', async function (e) {
            e.preventDefault();
            if (!this.editingId) return;
            const form = document.getElementById('editStaffForm');
            if (!form) return;
            const payload = Object.fromEntries(new FormData(form).entries());
            try {
                await requestJson('/staff/' + this.editingId, { method: 'PUT', body: JSON.stringify(payload) });
                modalClose('editStaffModal');
                showSuccess('Thành công', 'Cập nhật nhân viên thành công');
                this.editingId = null;
                await this.loadRows();
            } catch (err) {
                showError('Lỗi', err.message || 'Không thể cập nhật nhân viên');
            }
        }),

        executeDeleteStaff: window.withSubmitGuard('staff_delete', async function () {
            if (!this.deletingId) return;
            const id = this.deletingId;
            this.deletingId = null;
            try {
                await requestJson('/staff/' + id, { method: 'DELETE' });
                showSuccess('Thành công', 'Xóa nhân viên thành công');
                await this.loadRows();
            } catch (err) {
                showError('Lỗi', err.message || 'Không thể xóa nhân viên');
            } finally {
                modalClose('deleteStaffConfirmModal');
            }
        }),

        roleLabel(r) {
            const labels = { admin: 'Admin', staff: 'Nhân viên', owner: 'Chủ sở hữu' };
            return labels[r] || r || 'Không xác định';
        },

        goToPage(p) { this.page = Math.max(1, Math.min(p, this.totalPages)); this.loadRows(); },
        prevPage() { if (this.page > 1) { this.page--; this.loadRows(); } },
        nextPage() { if (this.page < this.totalPages) { this.page++; this.loadRows(); } },
        pageSizeChange() { this.page = 1; this.loadRows(); },

        _bindForm(id, handler) {
            const key = '_' + id + 'Bound';
            if (this[key]) return;
            const form = document.getElementById(id);
            if (form) { form.addEventListener('submit', (e) => handler.call(this, e)); this[key] = true; }
        },

        _bindAddForm() { this._bindForm('addStaffForm', this.submitAddStaff); },

        _bindEditForm() { this._bindForm('editStaffForm', this.submitEditStaff); },
    }));
}
