<template>
    <div class="mm__threads">
        <!-- <h2>Parent Component</h2>
        <p>Checked boxes: {{ selectedThreads.length }}</p>
 -->
        <div class="mm__operations">
            <div class="mm__operations-left">
                <!-- Select All -->
                <input type="checkbox" v-model="selectAll"
                    @change="selectedThreads = selectAll ? threads.map(t => t.id) : []">

                <!-- Buttons with SVG Icons -->
                <button @click="markOpen" title="Open Thread" name="open">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640">
                        <path
                            d="M416 160C416 124.7 444.7 96 480 96C515.3 96 544 124.7 544 160L544 192C544 209.7 558.3 224 576 224C593.7 224 608 209.7 608 192L608 160C608 89.3 550.7 32 480 32C409.3 32 352 89.3 352 160L352 224L192 224C156.7 224 128 252.7 128 288L128 512C128 547.3 156.7 576 192 576L448 576C483.3 576 512 547.3 512 512L512 288C512 252.7 483.3 224 448 224L416 224L416 160z" />
                    </svg>
                </button>

                <button @click="markClosed" title="Close Thread" name="close">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640">
                        <path
                            d="M256 160L256 224L384 224L384 160C384 124.7 355.3 96 320 96C284.7 96 256 124.7 256 160zM192 224L192 160C192 89.3 249.3 32 320 32C390.7 32 448 89.3 448 160L448 224C483.3 224 512 252.7 512 288L512 512C512 547.3 483.3 576 448 576L192 576C156.7 576 128 547.3 128 512L128 288C128 252.7 156.7 224 192 224z" />
                    </svg>
                </button>
                <!-- Star -->
                <button @click="star" title="Star Thread" name="star">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640">
                        <path
                            d="M341.5 45.1C337.4 37.1 329.1 32 320.1 32C311.1 32 302.8 37.1 298.7 45.1L225.1 189.3L65.2 214.7C56.3 216.1 48.9 222.4 46.1 231C43.3 239.6 45.6 249 51.9 255.4L166.3 369.9L141.1 529.8C139.7 538.7 143.4 547.7 150.7 553C158 558.3 167.6 559.1 175.7 555L320.1 481.6L464.4 555C472.4 559.1 482.1 558.3 489.4 553C496.7 547.7 500.4 538.8 499 529.8L473.7 369.9L588.1 255.4C594.5 249 596.7 239.6 593.9 231C591.1 222.4 583.8 216.1 574.8 214.7L415 189.3L341.5 45.1z" />
                    </svg>
                </button>

                <!-- Create -->
                <button @click="toggleCreateThread" title="Create Thread" name="create">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640">
                        <path
                            d="M64 416L64 192C64 139 107 96 160 96L480 96C533 96 576 139 576 192L576 416C576 469 533 512 480 512L360 512C354.8 512 349.8 513.7 345.6 516.8L230.4 603.2C226.2 606.3 221.2 608 216 608C202.7 608 192 597.3 192 584L192 512L160 512C107 512 64 469 64 416z" />
                    </svg>
                </button>

                <button v-show="canViewAllThreads" @click="archive" title="Archive Thread" name="archive">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640">
                        <path
                            d="M232.7 69.9L224 96L128 96C110.3 96 96 110.3 96 128C96 145.7 110.3 160 128 160L512 160C529.7 160 544 145.7 544 128C544 110.3 529.7 96 512 96L416 96L407.3 69.9C402.9 56.8 390.7 48 376.9 48L263.1 48C249.3 48 237.1 56.8 232.7 69.9zM512 208L128 208L149.1 531.1C150.7 556.4 171.7 576 197 576L443 576C468.3 576 489.3 556.4 490.9 531.1L512 208z" />
                    </svg>
                </button>


                <button v-show="canViewAllThreads" @click="restore" title="Restore Archived Thread" name="restore">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640">
                        <path
                            d="M263.1 48L377 48C390.8 48 403 56.8 407.4 69.9L416 96L512 96C529.7 96 544 110.3 544 128C544 145.7 529.7 160 512 160L128 160C110.3 160 96 145.7 96 128C96 110.3 110.3 96 128 96L224 96L232.7 69.9C237.1 56.8 249.3 48 263.1 48zM128 208L512 208L512 512C512 547.3 483.3 576 448 576L192 576C156.7 576 128 547.3 128 512L128 208zM337 287C327.6 277.6 312.4 277.6 303.1 287L231.1 359C221.7 368.4 221.7 383.6 231.1 392.9C240.5 402.2 255.7 402.3 265 392.9L296 361.9L296 464C296 477.3 306.7 488 320 488C333.3 488 344 477.3 344 464L344 361.9L375 392.9C384.4 402.3 399.6 402.3 408.9 392.9C418.2 383.5 418.3 368.3 408.9 359L336.9 287z" />
                    </svg>
                </button>

                <!-- Trash -->
                <button v-show="canViewAllThreads" @click="trash" title="Erase Thread Forever" name="trash">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 640">
                        <path
                            d="M210.5 480L333.5 480L398.8 414.7L225.3 241.2L98.6 367.9L210.6 479.9zM256 544L210.5 544C193.5 544 177.2 537.3 165.2 525.3L49 409C38.1 398.1 32 383.4 32 368C32 352.6 38.1 337.9 49 327L295 81C305.9 70.1 320.6 64 336 64C351.4 64 366.1 70.1 377 81L559 263C569.9 273.9 576 288.6 576 304C576 319.4 569.9 334.1 559 345L424 480L544 480C561.7 480 576 494.3 576 512C576 529.7 561.7 544 544 544L256 544z" />
                    </svg>
                </button>

            </div>
            <div v-show="canViewAllThreads" class="mm__operations-center">
                <!-- Assign -->
                <div class="mm__assign">
                    <select class="no-chosen" name="assign">
                        <option value="" selected>All</option>
                        <option value="0">Unassigned</option>
                        <option v-for="admin in admins" :key="admin.id" :value="admin.id">
                            {{ admin.name }}
                        </option>
                    </select>
                    <button @click="find" title="Find Assigned" name="find">
                        <svg xmlns="http://www.w3.org/2000/svg"
                            viewBox="0 0 640 640"><!--!Font Awesome Free v7.0.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.-->
                            <path
                                d="M480 272C480 317.9 465.1 360.3 440 394.7L566.6 521.4C579.1 533.9 579.1 554.2 566.6 566.7C554.1 579.2 533.8 579.2 521.3 566.7L394.7 440C360.3 465.1 317.9 480 272 480C157.1 480 64 386.9 64 272C64 157.1 157.1 64 272 64C386.9 64 480 157.1 480 272zM272 416C351.5 416 416 351.5 416 272C416 192.5 351.5 128 272 128C192.5 128 128 192.5 128 272C128 351.5 192.5 416 272 416z" />
                        </svg>
                    </button>
                    <button @click="assign" title="Assign Thread" name="assign">
                        <svg xmlns="http://www.w3.org/2000/svg"
                            viewBox="0 0 640 640"><!--!Font Awesome Free v7.0.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.-->
                            <path
                                d="M136 192C136 125.7 189.7 72 256 72C322.3 72 376 125.7 376 192C376 258.3 322.3 312 256 312C189.7 312 136 258.3 136 192zM48 546.3C48 447.8 127.8 368 226.3 368L285.7 368C384.2 368 464 447.8 464 546.3C464 562.7 450.7 576 434.3 576L77.7 576C61.3 576 48 562.7 48 546.3zM544 160C557.3 160 568 170.7 568 184L568 232L616 232C629.3 232 640 242.7 640 256C640 269.3 629.3 280 616 280L568 280L568 328C568 341.3 557.3 352 544 352C530.7 352 520 341.3 520 328L520 280L472 280C458.7 280 448 269.3 448 256C448 242.7 458.7 232 472 232L520 232L520 184C520 170.7 530.7 160 544 160z" />
                        </svg>
                    </button>
                    <button @click="unassign" title="Unassign Thread" name="unassign">
                        <svg xmlns="http://www.w3.org/2000/svg"
                            viewBox="0 0 640 640"><!--!Font Awesome Free v7.0.1 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free Copyright 2025 Fonticons, Inc.-->
                            <path
                                d="M136 192C136 125.7 189.7 72 256 72C322.3 72 376 125.7 376 192C376 258.3 322.3 312 256 312C189.7 312 136 258.3 136 192zM48 546.3C48 447.8 127.8 368 226.3 368L285.7 368C384.2 368 464 447.8 464 546.3C464 562.7 450.7 576 434.3 576L77.7 576C61.3 576 48 562.7 48 546.3zM472 232L616 232C629.3 232 640 242.7 640 256C640 269.3 629.3 280 616 280L472 280C458.7 280 448 269.3 448 256C448 242.7 458.7 232 472 232z" />
                        </svg>
                    </button>
                </div>
            </div>

            <!-- Filters -->
            <div class="mm__operations-right">
                <div class="mm__filters">
                    <select class="no-chosen" v-model="selectedFilter" @change="applyFilter">
                        <option v-for="(filter, index) in filters" :key="index" :value="index">
                            {{ filter }}
                        </option>
                    </select>
                </div>
            </div>
        </div>

        <!-- Create Thread Form -->
        <div class="mm__create-thread">
            <form class="create-thread-form" action="/admin/members/messaging/threads/create-thread" method="POST">
                <input name="title" type="text" placeholder="Thread Title" />
                <select class="no-chosen" name="member">
                    <option disabled selected>Select Member</option>
                    <option v-for="member in members" :key="member.id" :value="member.id">
                        {{ member.full_name }}
                    </option>
                </select>
                <select class="no-chosen" name="category">
                    <option disabled selected>Select Category</option>
                    <option v-for="(category, index) in categories" :key="index" :value="index">
                        {{ category }}
                    </option>
                </select> <input type="submit" value="New Thread">
            </form>
        </div>

        <ThreadsTable :threads="threads" :selectedThreads="selectedThreads"
            @checked-threads="ids => selectedThreads = ids" />
        <ThreadsPagination :current="pagination.current_page" :last="pagination.last_page" @page-changed="fetchThreads" />
    </div>
