<template>
    <v-card>
        <v-card-title class="px-4 py-3">
            <div class="d-flex align-center justify-space-between flex-wrap ga-3 w-100">
                <div class="text-h6 font-weight-medium">
                    Manage Employees
                </div>
                <div class="d-flex align-center ga-2 flex-wrap">

                    <!-- Search -->
                    <v-text-field
                        v-model="search"
                        placeholder="Search employees..."
                        density="compact"
                        variant="outlined"
                        clearable
                        hide-details
                        prepend-inner-icon="mdi-magnify"
                        style="width: 250px"
                    />

                    <!-- Add User -->
                    <v-btn
                        v-if="canManage"
                        color="primary"
                        variant="flat"
                        @click="createDialog = true"
                    >
                        <v-icon start>mdi-plus</v-icon>
                        Add User
                    </v-btn>

                </div>
            </div>
        </v-card-title>

        <v-card-text v-if="!canManage">
            <v-alert type="info" variant="tonal">Only organization owner or admin can manage members.</v-alert>
        </v-card-text>
        <v-data-table-server
            :headers="headers"
            :items="members"
            :items-length="total"
            v-model:options="options"
            v-model:sort-by="options.sortBy"
            multi-sort
        >
            <template #item.isActive="{ item }">
                <v-chip :color="item.isActive ? 'success' : 'error'" size="small">{{ item.isActive ? "Active" : "Inactive" }}</v-chip>
            </template>
            <template #item.organizationRole="{ item }">
                <v-chip :color="roleColor(item.organizationRole)" size="small">
                    {{ roleLabel(item.organizationRole) }}
                </v-chip>
            </template>
            <template #item.actions="{ item }">
                <div class="d-flex ga-2">
                    <v-btn v-if="canManage" size="small" variant="tonal" @click="openEditDialog(item)">Edit</v-btn>
                    <v-btn v-if="canManage" size="small" :color="item.isActive ? 'error' : 'success'" variant="tonal" @click="toggleMemberStatus(item)">
                        {{ item.isActive ? "Inactive" : "Active" }}
                    </v-btn>
                    <span v-if="!canManage">-</span>
                </div>
            </template>
        </v-data-table-server>

        <v-dialog v-model="createDialog" max-width="520">
            <v-card>
                <v-card-title>Create Member</v-card-title>
                <v-card-text>
                    <v-alert v-if="createError" type="error" variant="tonal" class="mb-3">{{ createError }}</v-alert>
                    <v-text-field v-model="createForm.employeeCode" variant="outlined" label="Employee Code" density="comfortable" />
                    <v-text-field v-model="createForm.displayName" variant="outlined" label="Display Name" density="comfortable" />
                    <v-text-field v-model="createForm.email" variant="outlined" label="Email" density="comfortable" />
                    <v-text-field v-model="createForm.password" variant="outlined" label="Password" type="password" density="comfortable" />
                    <v-select
                        v-model="createForm.organizationRole"
                        :items="roleOptions"
                        item-title="label"
                        item-value="value"
                        variant="outlined"
                        label="Organization Role"
                        density="comfortable"
                    />
                </v-card-text>
                <v-card-actions>
                    <v-spacer />
                    <v-btn variant="text" @click="closeCreateDialog">Cancel</v-btn>
                    <v-btn color="primary" :loading="creating" @click="createMember">Create</v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>

        <v-dialog v-model="editDialog" max-width="520">
            <v-card>
                <v-card-title>Edit Member</v-card-title>
                <v-card-text>
                    <v-alert v-if="editError" type="error" variant="tonal" class="mb-3">{{ editError }}</v-alert>
                    <v-text-field v-model="editForm.employeeCode" variant="outlined" label="Employee Code" density="comfortable" />
                    <v-switch v-model="editForm.isActive" variant="outlined" color="primary" :label="editForm.isActive ? 'Active' : 'Inactive'" />
                    <v-select
                        v-model="editForm.organizationRole"
                        :items="roleOptions"
                        item-title="label"
                        item-value="value"
                        variant="outlined"
                        label="Organization Role"
                        density="comfortable"
                    />
                </v-card-text>
                <v-card-actions>
                    <v-spacer />
                    <v-btn variant="text" @click="closeEditDialog">Cancel</v-btn>
                    <v-btn color="primary" :loading="savingEdit" @click="saveMember">Save</v-btn>
                </v-card-actions>
            </v-card>
        </v-dialog>
    </v-card>
