import { formatDateTime } from '../utils/date';

export function registerNotesChat(Alpine) {
    Alpine.data('notesChat', () => ({
        bookingId: '',
        bookingName: '',
        notes: [],
        newContent: '',
        editingId: null,
        editingContent: '',
        sending: false,
        pendingDeleteNoteId: null,

        async open(id, name) {
            this.bookingId = id;
            this.bookingName = name;
            this.notes = [];
            this.newContent = '';
            this.editingId = null;
            this.editingContent = '';
            this.pendingDeleteNoteId = null;
            // [FIX] Load notes với fallback lazy load từ API nếu local rỗng
            await this.loadNotes();
            modalOpen('notesChatModal');
            this.syncModalTitle();
        },

        close() {
            this.resetModalTitle();
            this.bookingId = '';
            this.bookingName = '';
            this.notes = [];
            this.newContent = '';
            this.editingId = null;
            this.editingContent = '';
            this.sending = false;
            this.pendingDeleteNoteId = null;
        },

        syncModalTitle() {
            const el = document.querySelector('#notesChatModal .modal-header h3');
            if (el) el.textContent = 'Ghi chú — ' + this.bookingName;
        },

        resetModalTitle() {
            const el = document.querySelector('#notesChatModal .modal-header h3');
            if (el) el.textContent = 'Ghi chú';
        },

        async loadNotes() {
            // Thử load từ local data trước
            let loaded = false;
            if (window.__pageKocs && Array.isArray(window.__pageKocs)) {
                const koc = window.__pageKocs.find(k => String(k.id) === String(this.bookingId));
                if (koc && koc.booking_notes && koc.booking_notes.length > 0) {
                    const currentId = window.__currentUserIdHex;
                    this.notes = koc.booking_notes.map(n => ({
                        ...n,
                        is_editable: String(n.user_id) === String(currentId),
                        is_own: String(n.user_id) === String(currentId),
                    }));
                    loaded = true;
                }
            }
            // [FIX] Fallback: gọi API lazy load nếu local rỗng
            if (!loaded) {
                try {
                    const resp = await fetch('/bookings/' + this.bookingId + '/notes', {
                        headers: { Accept: 'application/json', 'X-Requested-With': 'XMLHttpRequest' },
                    });
                    if (resp.ok) {
                        const data = await resp.json();
                        const notes = Array.isArray(data) ? data : (data.notes || []);
                        const currentId = window.__currentUserIdHex;
                        this.notes = notes.map(n => ({
                            ...n,
                            is_editable: String(n.user_id) === String(currentId),
                            is_own: String(n.user_id) === String(currentId),
                        }));
                        // Cache vào __pageKocs
                        if (window.__pageKocs) {
                            const koc = window.__pageKocs.find(k => String(k.id) === String(this.bookingId));
                            if (koc) koc.booking_notes = this.notes;
                        }
                    }
                } catch (e) {
                    console.error('Failed to lazy load notes:', e);
                }
            }
        },

        async addNote() {
            const content = this.newContent.trim();
            if (!content) return;
            this.sending = true;
            try {
                const resp = await fetch('/bookings/' + this.bookingId + '/notes', {
                    method: 'POST',
                    headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-TOKEN': this.getCsrfToken() },
                    body: JSON.stringify({ content }),
                });
                if (!resp.ok) throw new Error('Status ' + resp.status);
                const note = await resp.json();
                const currentId = window.__currentUserIdHex;
                note.is_own = String(note.user_id) === String(currentId);
                note.is_editable = note.is_own;
                this.notes.push(note);
                this.newContent = '';
                this.syncToPageKocs();
                this.showSuccess('Đã thêm ghi chú');
            } catch (e) {
                this.showError('Không thể thêm ghi chú: ' + (e.message || e));
            } finally {
                this.sending = false;
            }
        },

        startEdit(noteId) {
            this.editingId = noteId;
            const note = this.notes.find(n => n.id === noteId);
            this.editingContent = note ? note.content : '';
        },

        cancelEdit() {
            this.editingId = null;
            this.editingContent = '';
        },

        async updateNote(noteId) {
            const content = this.editingContent.trim();
            if (!content) return;
            this.sending = true;
            try {
                const resp = await fetch('/bookings/' + this.bookingId + '/notes/' + noteId, {
                    method: 'PUT',
                    headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-TOKEN': this.getCsrfToken() },
                    body: JSON.stringify({ content }),
                });
                if (!resp.ok) throw new Error('Status ' + resp.status);
                const updated = await resp.json();
                const idx = this.notes.findIndex(n => n.id === noteId);
                if (idx !== -1) {
                    this.notes[idx].content = updated.content;
                    this.notes[idx].updated_at = updated.updated_at;
                }
                this.editingId = null;
                this.editingContent = '';
                this.syncToPageKocs();
                this.showSuccess('Đã cập nhật ghi chú');
            } catch (e) {
                this.showError('Không thể cập nhật ghi chú: ' + (e.message || e));
            } finally {
                this.sending = false;
            }
        },

        confirmDelete(noteId) {
            this.pendingDeleteNoteId = noteId;
            modalOpen('notesDeleteConfirm');
        },

        async confirmedDelete() {
            const noteId = this.pendingDeleteNoteId;
            if (!noteId) return;
            this.pendingDeleteNoteId = null;
            this.sending = true;
            try {
                const resp = await fetch('/bookings/' + this.bookingId + '/notes/' + noteId, {
                    method: 'DELETE',
                    headers: { 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-TOKEN': this.getCsrfToken() },
                });
                if (!resp.ok) throw new Error('Status ' + resp.status);
                this.notes = this.notes.filter(n => n.id !== noteId);
                this.syncToPageKocs();
                this.showSuccess('Đã xóa ghi chú');
            } catch (e) {
                this.showError('Không thể xóa ghi chú: ' + (e.message || e));
            } finally {
                this.sending = false;
            }
        },

        syncToPageKocs() {
            if (window.__pageKocs && Array.isArray(window.__pageKocs)) {
                const koc = window.__pageKocs.find(k => String(k.id) === String(this.bookingId));
                if (koc) koc.booking_notes = this.notes;
            }
        },

        formatNoteTime(v) { return formatDateTime(v); },

        getCsrfToken() {
            const m = document.querySelector('meta[name="csrf-token"]');
            return m ? m.getAttribute('content') : '';
        },

        showSuccess(msg) {
            if (typeof window.showSuccess === 'function') window.showSuccess('Thành công', msg);
        },

        showError(msg) {
            if (typeof window.showError === 'function') window.showError('Lỗi', msg);
        },
    }));
}
