<template>
    <v-row>
        <!-- LEFT SIDEBAR -->
        <v-col cols="12" md="3" lg="2.5">
            <v-card variant="outlined" class="pa-2 h-100 d-flex flex-column">
                <!-- Search -->
                <v-text-field
                    v-model="memberSearch"
                    placeholder="Search members"
                    density="compact"
                    variant="outlined"
                    hide-details
                    class="mb-2 flex-grow-0"
                />

                <!-- Member List -->
                <div
                    class="member-list flex-grow-1"
                    @scroll="onScroll"
                    ref="memberListRef"
                >
                    <v-list density="compact">
                        <v-list-item
                            v-for="member in members"
                            :key="member.id"
                            :active="selectedUserId === member.id"
                            @click="selectMember(member)"
                            rounded="lg"
                        >
                            <v-list-item-title>
                                {{ member.displayName || member.email }}
                            </v-list-item-title>
                        </v-list-item>
                        <v-list-item v-if="membersLoading">
                            <v-list-item-title>Loading...</v-list-item-title>
                        </v-list-item>

                        <v-list-item v-if="!hasMore && members.length">
                            <v-list-item-title class="text-caption text-center">
                                No more members
                            </v-list-item-title>
                        </v-list-item>
                    </v-list>
                </div>

            </v-card>
        </v-col>
        <v-col cols="12" md="9" lg="9.5">
            <!-- Header -->
            <v-row class="mb-4 align-center">
                <v-col cols="auto">
                    <h2 class="text-h6 font-weight-bold">My Work</h2>
                </v-col>

                <v-spacer/>

                <v-col cols="auto">
                    <v-text-field
                        v-model="selectedDate"
                        type="date"
                        density="compact"
                        variant="outlined"
                        label="Select Date"
                        style="max-width: 220px"
                    />
                </v-col>
            </v-row>

            <!-- Metrics -->
            <v-row>
                <v-col
                    cols="12"
                    sm="6"
                    md="4"
                    lg="2.4"
                    v-for="card in metricCards"
                    :key="card.title"
                >
                    <v-card variant="outlined" class="pa-3 h-100 d-flex flex-column justify-space-between">
                        <div class="text-caption text-medium-emphasis mb-1">
                            {{ card.title }}
                        </div>

                        <div class="text-h6 font-weight-bold mb-2">
                            {{ card.value }}
                        </div>

                        <!-- Description -->
                        <div class="text-caption text-disabled">
                            {{ card.description }}
                        </div>
                    </v-card>
                </v-col>
            </v-row>
            <v-row>
                <v-col>
                    <div>
                        <TopApplicationsChart
                            class="h-100"
                            :apps="applications"
                        />
                    </div>
                </v-col>
                <v-col>
                    <div>
                        <TopBrowserHostsChart
                            class="h-100"
                            :hosts="topBrowserHosts"
                        />
                    </div>
                </v-col>
            </v-row>
        </v-col>
    </v-row>
</template>

<script setup>
import axios from "axios"
import {computed, ref, watch} from "vue"
import {useStore} from "vuex"
import {apiEndpoints} from "../apiEndpoints"
import TopApplicationsChart from "../components/TopApplicationsChart.vue";
import TopBrowserHostsChart from "../components/TopBrowserHostsChart.vue";

const metrics = ref({})
const applications = ref([])
const topBrowserHosts = ref([])
const store = useStore()

const members = ref([])
const memberSearch = ref("")
const selectedUserId = ref(null)
const membersLoading = ref(false)
const page = ref(1)
const hasMore = ref(true)
const perPage = 20

const organizationId = computed(() => store.state.auth.organization?.id)
const user = computed(() => store.state.auth.user)

// Default today (YYYY-MM-DD)
const selectedDate = ref(new Date().toISOString().slice(0, 10))

