<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="Number List"
                            page-modal-title="Add / Edit Phone Number"
                            :default-object="{ group_id: 0, is_bulk: false }"
                            :default-add-button="can('number_list_add')"
                        ></page-top>
                    </template>

                    <template v-slot:filter>
                        <!-- Search Keyword Filter -->
                        <div class="col-md-3 col-sm-6 mb-2">
                            <div class="input-group input-group-sm">
                                <span class="input-group-text"><i class="fa fa-search"></i></span>
                                <input
                                    type="text"
                                    class="form-control"
                                    v-model="formFilter.keyword"
                                    placeholder="Search by Phone, Name or Notes..."
                                    @input="debounceSearch"
                                />
                            </div>
                        </div>

                        <!-- Group Filter Dropdown -->
                        <div class="col-md-3 col-sm-6 mb-2">
                            <select
                                class="form-select form-control form-control-sm"
                                v-model="formFilter.group_id"
                                @change="getDataList(1)"
                            >
                                <option value="">-- All Groups --</option>
                                <option value="0">-- Unassigned (No Group) --</option>
                                <option
                                    v-for="grp in groupList"
                                    :key="grp.id"
                                    :value="grp.id"
                                >
                                    {{ grp.name || grp.group_name }} ({{ grp.numbers_count ?? grp.total_number ?? 0 }})
                                </option>
                            </select>
                        </div>

                        <!-- Reset Filter Button -->
                        <div class="col-md-2 col-sm-4 mb-2">
                            <button
                                v-if="formFilter.keyword || formFilter.group_id !== ''"
                                class="btn btn-sm btn-outline-secondary w-100"
                                @click="resetFilter"
                            >
                                <i class="fa fa-times me-1"></i> Clear Filter
                            </button>
                        </div>
                    </template>

                    <template v-slot:data>
                        <tr v-for="(data, index) in dataList.data" :key="data.id">
                            <td class="fw-medium text-muted">{{ parseInt(dataList.from || 1) + index }}</td>
                            <td>
                                <div class="d-flex align-items-center gap-2">
                                    <div class="avatar-xs rounded-circle bg-light d-flex align-items-center justify-content-center text-primary fw-bold">
                                        {{ (data.name ? data.name[0] : '#').toUpperCase() }}
                                    </div>
                                    <div>
                                        <strong class="d-block text-dark">{{ data.name || 'Unnamed Contact' }}</strong>
                                    </div>
                                </div>
                            </td>
                            <td>
                                <span class="fw-bold font-monospace text-dark">{{ data.number || data.phone }}</span>
                            </td>
                            <td>
                                <template v-if="data.group">
                                    <span class="badge rounded-pill px-2 py-1 text-white" :style="{ backgroundColor: data.group.color || '#246bfd' }">
                                        <i class="fa fa-users me-1"></i> {{ data.group.name }}
                                    </span>
                                </template>
                                <template v-else>
                                    <span class="badge bg-secondary-subtle text-secondary rounded-pill px-2 py-1">
                                        Unassigned
                                    </span>
                                </template>
                            </td>
                            <td>
                                <span class="text-muted small text-truncate d-inline-block" style="max-width: 200px;" :title="data.notes">
                                    {{ data.notes || '-' }}
                                </span>
                            </td>
                            <td>{{ formatDate(data.created_at) }}</td>
                            <td>
                                <router-link
                                    :to="`/admin/sms_messages?recipient=${encodeURIComponent(data.number || data.phone)}`"
                                    class="btn btn-sm btn-outline-primary py-0 px-2"
                                    title="Send Direct SMS"
                                >
                                    <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-primary"
                                        v-if="can('number_list_update')"
                                        @click="editNumber(data)"
                                        title="Edit Contact"
                                    >
                                        <i class="fa fa-edit"></i>
                                    </a>
                                    <a
                                        class="btn btn-sm btn-icon btn-light text-danger"
                                        v-if="can('number_list_delete')"
                                        @click="deleteInformation(index, data.id)"
                                        title="Delete Contact"
                                    >
                                        <i class="fa fa-trash"></i>
                                    </a>
                                </div>
                            </td>
                        </tr>
                        <tr v-if="!dataList.data || dataList.data.length === 0">
                            <td colspan="8" class="text-center py-5 text-muted">
                                <i class="fa fa-address-book fa-3x mb-2 d-block text-black-50"></i>
                                No contact numbers found. Click "Add Number" to start adding contacts.
                            </td>
                        </tr>
                    </template>
                </data-table>
            </div>
        </div>

        <!-- Add / Edit Number Modal -->
        <formModal modal-size="modal-md" modal-id="formModal" @submit="submitNumberForm()">
            <NumberForm></NumberForm>
        </formModal>
    </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 NumberForm from "./NumberForm";
import axios from "axios";

export default {
    name: "NumberList",
    components: { PageTop, Pagination, DataTable, formModal, NumberForm },
    data() {
        return {
            tableHeading: ['Sl', 'Contact Name', 'Phone Number', 'Group', 'Notes', 'Created At', 'Send SMS', 'Action'],
            groupList: [],
            searchTimer: null
        };
    },
    methods: {
        async fetchGroups() {
            try {
                const response = await axios.get('/api/groups', { params: { perPage: 100 } });
                if (response.data && response.data.status === 2000) {
                    this.groupList = response.data.result.data || response.data.result || [];
                }
            } catch (err) {
                console.error('Failed to load groups for filter:', err);
            }
        },
        debounceSearch() {
            clearTimeout(this.searchTimer);
            this.searchTimer = setTimeout(() => {
                this.getDataList(1);
            }, 300);
        },
        resetFilter() {
            this.formFilter.keyword = '';
            this.formFilter.group_id = '';
            this.getDataList(1);
        },
        editNumber(data) {
            this.formObject.id = data.id;
            this.formObject.number = data.number || data.phone;
            this.formObject.name = data.name || '';
            this.formObject.group_id = data.group_id || 0;
            this.formObject.notes = data.notes || '';
            this.editData(data, data.id);
        },
        submitNumberForm() {
            const _this = this;
            if (!_this.formObject.number && !_this.formObject.bulk_numbers) {
                _this.$toastr('warning', 'Phone number is required', 'Warning');
                return;
            }
            _this.submitForm(_this.formObject, 'formModal', function(retData) {
                _this.getDataList(1);
                _this.fetchGroups();
            }, false, false, {});
        },
        formatDate(dateStr) {
            if (!dateStr) return '-';
            const d = new Date(dateStr);
            return d.toLocaleDateString();
        }
    },
    mounted() {
        this.fetchGroups();
        this.getDataList();
    }
};
</script>

<style scoped>
.avatar-xs {
    width: 28px;
    height: 28px;
    font-size: 12px;
    flex-shrink: 0;
}
</style>
