<template :key="$route.meta.name">
    <div class="main_component">
        <div class="row">
            <div class="col">
                <data-table :table-heading="tableHeading" :default-filter="false">
                    <template v-slot:page_top>
                        <page-top
                            topPageTitle="Group List"
                            page-modal-title="Create / Edit Group"
                            :default-object="{ color: '#246bfd', number_type: 0 }"
                            :default-add-button="can('group_list_add')"
                        ></page-top>
                    </template>
                    <template v-slot:filter>
                        <div class="col-md-3">
                            <input
                                type="text"
                                class="form-control"
                                v-model="formFilter.group_name"
                                placeholder="Search by Group Name..."
                                @input="searchFilter"
                            />
                        </div>
                    </template>
                    <template v-slot:data>
                        <tr v-for="(data, index) in dataList.data" :key="data.id">
                            <td class="fw-medium">{{ parseInt(dataList.from || 1) + index }}</td>
                            <td>
                                <div class="d-flex align-items-center gap-2">
                                    <span class="color-indicator" :style="{ backgroundColor: data.color || '#246bfd' }"></span>
                                    <span class="fw-bold text-dark">{{ data.name || data.group_name }}</span>
                                </div>
                            </td>
                            <td>
                                <span class="text-muted small">{{ data.description || '-' }}</span>
                            </td>
                            <td>
                                <span class="badge bg-primary-subtle text-primary rounded-pill px-3 py-1 fw-bold fs-12">
                                    {{ data.numbers_count ?? data.total_number ?? data.number_count ?? 0 }} Contacts
                                </span>
                            </td>
                            <td>{{ formatDate(data.created_at) }}</td>
                            <td>
                                <router-link
                                    :to="`/admin/sms_messages?group_id=${data.id}`"
                                    class="btn btn-sm btn-outline-primary"
                                    title="Send Queue SMS to Group"
                                >
                                    <i class="fa fa-paper-plane me-1"></i> Send SMS
                                </router-link>
                            </td>
                            <td>
                                <div class="hstack gap-2 fs-15">
                                    <a
                                        class="btn btn-sm btn-icon btn-light text-info"
                                        @click="openGroupDetails(data)"
                                        title="View Group Contacts"
                                    >
                                        <i class="fa fa-eye"></i>
                                    </a>
                                    <a
                                        class="btn btn-sm btn-icon btn-light text-primary"
                                        v-if="can('group_list_update')"
                                        @click="editGroup(data)"
                                        title="Edit Group"
                                    >
                                        <i class="fa fa-edit"></i>
                                    </a>
                                    <a
                                        class="btn btn-sm btn-icon btn-light text-danger"
                                        v-if="can('group_list_delete')"
                                        @click="deleteInformation(index, data.id)"
                                        title="Delete Group"
                                    >
                                        <i class="fa fa-trash"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <tr v-if="!dataList.data || dataList.data.length === 0">
                            <td colspan="7" class="text-center py-5 text-muted">
                                <i class="fa fa-users fa-3x mb-2 d-block text-black-50"></i>
                                No groups found. Click "Add Group" to create one.
                            </td>
                        </tr>
                    </template>
                </data-table>
            </div>
        </div>

        <!-- Add / Edit Group Modal -->
        <formModal modal-size="modal-md" modal-id="formModal" @submit="submitGroupForm()">
            <GroupForm></GroupForm>
        </formModal>

        <!-- Group Details & Contacts Management Modal -->
        <general-modal modal-id="detailsModal" modal-size="modal-lg">
            <template v-slot:title>
                <div class="d-flex align-items-center gap-2">
                    <span class="color-indicator" :style="{ backgroundColor: activeGroup.color || '#246bfd' }"></span>
                    <span>Contacts in "{{ activeGroup.name || activeGroup.group_name || 'Group' }}"</span>
                </div>
            </template>
            <template v-slot:body>
                <!-- Add New Number Directly to this Group -->
                <form @submit.prevent="addGroupNumber()" class="p-3 bg-light rounded border mb-3">
                    <h6 class="fw-bold mb-2 text-dark"><i class="fa fa-plus-circle text-primary me-1"></i> Add Contact to this Group</h6>
                    <div class="row g-2">
                        <div class="col-md-5">
                            <input
                                class="form-control form-control-sm"
                                type="text"
                                v-model="newNumber"
                                placeholder="Phone Number (e.g. 01712345678)"
                                required
                            />
                        </div>
                        <div class="col-md-4">
                            <input
                                class="form-control form-control-sm"
                                type="text"
                                v-model="newContactName"
                                placeholder="Contact Name (optional)"
                            />
                        </div>
                        <div class="col-md-3">
                            <button type="submit" class="btn btn-sm btn-primary w-100" :disabled="addingNumber">
                                <i v-if="addingNumber" class="fa fa-spinner fa-spin"></i>
                                <i v-else class="fa fa-plus"></i> Add Contact
                            </button>
                        </div>
                    </div>
                </form>

                <!-- Search & Filters in Group Contacts -->
                <div class="row mb-3 align-items-center g-2">
                    <div class="col-md-3 col-sm-4">
                        <select @change="viewData(1)" class="form-select form-control form-control-sm" v-model="perPage">
                            <option v-for="page in [15, 30, 50, 100]" :key="page" :value="page">
                                {{ page }} per page
                            </option>
                        </select>
                    </div>
                    <div class="col-md-6 col-sm-8">
                        <div class="input-group input-group-sm">
                            <span class="input-group-text"><i class="fa fa-search"></i></span>
                            <input
                                type="text"
                                v-model="searchKeyword"
                                class="form-control form-control-sm"
                                placeholder="Search by phone or name..."
                                @input="viewData(1)"
                            />
                        </div>
                    </div>
                    <div class="col-md-3 text-md-end text-sm-start">
                        <router-link :to="`/admin/sms_messages?group_id=${viewId}`" class="btn btn-sm btn-outline-primary w-100">
                            <i class="fa fa-paper-plane me-1"></i> Send SMS
                        </router-link>
                    </div>
                </div>

                <!-- Numbers List Grid -->
                <div class="row g-2 mb-3">
                    <div class="col-md-4 col-sm-6" v-for="(num, idx) in details.data" :key="num.id">
                        <div class="contact-card p-2 rounded border bg-white d-flex align-items-center justify-content-between">
                            <div class="text-truncate me-2">
                                <strong class="d-block text-dark small text-truncate">
                                    {{ num.name || 'Unnamed' }}
                                </strong>
                                <span class="text-muted small font-monospace">{{ num.number || num.phone }}</span>
                            </div>
                            <button
                                type="button"
                                class="btn btn-sm btn-icon btn-link text-danger p-0"
                                @click="deleteSingleNumber(num)"
                                title="Delete Contact"
                            >
                                <i class="fa fa-trash"></i>
                            </button>
                        </div>
                    </div>
                    <div v-if="!details.data || details.data.length === 0" class="col-12 text-center py-4 text-muted">
                        No contacts found in this group.
                    </div>
                </div>

                <!-- Pagination -->
                <pagination previousText="PREV" nextText="NEXT" :data="details" @paginateTo="viewData"></pagination>
            </template>
        </general-modal>
    </div>