async function fetchMembers(reset = false) {
    if (!organizationId.value || membersLoading.value) return

    if (reset) {
        page.value = 1
        hasMore.value = true
    }

    if (!hasMore.value) return

    membersLoading.value = true

    try {
        const { data } = await axios.get(
            apiEndpoints.organizations.members(organizationId.value),
            {
                params: {
                    page: page.value,
                    perPage,
                    search: memberSearch.value || undefined,
                },
            }
        )

        const newMembers = data?.data || []

        if (reset) {
            members.value = newMembers
        } else {
            members.value.push(...newMembers) // ✅ append
        }

        // Stop if no more data
        if (newMembers.length < perPage) {
            hasMore.value = false
        } else {
            page.value++
        }

        // Auto select loggedin user
        if (!selectedUserId.value && members.value.length) {
            const loggedInUserId = user.value?.id

            const found = members.value.find(m => m.id === loggedInUserId)

            if (found) {
                selectMember(found)   // ✅ select logged-in user
            } else {
                selectMember(members.value[0]) // fallback
            }
        }

    } catch (e) {
        console.error(e)
    } finally {
        membersLoading.value = false
    }
}

function selectMember(member) {
    selectedUserId.value = member.id

    // Replace this line 👇
    // const user = computed(() => store.state.auth.user)

    fetchDashboard()
}

/**
 * ⏱ Convert seconds → "2h 30m"
 */
function formatDuration(seconds) {
    if (!seconds && seconds !== 0) return "-"

    const h = Math.floor(seconds / 3600)
    const m = Math.floor((seconds % 3600) / 60)

    return `${h}h ${m}m`
}

/**
 * 🕒 Format ISO → local readable
 */
function formatDateTime(value) {
    if (!value) return "-"
    return new Date(value).toLocaleTimeString([], {
        hour: "2-digit",
        minute: "2-digit",
    })
}

const metricCards = computed(() => [
    {
        title: "Total Worked",
        value: formatDuration(metrics.value.totalWorkedSeconds),
        description: "Total tracked time for the selected day",
    },
    {
        title: "Active Time",
        value: formatDuration(metrics.value.activeWorkedSeconds),
        description: "Time spent actively working (keyboard/mouse activity)",
    },
    {
        title: "Idle Time",
        value: formatDuration(metrics.value.idleWorkedSeconds),
        description: "Time with no activity detected",
    },
    {
        title: "Idle Time (%)",
        value: metrics.value.idleTimeSpentPercentage + " %",
        description: "Percentage of idle time out of total tracked time",
    },
    {
        title: "Start Time",
        value: formatDateTime(metrics.value.workStartedAt),
        description: "First recorded activity of the day",
    },
    {
        title: "End Time",
        value: formatDateTime(metrics.value.workEndedAt),
        description: "Last recorded activity of the day",
    },
])

async function fetchDashboard() {
    if (!organizationId.value || !selectedUserId.value) return

    try {
        const res = await axios.get(
            apiEndpoints.organizations.memberMetrics(
                organizationId.value,
                selectedUserId.value   // ✅ FIXED
            ),
            {
                params: {
                    date: selectedDate.value,
                },
            }
        )

        metrics.value = res.data

        const appsRes = await axios.get(
            apiEndpoints.organizations.memberApplications(
                organizationId.value,
                selectedUserId.value
            ),
            {
                params: {
                    date: selectedDate.value,
                },
            }
        )

        applications.value = appsRes.data.items || []

        const browserRes = await axios.get(
            apiEndpoints.organizations.memberBrowserHosts(
                organizationId.value,
                selectedUserId.value
            ),
            {
                params: {
                    date: selectedDate.value,
                },
            }
        )

        topBrowserHosts.value = browserRes.data.data || []
    } catch (error) {
        console.error(error)
    }
}

const memberListRef = ref(null)

function onScroll() {
    const el = memberListRef.value
    if (!el || membersLoading.value || !hasMore.value) return

    const threshold = 50

    if (el.scrollTop + el.clientHeight >= el.scrollHeight - threshold) {
        fetchMembers() // load next page
    }
}

watch(
    [organizationId, selectedUserId, selectedDate],
    ([orgId, userId]) => {
        if (orgId && userId) {
            fetchDashboard()
        }
    },
    { immediate: true }
)

watch(
    organizationId,
    (orgId) => {
        if (orgId) {
            fetchMembers()
        }
    },
    { immediate: true }
)

let timeout = null

watch(memberSearch, () => {
    clearTimeout(timeout)

    timeout = setTimeout(() => {
        fetchMembers(true) // ✅ reset
    }, 400)
})

</script>

<style scoped>
.member-list {
    overflow-y: auto;
    max-height: calc(100vh - 200px);
    min-height: 0;
}
</style>