</template>

<script setup>
import axios from "axios"
import { computed, ref, watch } from "vue"
import { apiEndpoints } from "../apiEndpoints"
import { useStore } from "vuex"
import { useRoute, useRouter } from "vue-router"

const route = useRoute()
const router = useRouter()
const store = useStore()

/* ---------------------------------- */
/* DEFAULTS */
/* ---------------------------------- */
const DEFAULTS = {
    page: "1",
    perPage: "10",
    sort: "isActive:desc,id:asc"
}

const initialized = ref(false)

/* ---------------------------------- */
/* HELPERS */
/* ---------------------------------- */
function parseSort(sortQuery) {
    return (sortQuery || '').split(",").map(s => {
        const [key, order] = s.split(":")
        return { key, order }
    })
}

function normalizeQuery(query) {
    return {
        page: String(query.page || DEFAULTS.page),
        perPage: String(query.perPage || DEFAULTS.perPage),
        sort: query.sort || DEFAULTS.sort,
        search: query.search || undefined
    }
}

function isSameQuery(a, b) {
    return (
        String(a.page || "") === String(b.page || "") &&
        String(a.perPage || "") === String(b.perPage || "") &&
        String(a.sort || "") === String(b.sort || "") &&
        String(a.search || "") === String(b.search || "")
    )
}

/* ---------------------------------- */
/* STATE */
/* ---------------------------------- */
const organization = computed(() => store.getters["auth/organization"])
const members = ref([])
const total = ref(0)

/* ---------------------------------- */
/* SEARCH (URL DRIVEN) */
/* ---------------------------------- */
const search = computed({
    get: () => route.query.search || "",
    set: (val) => {
        router.replace({
            query: {
                ...route.query,
                search: val || undefined
            }
        })
    }
})

/* ---------------------------------- */
/* TABLE OPTIONS */
/* ---------------------------------- */
const options = computed({
    get() {
        return {
            page: Number(route.query.page),
            itemsPerPage: Number(route.query.perPage),
            sortBy: parseSort(route.query.sort)
        }
    },
    set(val) {
        // BLOCK initial Vuetify emit
        if (!initialized.value) {
            return
        }

        const current = {
            page: Number(route.query.page),
            itemsPerPage: Number(route.query.perPage),
            sortBy: parseSort(route.query.sort)
        }

        if (
            val.page === current.page &&
            val.itemsPerPage === current.itemsPerPage &&
            JSON.stringify(val.sortBy) === JSON.stringify(current.sortBy)
        ) {
            return
        }

        const sortQuery = val.sortBy
            ?.map(s => `${s.key}:${s.order}`)
            .join(",")

        router.replace({
            query: {
                ...route.query,
                page: String(val.page),
                perPage: String(val.itemsPerPage),
                sort: sortQuery
            }
        })
    }
})

/* ---------------------------------- */
/* FETCH (ONLY USE QUERY) */
/* ---------------------------------- */
async function fetchMembers() {
    if (!organization.value?.id) return

    const params = {
        page: Number(route.query.page),
        perPage: Number(route.query.perPage),
        sorting: parseSort(route.query.sort)
    }

    if (route.query.search) {
        params.search = route.query.search
    }

    const { data } = await axios.get(
        apiEndpoints.organizations.members(organization.value.id),
        { params }
    )

    members.value = (data.data || []).map((item) => ({
        ...item,
        isActive: typeof item?.isActive === "boolean" ? item.isActive : false,
        organizationRole: item?.organizationRole || (item?.isAdmin ? "admin" : item?.isManager ? "manager" : "member")
    }))

    total.value = data?.meta?.pagination?.totalItems || 0
}

