<template>
    <a-modal
        :open="visible"
        :closable="false"
        :centered="true"
        :title="pageTitle"
        :width="700"
        @ok="onClose"
    >
        <a-form layout="vertical">
            <!-- Default language as base (always shown first) -->
            <template v-if="defaultLang && newFormData.translations[defaultLang.xid]">
                <a-row :gutter="16" align="middle">
                    <a-col :xs="24" :sm="24" :md="16" :lg="16">
                        <a-form-item
                            :label="`${getFlagEmoji(defaultLang.flag_code)} ${defaultLang.name}`"
                            :name="`translations.${defaultLang.xid}.name`"
                            :help="rules[`translations.${defaultLang.xid}.name`] ? rules[`translations.${defaultLang.xid}.name`].message : null"
                            :validateStatus="rules[`translations.${defaultLang.xid}.name`] ? 'error' : null"
                            class="required"
                        >
                            <a-input
                                v-model:value="newFormData.translations[defaultLang.xid].name"
                                :placeholder="$t('common.placeholder_default_text', [$t('website_page.name')])"
                                @input="() => generatePageKey(defaultLang.xid)"
                                @blur="() => autoFillOtherLanguages(defaultLang.xid)"
                            />
                        </a-form-item>
                    </a-col>
                    <a-col :xs="24" :sm="24" :md="8" :lg="8">
                        <a-form-item
                            :label="$t('website_page.show_in_header')"
                            :name="`translations.${defaultLang.xid}.show_in_header`"
                        >
                            <a-switch v-model:checked="newFormData.translations[defaultLang.xid].show_in_header" />
                        </a-form-item>
                    </a-col>
                </a-row>
            </template>

            <!-- Page Key (after English name) -->
            <a-row :gutter="16">
                <a-col :xs="24" :sm="24" :md="24" :lg="24">
                    <a-form-item
                        :label="$t('website_page.page_key')"
                        name="page_key"
                        :help="rules.page_key ? rules.page_key.message : null"
                        :validateStatus="rules.page_key ? 'error' : null"
                        class="required"
                    >
                        <a-input
                            v-model:value="newFormData.page_key"
                            :placeholder="$t('common.placeholder_default_text', [$t('website_page.page_key')])"
                            :disabled="addEditType === 'edit'"
                        />
                    </a-form-item>
                </a-col>
            </a-row>

            <!-- Other languages (translations) -->
            <template v-if="otherLanguages.length > 0">
                <a-divider>{{ $t('website_page.translations') }}</a-divider>

                <div v-for="lang in otherLanguages" :key="lang.xid" class="translation-item">
                    <a-row :gutter="16" align="middle">
                        <a-col :xs="24" :sm="24" :md="16" :lg="16">
                            <a-form-item
                                :label="`${getFlagEmoji(lang.flag_code)} ${lang.name}`"
                                :name="`translations.${lang.xid}.name`"
                                :help="rules[`translations.${lang.xid}.name`] ? rules[`translations.${lang.xid}.name`].message : null"
                                :validateStatus="rules[`translations.${lang.xid}.name`] ? 'error' : null"
                                class="required"
                            >
                                <a-input
                                    v-model:value="newFormData.translations[lang.xid].name"
                                    :placeholder="$t('common.placeholder_default_text', [$t('website_page.name')])"
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :xs="24" :sm="24" :md="8" :lg="8">
                            <a-form-item
                                :label="$t('website_page.show_in_header')"
                                :name="`translations.${lang.xid}.show_in_header`"
                            >
                                <a-switch v-model:checked="newFormData.translations[lang.xid].show_in_header" />
                            </a-form-item>
                        </a-col>
                    </a-row>
                </div>
            </template>
        </a-form>
        <template #footer>
            <a-space>
                <a-button
                    key="submit"
                    type="primary"
                    :loading="loading"
                    @click="onSubmit"
                >
                    <template #icon>
                        <SaveOutlined />
                    </template>
                    {{ addEditType == "add" ? $t("common.create") : $t("common.update") }}
                </a-button>
                <a-button key="back" @click="onClose">
                    {{ $t("common.cancel") }}
                </a-button>
            </a-space>
        </template>
    </a-modal>
</template>

<script>
import { defineComponent, ref, watch, computed } from "vue";
import { PlusOutlined, LoadingOutlined, SaveOutlined } from "@ant-design/icons-vue";
import apiAdmin from "@/common/composable/apiAdmin";
import common from "@/common/composable/common";
import { useAuthStore } from "../../store/authStore";
import { storeToRefs } from "pinia";
import { getFlagEmoji } from "../../../common/scripts/countryCodes";

