<template>
    <v-card>
        <v-card-title class="text-h6 font-weight-bold">
            Manage Company Settings
        </v-card-title>

        <v-divider />

        <v-card-text v-if="loading">Loading...</v-card-text>

        <v-card-text v-else-if="!canManage">
            <v-alert type="info" variant="tonal">
                Only company owner can update settings.
            </v-alert>
        </v-card-text>

        <v-card-text v-else>

            <!-- 🔹 Company Info -->
            <div class="mb-6">
                <h3 class="text-subtitle-1 font-weight-bold mb-3">Company Info</h3>

                <v-row>
                    <v-col cols="12" md="6">
                        <v-text-field
                            v-model="form.name"
                            label="Company Name"
                            variant="outlined"
                            density="comfortable"
                        />
                    </v-col>

                    <v-col cols="12" md="6">
                        <v-select
                            v-model="form.organizationTimezone"
                            :items="timezoneOptions"
                            label="Timezone"
                            variant="outlined"
                            item-title="title"
                            item-value="value"
                        />
                    </v-col>
                </v-row>
            </div>

            <!-- 🔹 Work Expectations -->
            <div class="mb-6">
                <h3 class="text-subtitle-1 font-weight-bold mb-3">Work Expectations</h3>

                <v-row>
                    <v-col cols="12" md="4">
                        <v-select
                            v-model="form.expectedWorkMinutes"
                            :items="workMinuteOptions"
                            label="Work Hours"
                            variant="outlined"
                            density="comfortable"
                            item-title="label"
                            item-value="value"
                        />
                    </v-col>

                    <v-col cols="12" md="4">
                        <v-select
                            v-model="form.expectedProductiveAppUsageMinutes"
                            :items="workMinuteOptions"
                            label="Productive Time"
                            variant="outlined"
                            density="comfortable"
                            item-title="label"
                            item-value="value"
                        />
                    </v-col>

                    <v-col cols="12" md="4">
                        <v-select
                            v-model="form.expectedActiveMinutes"
                            :items="workMinuteOptions"
                            label="Active Time"
                            variant="outlined"
                            density="comfortable"
                            item-title="label"
                            item-value="value"
                        />
                    </v-col>
                </v-row>

                <v-row>
                    <v-col cols="12" md="4">
                        <v-menu v-model="timeMenu" :close-on-content-click="false">
                            <template #activator="{ props }">
                                <v-text-field
                                    v-bind="props"
                                    :model-value="formattedTime"
                                    variant="outlined"
                                    label="Start Time"
                                    readonly
                                />
                            </template>

                            <v-time-picker
                                v-model="form.expectedStartWork"
                                variant="outlined"
                                format="ampm"
                            />
                        </v-menu>
                    </v-col>
                </v-row>
            </div>

            <!-- 🔹 Tracking Rules -->
            <div class="mb-6">
                <h3 class="text-subtitle-1 font-weight-bold mb-3">Tracking Rules</h3>

                <v-row>
                    <v-col cols="12" md="4">
                        <v-select
                            v-model="form.idleThresholdSeconds"
                            :items="idleOptions"
                            label="Idle Threshold"
                            hint="Marks user idle after inactivity"
                            persistent-hint
                            variant="outlined"
                            density="comfortable"
                            item-title="label"
                            item-value="value"
                        />
                    </v-col>
                </v-row>
            </div>

            <!-- Action -->
            <v-btn color="primary" :loading="saving" @click="save">
                Save Changes
            </v-btn>

        </v-card-text>
    </v-card>
</template>

<script setup>
import { computed, ref, watch } from "vue"
import { useStore } from "vuex"

const store = useStore()

const organization = computed(() => store.getters["auth/organization"])
const canManage = computed(() => store.getters["auth/canManageMembers"])
const loading = computed(() => store.state.auth.loadingOrganization)
const saving = ref(false)

const form = ref({
    name: "",
    idleThresholdSeconds: 180,
    expectedWorkMinutes: 480,
    expectedProductiveAppUsageMinutes: 360,
    expectedActiveMinutes: 420,
    organizationTimezone: "UTC",
    expectedStartWork: "09:00"
})

const idleOptions = [
    { label: "1 minute", value: 60 },
    { label: "2 minutes", value: 120 },
    { label: "3 minutes", value: 180 },
    { label: "5 minutes", value: 300 },
    { label: "10 minutes", value: 600 },
    { label: "15 minutes", value: 900 },
    { label: "20 minutes", value: 1200 },
    { label: "30 minutes", value: 1800 },
    { label: "60 minutes", value: 3600 },
    { label: "90 minutes", value: 5400 },
    { label: "120 minutes", value: 7200 }
]

const timeMenu = ref(false)

const workMinuteOptions = []

for (let i = 15; i <= 15 * 60; i += 15) {
    const hours = Math.floor(i / 60)
    const minutes = i % 60

    let label = ''
    if (hours > 0) label += `${hours} hour${hours > 1 ? 's' : ''} `
    if (minutes > 0) label += `${minutes} mins`

    workMinuteOptions.push({
        label: label.trim(),
        value: i
    })
}

const timezoneOptions = [
    { title: 'UTC', value: 'UTC' },
    { title: 'IST (Asia/Kolkata)', value: 'Asia/Kolkata' },
    { title: 'US Eastern', value: 'America/New_York' },
    { title: 'US Pacific', value: 'America/Los_Angeles' },
    { title: 'Europe London', value: 'Europe/London' }
]

watch(organization, (org) => {
    if (!org || !org.id) return
        form.value = {
            name: org.name || "",
            idleThresholdSeconds: Number(org.idleThresholdSeconds || 180),
            expectedWorkMinutes: Number(org.expectedWorkMinutes || 480),
            expectedProductiveAppUsageMinutes: Number(org.expectedProductiveAppUsageMinutes || 360),
            expectedActiveMinutes: Number(org.expectedActiveMinutes || 420),
            organizationTimezone: org.organizationTimezone || "UTC",
            expectedStartWork: org.expectedStartWork || "09:00"
        }
    },
    { immediate: true }
)

async function save() {
    if (!canManage.value) return

    saving.value = true
    try {
        await store.dispatch("auth/updateOrganization", {
            name: form.value.name,
            idleThresholdSeconds: Math.max(
                1,
                Number(form.value.idleThresholdSeconds) || 180
            ),
            expectedWorkMinutes: Math.max(1, Number(form.value.expectedWorkMinutes) || 480),
            expectedProductiveAppUsageMinutes: Math.max(0, Number(form.value.expectedProductiveAppUsageMinutes) || 0),
            expectedActiveMinutes: Math.max(0, Number(form.value.expectedActiveMinutes) || 0),
            organizationTimezone: String(form.value.organizationTimezone || "UTC"),
            expectedStartWork: String(form.value.expectedStartWork).trim()
        })
    } finally {
        saving.value = false
    }
}

const formattedTime = computed(() => {
    if (!form.value.expectedStartWork) return ''

    const [hour, minute] = form.value.expectedStartWork.split(':')
    const h = Number(hour)

    const ampm = h >= 12 ? 'PM' : 'AM'
    const formattedHour = ((h + 11) % 12 + 1)

    return `${formattedHour.toString().padStart(2, '0')}:${minute} ${ampm}`
})
</script>