</template>

<script>
import DataTable from "../../../components/dataTable";
import Pagination from "../../../plugins/pagination/pagination";
import PageTop from "../../../components/pageTop";
import formModal from "../../../components/formModal";
import GeneralModal from "../../../components/generalModal";
import GroupForm from "./GroupForm";
import axios from "axios";

export default {
    name: "GroupList",
    components: { GeneralModal, PageTop, Pagination, DataTable, formModal, GroupForm },
    data() {
        return {
            tableHeading: ['Sl', 'Group Name', 'Description', 'Total Numbers', 'Created At', 'Send SMS', 'Action'],
            details: {},
            activeGroup: {},
            newNumber: '',
            newContactName: '',
            searchKeyword: '',
            viewId: 0,
            perPage: 30,
            addingNumber: false,
            searchTimer: null
        }
    },
    methods: {
        searchFilter() {
            clearTimeout(this.searchTimer);
            this.searchTimer = setTimeout(() => {
                this.getDataList(1);
            }, 300);
        },
        editGroup(data) {
            this.formObject.id = data.id;
            this.formObject.name = data.name || data.group_name;
            this.formObject.group_name = data.name || data.group_name;
            this.formObject.description = data.description || '';
            this.formObject.color = data.color || '#246bfd';
            this.formObject.number_type = 0;
            this.editData(data, data.id);
        },
        openGroupDetails(data) {
            this.activeGroup = data;
            this.viewId = data.id;
            this.openModal('detailsModal', false);
            this.viewData(1, data.id);
        },
        submitGroupForm() {
            const _this = this;
            if (!_this.formObject.name && !_this.formObject.group_name) {
                _this.$toastr('warning', 'Group Name is required', 'Warning');
                return;
            }
            _this.submitForm(_this.formObject, 'formModal', function(retData) {
                _this.getDataList(1);
            }, false, false, {});
        },
        deleteSingleNumber(num) {
            const _this = this;
            const URL = `${_this.urlGenerate('api/groups/delete_single_number')}/${num.id}`;
            axios.delete(URL).then(function (response) {
                if (parseInt(response.data.status) === 2000) {
                    _this.$toastr('success', response.data.message || 'Contact deleted', 'Success');
                    _this.viewData(_this.details.current_page || 1);
                    _this.getDataList(_this.currentPagination);
                } else {
                    _this.$toastr('warning', response.data.message, 'Warning');
                }
            }).catch(err => {
                _this.$toastr('error', 'Failed to delete contact', 'Error');
            });
        },
        viewData(page = 1, groupId = null) {
            const _this = this;
            if (groupId) {
                _this.viewId = groupId;
            }
            const detailUrl = `${_this.urlGenerate()}/${_this.viewId}`;
            _this.getData(detailUrl, "get", {
                page: page,
                perPage: _this.perPage,
                keyword: _this.searchKeyword
            }, {}, function (retData) {
                _this.details = retData;
            });
        },
        async addGroupNumber() {
            if (!this.newNumber) return;
            const _this = this;
            _this.addingNumber = true;
            try {
                const detailUrl = `${_this.urlGenerate()}/${_this.viewId}`;
                const dataObj = {
                    number: _this.newNumber,
                    phone: _this.newNumber,
                    name: _this.newContactName,
                    id: _this.viewId,
                    operation: 'add_number'
                };
                const response = await axios.put(detailUrl, dataObj);
                if (parseInt(response.data.status) === 2000) {
                    _this.$toastr('success', 'Contact added to group', 'Success');
                    _this.newNumber = '';
                    _this.newContactName = '';
                    _this.viewData(1);
                    _this.getDataList(_this.currentPagination);
                } else {
                    _this.$toastr('warning', response.data.message || 'Could not add contact', 'Warning');
                }
            } catch (err) {
                _this.$toastr('error', 'Failed to add contact to group', 'Error');
            } finally {
                _this.addingNumber = false;
            }
        },
        formatDate(dateStr) {
            if (!dateStr) return '-';
            const d = new Date(dateStr);
            return d.toLocaleDateString();
        }
    },
    mounted() {
        this.getDataList();
    }
}
</script>

<style scoped>
.color-indicator {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    display: inline-block;
    flex-shrink: 0;
}
.contact-card {
    transition: all 0.15s ease;
    border: 1px solid #e2e8f0;
}
.contact-card:hover {
    border-color: #94a3b8;
    background-color: #f8fafc !important;
}
</style>