</template>

<script>
import ThreadsTable from './ThreadsTable.vue';
import ThreadsPagination from './ThreadsPagination.vue';

export default {
    name: 'Threads',
    components: { ThreadsTable, ThreadsPagination },
    data() {
        return {
            canViewAllThreads: null,
            selectAll: false,
            selectedThreads: [],
            threads: [],
            admins: [],
            members: [],
            categories: [],
            filters: [],
            pagination: {
                current_page: 1,
                last_page: 1,
            },
            selectedFilter: 0
        }
    },
    watch: {
        selectAll(newVal) {
            if (newVal) {
                // select all thread IDs
                this.selectedThreads = this.threads.map(t => t.id);
            } else {
                this.selectedThreads = [];
            }
        },
        // if threads change, reapply selectAll state
        threads() {
            if (this.selectAll) {
                this.selectedThreads = this.threads.map(t => t.id);
            }
        }
    },
    mounted() {
        this.fetchThreads()
    },
    methods: {
        async fetchThreads(page = 1) {
            try {
                const res = await fetch(`/admin/members/messaging/fetch?page=${page}`);
                const json = await res.json();

                this.threads = json.threads || [];
                this.admins = json.admins || [];
                this.filters = json.filters || [];
                this.members = json.members || [];
                this.categories = json.categories || [];
                this.canViewAllThreads = json.canViewAllThreads;

                // pagination
                const current = json.current_page;
                const last = json.last_page;

                this.pagination.current_page = current;
                this.pagination.last_page = last;
                this.pagination.prev_page = current > 1 ? current - 1 : null;
                this.pagination.next_page = current < last ? current + 1 : null;
            } catch (e) {
                console.error('Fetch failed', e);
            }
        },

        handleCheckedThreads(ids) {
            this.selectedThreads = ids;
        },

        async markOpen() {
            if (!this.selectedThreads.length) return alert('No threads selected.');
            await this._postThreads('/admin/members/messaging/threads/mark-open');
        },

        async markClosed() {
            if (!this.selectedThreads.length) return alert('No threads selected.');
            await this._postThreads('/admin/members/messaging/threads/mark-closed');
        },

        async archive() {
            if (!this.selectedThreads.length) return alert('No threads selected.');
            await this._postThreads('/admin/members/messaging/threads/archive');
        },

        async trash() {
            if (!this.selectedThreads.length) return alert('No threads selected.');
            if (!confirm('Are you sure you want to permanently delete the selected threads?')) return;
            await this._deleteThreads('/admin/members/messaging/threads/trash');
        },

        async star() {
            if (!this.selectedThreads.length) return alert('No threads selected.');
            await this._postThreads('/admin/members/messaging/threads/star');
        },

        async restore() {
            if (!this.selectedThreads.length) return alert('No threads selected.');
            await this._postThreads('/admin/members/messaging/threads/restore');
        },

        toggleCreateThread() {
            const form = document.querySelector('.create-thread-form');
            if (!form) return;
            form.style.display = form.style.display === 'flex' ? 'none' : 'flex';
        },
        toggleAll() {
            this.selectedThreads = this.selectAll
                ? this.threads.map(t => t.id)
                : [];
        },
        async find() {
            const id = this._gatherSelectedDropdown();
            await this._postThreads('/admin/members/messaging/threads/find', { id }, true);
        },

        async assign() {
            const id = this._gatherSelectedDropdown();
            if (!id || !this.selectedThreads.length) return alert('Select threads and an admin.');
            await this._postThreads('/admin/members/messaging/threads/assign', { id });
        },

        async unassign() {
            const id = this._gatherSelectedDropdown();
            if (!id || !this.selectedThreads.length) return alert('Select threads and an admin.');
            await this._postThreads('/admin/members/messaging/threads/unassign', { id });
        },
        applyFilter() {
            this._postThreads('/admin/members/messaging/threads/filter', { filter: this.selectedFilter }, true);
        },

        // ----- Helper functions -----
        async _postThreads(url, extraData = {}, replaceThreads = false) {
            try {
                const token = document.querySelector('meta[name="csrf-token"]').content;
                const payload = { threads: this.selectedThreads, ...extraData };
                const res = await fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json',
                        'X-CSRF-TOKEN': token,
                    },
                    body: JSON.stringify(payload),
                });
                const data = await res.json();
                if (!data.success) return alert(data.message || 'Operation failed');
                if (replaceThreads && data.threads) {
                    this.threads = data.threads;
                } else {
                    this.fetchThreads();
                }
            } catch (err) {
                console.error('Error:', err);
            }
        },

        async _deleteThreads(url) {
            try {
                const token = document.querySelector('meta[name="csrf-token"]').content;
                const res = await fetch(url, {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json',
                        'Accept': 'application/json',
                        'X-CSRF-TOKEN': token,
                    },
                    body: JSON.stringify({ threads: this.selectedThreads }),
                });
                const data = await res.json();
                if (!data.success) return alert(data.message || 'Operation failed');
                this.fetchThreads();
            } catch (err) {
                console.error('Error:', err);
            }
        },

        _gatherSelectedDropdown() {
            const dropdown = document.querySelector('select[name="assign"]');
            if (!dropdown) return;
            return dropdown.value;
        },
    }
}
</script>