/* ---------------------------------- */
/* MAIN WATCH (CORE LOGIC) */
/* ---------------------------------- */
watch(
    () => route.query,
    async (q) => {
        const normalized = normalizeQuery(q)

        if (!isSameQuery(q, normalized)) {
            router.replace({ query: normalized })
            return
        }

        // ✅ Allow table updates ONLY after URL is stable
        initialized.value = true

        await fetchMembers()
    },
    { immediate: true }
)

/* ---------------------------------- */
/* REMAINING CODE (UNCHANGED) */
/* ---------------------------------- */

const headers = [
    { title: "Employee ID", key: "id", sortable: true },
    { title: "Employee Code", key: "employeeCode", sortable: true },
    { title: "Name", key: "displayName", sortable: true },
    { title: "Email", key: "email", sortable: true },
    { title: "App Version", key: "appVersion", sortable: true },
    { title: "App Platform", key: "appPlatform", sortable: true },
    { title: "Role", key: "organizationRole", sortable: true },
    { title: "Status", key: "isActive", sortable: true },
    { title: "Actions", key: "actions", sortable: false }
]

const createDialog = ref(false)
const creating = ref(false)
const createError = ref("")
const createForm = ref({
    displayName: "",
    email: "",
    password: "",
    employeeCode: "",
    organizationRole: "member"
})

const editDialog = ref(false)
const savingEdit = ref(false)
const editError = ref("")
const editForm = ref({
    id: null,
    employeeCode: "",
    isActive: true,
    organizationRole: "member"
})

const roleOptions = [
    { label: "Member", value: "member" },
    { label: "Manager", value: "manager" },
    { label: "Admin", value: "admin" }
]

const canManage = computed(() =>
    store.getters["auth/isAdmin"] ||
    store.state.auth.organization?.isOwner ||
    store.state.auth.organization?.isAdmin
)

async function toggleMemberStatus(item) {
    const organizationId = store.state.auth.organization?.id
    if (!organizationId) return

    await axios.put(apiEndpoints.organizations.updateMember(organizationId, item.id), { isActive: !item.isActive })
    await fetchMembers()
}

function openEditDialog(item) {
    editError.value = ""
    editForm.value = {
        id: item.id,
        employeeCode: item.employeeCode || "",
        isActive: Boolean(item.isActive),
        organizationRole: item.organizationRole || (item.isAdmin ? "admin" : item.isManager ? "manager" : "member")
    }
    editDialog.value = true
}

function closeEditDialog() {
    editDialog.value = false
}

async function saveMember() {
    if (!editForm.value.id) return

    savingEdit.value = true
    editError.value = ""

    try {
        const organizationId = store.state.auth.organization?.id
        if (!organizationId) {
            editError.value = "Organization not found"
            return
        }

        await axios.put(apiEndpoints.organizations.updateMember(organizationId, editForm.value.id), {
            isActive: editForm.value.isActive,
            employeeCode: editForm.value.employeeCode,
            organizationRole: editForm.value.organizationRole
        })
        closeEditDialog()
        await fetchMembers()
    } catch (error) {
        editError.value = error?.response?.data?.message || "Unable to update member"
    } finally {
        savingEdit.value = false
    }
}

function closeCreateDialog() {
    createDialog.value = false
    createForm.value = {
        displayName: "",
        email: "",
        password: "",
        employeeCode: "",
        organizationRole: "member"
    }
}

function roleLabel(role) {
    return (role || "member").toString().replace(/^./, (match) => match.toUpperCase())
}

function roleColor(role) {
    if (role === "admin") return "deep-purple"
    if (role === "manager") return "primary"
    return "default"
}

async function createMember() {
    createError.value = ""

    if (!createForm.value.displayName || !createForm.value.email || !createForm.value.password) {
        createError.value = "Display name, email and password are required"
        return
    }

    creating.value = true
    try {
        await axios.post(apiEndpoints.users.create, createForm.value)
        closeCreateDialog()
        await fetchMembers()
    } catch (error) {
        createError.value = error?.response?.data?.message || "Unable to create member"
    } finally {
        creating.value = false
    }
}
</script>
