<template>
    <div
        class="main-container"
        :style="{ backgroundImage: `url(${verifyPurchaseBackground})` }"
    >
        <div class="container-content">
            <a-row type="flex" justify="center">
                <a-col :xs="22" :sm="18" :md="14" :lg="10" :xl="8">
                    <div class="text-center">
                        <a-typography-title :level="4">
                            {{ $t("common.verify_purchase") }}
                        </a-typography-title>
                    </div>

                    <a-divider />

                    <a-alert v-if="successMessage != ''" type="success" show-icon banner>
                        <template #message>
                            <span v-html="successMessage" />
                        </template>
                    </a-alert>
                    <a-alert v-if="errorMessage != ''" type="error" show-icon banner>
                        <template #message>
                            <span v-html="errorMessage" />
                        </template>
                    </a-alert>

                    <!-- Loading state while fetching settings -->
                    <div v-if="settingsLoading" class="text-center mt-20">
                        <a-spin size="large" />
                    </div>

                    <a-form v-else layout="vertical" class="mt-20">
                        <a-form-item
                            :label="$t('common.purchase_code')"
                            name="purchase_code"
                            :help="
                                rules.purchase_code ? rules.purchase_code.message : null
                            "
                            :validateStatus="rules.purchase_code ? 'error' : null"
                            class="required"
                        >
                            <a-input
                                v-model:value="purchaseCode"
                                :placeholder="
                                    $t('common.placeholder_default_text', [
                                        $t('common.purchase_code'),
                                    ])
                                "
                            >
                                <template #prefix>
                                    <SafetyCertificateOutlined />
                                </template>
                            </a-input>
                        </a-form-item>
                        <a-row
                            :gutter="16"
                            v-if="
                                verifySettings.show_email || verifySettings.show_whatsapp
                            "
                        >
                            <a-col
                                v-if="verifySettings.show_email"
                                :xs="24"
                                :sm="24"
                                :md="verifySettings.show_whatsapp ? 12 : 24"
                                :lg="verifySettings.show_whatsapp ? 12 : 24"
                            >
                                <a-form-item
                                    :label="$t('common.email')"
                                    name="email"
                                    :help="rules.email ? rules.email.message : null"
                                    :validateStatus="rules.email ? 'error' : null"
                                    :class="{ required: verifySettings.email_required }"
                                >
                                    <a-input
                                        v-model:value="verifyEmail"
                                        type="email"
                                        :placeholder="
                                            $t('common.placeholder_default_text', [
                                                $t('common.email'),
                                            ])
                                        "
                                    >
                                        <template #prefix>
                                            <MailOutlined />
                                        </template>
                                    </a-input>
                                </a-form-item>
                            </a-col>
                            <a-col
                                v-if="verifySettings.show_whatsapp"
                                :xs="24"
                                :sm="24"
                                :md="verifySettings.show_email ? 12 : 24"
                                :lg="verifySettings.show_email ? 12 : 24"
                            >
                                <a-form-item
                                    :label="$t('common.whatsapp_number')"
                                    name="whatsapp_number"
                                    :help="
                                        rules.whatsapp_number
                                            ? rules.whatsapp_number.message
                                            : null
                                    "
                                    :validateStatus="
                                        rules.whatsapp_number ? 'error' : null
                                    "
                                    :class="{
                                        required: verifySettings.whatsapp_required,
                                    }"
                                >
                                    <PhoneInput
                                        v-model="whatsappNumber"
                                        size="default"
                                        selectWidth="100px"
                                        :placeholder="
                                            $t('common.placeholder_default_text', [
                                                $t('common.whatsapp_number'),
                                            ])
                                        "
                                    />
                                </a-form-item>
                            </a-col>
                        </a-row>
                        <a-form-item>
                            <a-button type="primary" @click="verify" :loading="loading">
                                {{ $t("common.verify_purchase") }}
                            </a-button>
                        </a-form-item>
                    </a-form>
                </a-col>
            </a-row>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { SafetyCertificateOutlined, MailOutlined } from "@ant-design/icons-vue";
import axios from "axios";
import modules from "../../../common/composable/modules";
import { useModuleVerificationStore } from "../../verification";

const verifyPurchaseBackground = window.config.verify_purchase_background;
const router = useRouter();
const verificationStore = useModuleVerificationStore();
const {
    rules,
    purchaseCode,
    verifyEmail,
    whatsappNumber,
    errorMessage,
    successMessage,
    loading,
    verifyPurchase,
} = modules();

// Settings state
const settingsLoading = ref(true);
const verifySettings = ref({
    show_email: true,
    email_required: true,
    show_whatsapp: true,
    whatsapp_required: true,
});

// Fetch verify settings on mount
onMounted(async () => {
    try {
        const response = await axios.post("https://envato.codeifly.com/verify-settings", {
            domain: window.location.host,
            verified_name: window.config.product_name,
        });

        if (response.data) {
            verifySettings.value = {
                show_email: response.data.show_email ?? true,
                email_required: response.data.email_required ?? true,
                show_whatsapp: response.data.show_whatsapp ?? true,
                whatsapp_required: response.data.whatsapp_required ?? true,
            };
        }
    } catch (error) {
        // On error, use default settings (show all fields as required)
        console.warn("Failed to fetch verify settings:", error);
    } finally {
        settingsLoading.value = false;
    }
});

const verify = () =>
    verifyPurchase({
        success: async (res) => {
            // Reset and re-run verification to update the store state
            verificationStore.reset();
            await verificationStore.runVerification({
                appType: window.config.app_type,
                modules: window.config.modules,
            });

            // Now redirect - the guard will allow it since verification state is updated
            router.push({ name: "admin.login" });
        },
    });
</script>

<style lang="less">
.main-container {
    height: 100vh;
}

.container-content {
    margin-top: 100px;
}
</style>