export default defineComponent({
    props: [
        "formData",
        "data",
        "visible",
        "url",
        "addEditType",
        "pageTitle",
        "successMessage",
        "languages",
    ],
    emits: ["addListSuccess", "addEditSuccess", "closed"],
    components: {
        PlusOutlined,
        LoadingOutlined,
        SaveOutlined,
    },
    setup(props, { emit }) {
        const { appSetting } = common();
        const newFormData = ref({
            page_key: '',
            translations: {},
        });
        const { addEditRequestAdmin, loading, rules } = apiAdmin();

        // Get selected business from store
        const authStore = useAuthStore();
        const { selectedWebsite } = storeToRefs(authStore);

        // Get default language for the selected business
        const defaultLang = computed(() => {
            if (!props.languages) return null;
            return props.languages.find(l => l.is_default);
        });

        // Get other languages (non-default), sorted alphabetically
        const otherLanguages = computed(() => {
            if (!props.languages) return [];
            return props.languages
                .filter(l => !l.is_default)
                .sort((a, b) => a.name.localeCompare(b.name));
        });

        // Generate page_key from default language name (URL slug format)
        const generatePageKey = (langXid) => {
            if (props.addEditType === "add" && defaultLang.value) {
                if (langXid === defaultLang.value.xid && newFormData.value.translations[langXid]?.name) {
                    const defaultName = newFormData.value.translations[langXid].name;

                    // Generate URL-friendly slug
                    newFormData.value.page_key = defaultName
                        .toString()
                        .normalize('NFD')                    // Normalize unicode characters
                        .replace(/[\u0300-\u036f]/g, '')     // Remove diacritics
                        .toLowerCase()
                        .trim()
                        .replace(/[^a-z0-9\s-]/g, '')        // Remove non-alphanumeric except spaces and hyphens
                        .replace(/\s+/g, '-')                // Replace spaces with hyphens
                        .replace(/-+/g, '-')                 // Replace multiple hyphens with single
                        .replace(/^-+/, '')                  // Remove leading hyphens
                        .replace(/-+$/, '');                 // Remove trailing hyphens
                }
            }
        };

        // Auto-fill other language names from default language (called on blur)
        const autoFillOtherLanguages = (langXid) => {
            if (props.addEditType === "add" && defaultLang.value) {
                if (langXid === defaultLang.value.xid && newFormData.value.translations[langXid]?.name) {
                    const defaultName = newFormData.value.translations[langXid].name;

                    // Auto-fill other language names if they are empty
                    otherLanguages.value.forEach((lang) => {
                        if (!newFormData.value.translations[lang.xid]?.name) {
                            newFormData.value.translations[lang.xid].name = defaultName;
                        }
                    });
                }
            }
        };

        const onSubmit = () => {
            // Build translations array from the object
            const translationsArray = [];
            if (props.languages) {
                props.languages.forEach((lang) => {
                    const translationData = newFormData.value.translations[lang.xid] || {};
                    translationsArray.push({
                        website_language_id: lang.xid,
                        name: translationData.name || '',
                        show_in_header: translationData.show_in_header || false,
                    });
                });
            }

            const dataToSubmit = {
                page_key: newFormData.value.page_key,
                website_id: selectedWebsite.value?.xid || newFormData.value.website_id,
                translations: translationsArray,
            };

            // Add _method: PUT for update requests
            if (props.addEditType === "edit") {
                dataToSubmit._method = "PUT";
            }

            addEditRequestAdmin({
                url: props.url,
                data: dataToSubmit,
                successMessage: props.successMessage,
                success: (res) => {
                    emit("addEditSuccess", res.xid);
                },
            });
        };

        const onClose = () => {
            rules.value = {};
            emit("closed");
        };

        watch(
            () => props.visible,
            (newVal) => {
                if (newVal) {
                    // Initialize translations object for all languages
                    const translations = {};
                    if (props.languages) {
                        props.languages.forEach((lang) => {
                            translations[lang.xid] = {
                                name: '',
                                show_in_header: false,
                            };
                        });
                    }

                    if (props.addEditType === "edit" && props.data) {
                        // For edit mode, populate translations from record
                        const record = props.data;

                        if (record.translations && record.translations.length > 0) {
                            record.translations.forEach((translation) => {
                                // Handle both camelCase (frontLang) and snake_case (front_lang) from API
                                const langXid = translation.frontLang?.xid || translation.front_lang?.xid || translation.x_website_language_id;
                                if (langXid) {
                                    translations[langXid] = {
                                        name: translation.name || '',
                                        show_in_header: translation.show_in_header || false,
                                    };
                                }
                            });
                        }

                        newFormData.value = {
                            page_key: record.page_key,
                            website_id: record.x_website_id,
                            translations: translations,
                        };
                    } else {
                        newFormData.value = {
                            page_key: '',
                            translations: translations,
                        };
                    }
                }
            }
        );

        return {
            appSetting,
            loading,
            rules,
            onClose,
            onSubmit,
            newFormData,
            generatePageKey,
            autoFillOtherLanguages,
            getFlagEmoji,
            defaultLang,
            otherLanguages,
            drawerWidth: window.innerWidth <= 991 ? "90%" : "45%",
        };
    },
});
</script>

<style scoped>
.translation-item {
    border-bottom: 1px solid #f0f0f0;
    padding-bottom: 8px;
    margin-bottom: 8px;
}

.translation-item:last-child {
    border-bottom: none;
    margin-bottom: 0;
}

:global(.dark_theme) .translation-item {
    border-bottom-color: #303030;
}
</style>
