<template>
    <v-row no-gutters>
        <v-expansion-panels multiple v-model="openPanels" >

            <!-- Work Order Settings -->
            <v-expansion-panel color="primary">
                <v-expansion-panel-title>
                    <v-icon class="mr-2">mdi-format-list-numbered</v-icon>
                    Work Order Settings
                </v-expansion-panel-title>

                <v-expansion-panel-text>
                    <v-text-field v-model="prefix" label="Prefix" :disabled="isLoading || !canManageSiteSettings"
                        @input="handleInput" />

                    <v-select v-model="noOfDigits" :items="[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" label="No. of Digits"
                        :disabled="isLoading || !canManageSiteSettings" />

                    <v-text-field v-model="orderNumberPreview" label="Preview" readonly />

                    <v-btn v-if="canManageSiteSettings" class="mt-2" :loading="isLoading" @click="save">
                        Save
                    </v-btn>
                </v-expansion-panel-text>
            </v-expansion-panel>

        </v-expansion-panels>

        <Snackbar v-model="toast.show" :text="toast.message" :color="toast.color" />
    </v-row>
</template>

<script setup lang="ts">
const props = defineProps({
    siteId: { type: String, required: true },
    canManageSiteSettings: { type: Boolean, default: false },
    service: { type: String, required: true }
})

const openPanels = ref([0]) // default open first

const { getSiteById, updateSitebyId } = useSiteSettings()
const { requiredRule } = useUtils()
const { getFileUrl } = useFile()
const { getWorkOrderSettings, createWorkOrderSettings } = useWorkOrder()

const blocks = ref(0)
const guardPosts = ref(0)
const gracePeriod = ref(0)

const existingBlockNumber = ref(0)
const existingGuardPostNumber = ref(0)
const existingGracePeriodNumber = ref(0)

const gracePeriodValid = ref(false)
const gracePeriodLoading = ref(false)
const deliveryCompanies = ref<string[]>([])

const siteLogo = ref<any[]>([])
const uploadedSiteLogo = ref("")

const prefix = ref("")
const noOfDigits = ref(1)
const isLoading = ref(false)

const toast = reactive({
    show: false,
    message: "",
    color: ""
})

const { data: siteData, refresh: refreshSiteData } = await useLazyAsyncData(
    `site-${props.siteId}`,
    () => getSiteById(props.siteId)
)

watch(siteData, (val: TSite) => {
    if (!val) return

    blocks.value = val.metadata?.block || 0
    guardPosts.value = val.metadata?.guardPosts || 0
    gracePeriod.value = val.metadata?.gracePeriod || 0

    existingBlockNumber.value = blocks.value
    existingGuardPostNumber.value = guardPosts.value
    existingGracePeriodNumber.value = gracePeriod.value
    deliveryCompanies.value = Array.isArray(val.deliveryCompanyList) ? [...val.deliveryCompanyList] : []

    uploadedSiteLogo.value = val.metadata?.incidentLogo || ""
}, { immediate: true })

async function handleSaveGracePeriod() {
    gracePeriodLoading.value = true
    try {
        await updateSitebyId(props.siteId, {
            field: "metadata.gracePeriod",
            value: gracePeriod.value
        })
        show("Grace period updated", "success")
        refreshSiteData()
    } catch (e: any) {
        show(e?.data?.message || "Error updating grace period", "error")
    } finally {
        gracePeriodLoading.value = false
    }
}

async function handleLogo(action: string) {
    try {
        await updateSitebyId(props.siteId, {
            field: "metadata.incidentLogo",
            value: action === "add" ? siteLogo.value[0] : 0
        })
        show("Logo updated", "success")
        refreshSiteData()
    } catch {
        show("Error updating logo", "error")
    } finally {
        siteLogo.value = []
    }
}

const onUploadedLogoPreview = () => {
    if (!uploadedSiteLogo.value) return ""
    return getFileUrl(uploadedSiteLogo.value)
}

const { data: workOrderSetting } = await useLazyAsyncData(
    `work-${props.siteId}`,
    () => getWorkOrderSettings({ site: props.siteId, service: props.service })
)

watchEffect(() => {
    if (workOrderSetting.value) {
        prefix.value = workOrderSetting.value.prefix
        noOfDigits.value = workOrderSetting.value.noOfDigits
    }
})

function handleInput(e: any) {
    prefix.value = e.target.value
        .replace(/[^A-Z]/g, "")
        .toUpperCase()
}

function handleUpdateCompanies(value: string[]) {
    deliveryCompanies.value = value
}

const orderNumberPreview = computed(() => {
    return `${prefix.value}${"0".repeat(noOfDigits.value - 1)}1`
})

async function save() {
    try {
        isLoading.value = true
        await createWorkOrderSettings({
            site: props.siteId,
            service: props.service,
            prefix: prefix.value,
            noOfDigits: noOfDigits.value
        })
        show("Saved successfully", "success")
    } catch {
        show("Error saving", "error")
    } finally {
        isLoading.value = false
    }
}

function show(message: string, color: string) {
    toast.show = true
    toast.message = message
    toast.color = color
}
</script>