<template>
    <a-drawer
        :open="visible"
        :closable="true"
        :maskClosable="false"
        :title="pageTitle"
        :width="drawerWidth"
        @close="onClose"
    >
        <a-form layout="vertical">
            <a-tabs v-model:activeKey="activeTab">
                <!-- Basic Info & Theme Settings Tab -->
                <a-tab-pane key="basic" :tab="$t('website.basic_and_theme')">
                    <!-- Basic Info Section -->
                    <a-divider orientation="left">{{ $t("website.basic_info") }}</a-divider>
                    <a-row :gutter="16">
                        <a-col :xs="24" :sm="24" :md="12" :lg="8">
                            <a-form-item
                                :label="$t('website.name')"
                                name="name"
                                :help="rules.name ? rules.name.message : null"
                                :validateStatus="rules.name ? 'error' : null"
                                class="required"
                            >
                                <a-input
                                    v-model:value="newFormData.name"
                                    :placeholder="
                                        $t('common.placeholder_default_text', [$t('website.name')])
                                    "
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :xs="24" :sm="24" :md="12" :lg="8">
                            <a-form-item
                                :label="$t('website.slug')"
                                name="slug"
                                :help="rules.slug ? rules.slug.message : null"
                                :validateStatus="rules.slug ? 'error' : null"
                                class="required"
                            >
                                <a-input
                                    v-model:value="newFormData.slug"
                                    :placeholder="
                                        $t('common.placeholder_default_text', [$t('website.slug')])
                                    "
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :xs="24" :sm="24" :md="12" :lg="8">
                            <a-form-item
                                :label="$t('website.category')"
                                name="website_category_id"
                                :help="rules.website_category_id ? rules.website_category_id.message : null"
                                :validateStatus="rules.website_category_id ? 'error' : null"
                            >
                                <span style="display: flex">
                                    <a-select
                                        v-model:value="newFormData.website_category_id"
                                        :placeholder="$t('common.select_default_text', [$t('website.category')])"
                                        optionFilterProp="label"
                                        show-search
                                        allowClear
                                        style="flex: 1"
                                    >
                                        <a-select-option
                                            v-for="category in websiteCategories"
                                            :key="category.xid"
                                            :value="category.xid"
                                            :label="category.name"
                                        >
                                            {{ category.name }}
                                        </a-select-option>
                                    </a-select>
                                    <WebsiteCategoryAddButton @onAddSuccess="categoryAdded" />
                                </span>
                            </a-form-item>
                        </a-col>
                    </a-row>

                    <!-- Theme Settings Section -->
                    <a-divider orientation="left">{{ $t("website.theme_settings") }}</a-divider>
                    <a-row :gutter="16">
                        <a-col :xs="24" :sm="24" :md="12" :lg="6">
                            <a-form-item
                                :label="$t('website.theme_name')"
                                name="theme_name"
                                :help="rules.theme_name ? rules.theme_name.message : null"
                                :validateStatus="rules.theme_name ? 'error' : null"
                                class="required"
                            >
                                <a-select
                                    v-model:value="newFormData.theme_name"
                                    :placeholder="
                                        $t('common.select_default_text', [$t('website.theme_name')])
                                    "
                                >
                                    <a-select-option
                                        v-for="theme in availableThemes"
                                        :key="theme.name"
                                        :value="theme.name"
                                    >
                                        {{ theme.label }}
                                    </a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :xs="24" :sm="24" :md="12" :lg="6">
                            <a-form-item
                                :label="$t('website.theme_primary_color')"
                                name="theme_primary_color"
                                :help="
                                    rules.theme_primary_color
                                        ? rules.theme_primary_color.message
                                        : null
                                "
                                :validateStatus="rules.theme_primary_color ? 'error' : null"
                                class="required"
                            >
                                <color-picker
                                    v-model:pureColor="newFormData.theme_primary_color"
                                    format="hex"
                                    useType="pure"
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :xs="24" :sm="24" :md="12" :lg="6">
                            <a-form-item
                                :label="$t('website.theme_secondary_color')"
                                name="theme_secondary_color"
                                :help="
                                    rules.theme_secondary_color
                                        ? rules.theme_secondary_color.message
                                        : null
                                "
                                :validateStatus="rules.theme_secondary_color ? 'error' : null"
                            >
                                <a-space direction="vertical" style="width: 100%">
                                    <a-switch
                                        v-model:checked="enableSecondaryColor"
                                        :checkedChildren="$t('common.yes')"
                                        :unCheckedChildren="$t('common.no')"
                                    />
                                    <color-picker
                                        v-if="enableSecondaryColor"
                                        v-model:pureColor="newFormData.theme_secondary_color"
                                        format="hex"
                                        useType="pure"
                                    />
                                </a-space>
                            </a-form-item>
                        </a-col>
                        <!-- Theme Mode - Hidden for now, only light mode supported
                        <a-col :xs="24" :sm="24" :md="12" :lg="6">
                            <a-form-item
                                :label="$t('website.theme_mode')"
                                name="theme_mode"
                                :help="rules.theme_mode ? rules.theme_mode.message : null"
                                :validateStatus="rules.theme_mode ? 'error' : null"
                                class="required"
                            >
                                <a-select v-model:value="newFormData.theme_mode">
                                    <a-select-option value="light">
                                        {{ $t("website.light") }}
                                    </a-select-option>
                                    <a-select-option value="dark">
                                        {{ $t("website.dark") }}
                                    </a-select-option>
                                </a-select>
                            </a-form-item>
                        </a-col>
                        -->
                    </a-row>

                    <!-- Header/Footer Settings Section -->
                    <a-divider orientation="left">{{ $t("website_setting.header_settings") }} / {{ $t("website_setting.footer_settings") }}</a-divider>
                    <a-row :gutter="16">
                        <a-col :xs="24" :sm="24" :md="12" :lg="12">
                            <a-form-item name="use_same_header_across_all_pages">
                                <template #label>
                                    <span>
                                        {{ $t('website.use_same_header_across_all_pages') }}
                                        <a-tooltip :title="$t('website.use_same_header_across_all_pages_help')">
                                            <QuestionCircleOutlined style="margin-left: 4px; color: #999" />
                                        </a-tooltip>
                                    </span>
                                </template>
                                <a-switch
                                    v-model:checked="newFormData.use_same_header_across_all_pages"
                                    :checkedChildren="$t('common.yes')"
                                    :unCheckedChildren="$t('common.no')"
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :xs="24" :sm="24" :md="12" :lg="12">
                            <a-form-item name="use_same_footer_across_all_pages">
                                <template #label>
                                    <span>
                                        {{ $t('website.use_same_footer_across_all_pages') }}
                                        <a-tooltip :title="$t('website.use_same_footer_across_all_pages_help')">
                                            <QuestionCircleOutlined style="margin-left: 4px; color: #999" />
                                        </a-tooltip>
                                    </span>
                                </template>
                                <a-switch
                                    v-model:checked="newFormData.use_same_footer_across_all_pages"
                                    :checkedChildren="$t('common.yes')"
                                    :unCheckedChildren="$t('common.no')"
                                />
                            </a-form-item>
                        </a-col>
                    </a-row>
                </a-tab-pane>

                <!-- Languages Tab -->
                <a-tab-pane key="languages" :tab="$t('menu.website_languages')">
                    <a-alert
                        :message="$t('website.languages_help')"
                        type="info"
                        show-icon
                        style="margin-bottom: 16px"
                    />

                    <!-- Languages Table -->
                    <a-table
                        :dataSource="newFormData.languages"
                        :pagination="false"
                        :rowKey="(record, index) => index"
                        size="middle"
                        bordered
                    >
                        <a-table-column :title="$t('website_language.name')" key="name">
                            <template #default="{ record, index }">
                                <a-input-group v-if="canEditLanguage || !record.xid" compact style="display: flex">
                                    <a-select
                                        v-model:value="record.flag_code"
                                        style="width: 70px"
                                        show-search
                                        :filter-option="filterCountryOption"
                                        @change="onFlagCodeChange(index)"
                                    >
                                        <a-select-option
                                            v-for="country in countryOptions"
                                            :key="country.code"
                                            :value="country.code"
                                            :label="country.label"
                                            :filterLabel="country.filterLabel"
                                        >
                                            {{ country.label }}
                                        </a-select-option>
                                    </a-select>
                                    <a-input
                                        v-model:value="record.name"
                                        :placeholder="$t('website_language.name')"
                                        style="flex: 1"
                                    />
                                </a-input-group>
                                <span v-else>
                                    {{ getFlagEmoji(record.flag_code) }} {{ record.name }}
                                </span>
                            </template>
                        </a-table-column>
                        <a-table-column :title="$t('website_language.is_rtl')" key="is_rtl" width="120" align="center">
                            <template #default="{ record }">
                                <a-switch
                                    v-if="canEditLanguage || !record.xid"
                                    v-model:checked="record.is_rtl"
                                    :checkedValue="true"
                                    :unCheckedValue="false"
                                    size="small"
                                />
                                <a-tag v-else :color="record.is_rtl ? 'blue' : 'default'">
                                    {{ record.is_rtl ? $t('website_language.rtl') : $t('website_language.ltr') }}
                                </a-tag>
                            </template>
                        </a-table-column>
                        <a-table-column :title="$t('website_language.enabled')" key="enabled" width="100" align="center">
                            <template #default="{ record }">
                                <a-switch
                                    v-if="canEditLanguage || !record.xid"
                                    v-model:checked="record.enabled"
                                    :checkedValue="true"
                                    :unCheckedValue="false"
                                    size="small"
                                />
                                <a-tag v-else :color="record.enabled ? 'success' : 'default'">
                                    {{ record.enabled ? $t('common.enabled') : $t('common.disabled') }}
                                </a-tag>
                            </template>
                        </a-table-column>
                        <a-table-column :title="$t('website_language.is_default')" key="is_default" width="100" align="center">
                            <template #default="{ record, index }">
                                <a-radio
                                    v-if="canEditLanguage || !record.xid"
                                    :checked="record.is_default"
                                    @click="setDefaultLanguage(index)"
                                />
                                <a-tag v-else-if="record.is_default" color="green">
                                    {{ $t('common.yes') }}
                                </a-tag>
                                <span v-else>-</span>
                            </template>
                        </a-table-column>
                        <a-table-column v-if="canDeleteLanguage" key="action" width="60" align="center">
                            <template #default="{ record, index }">
                                <a-button
                                    v-if="newFormData.languages.length > 1"
                                    type="text"
                                    danger
                                    size="small"
                                    @click="removeLanguage(index)"
                                    :disabled="record.is_default"
                                >
                                    <template #icon>
                                        <DeleteOutlined />
                                    </template>
                                </a-button>
                            </template>
                        </a-table-column>
                    </a-table>

                    <!-- Add Language Button -->
                    <a-button
                        v-if="canCreateLanguage"
                        type="dashed"
                        block
                        @click="addLanguage"
                        style="margin-top: 12px;"
                    >
                        <template #icon>
                            <PlusOutlined />
                        </template>
                        {{ $t('website.add_language') }}
                    </a-button>
                </a-tab-pane>

                <!-- Primary Tab (non-saas only) -->
                <a-tab-pane v-if="appType === 'non-saas'" key="primary" :tab="$t('website.primary')">
                    <a-row :gutter="16">
                        <a-col :xs="24" :sm="24" :md="12" :lg="8">
                            <a-form-item
                                :label="$t('website.is_primary')"
                                name="is_primary"
                                :help="$t('website.primary_help')"
                            >
                                <a-switch
                                    v-model:checked="newFormData.is_primary"
                                    :checkedChildren="$t('common.yes')"
                                    :unCheckedChildren="$t('common.no')"
                                />
                            </a-form-item>
                        </a-col>
                    </a-row>
                </a-tab-pane>

                <!-- Custom Code Tab -->
                <a-tab-pane key="custom_code" :tab="$t('website.custom_code')">
                    <a-alert
                        :message="$t('website.custom_code_warning')"
                        type="warning"
                        show-icon
                        style="margin-bottom: 16px"
                    />
                    <a-row :gutter="16">
                        <a-col :xs="24" :sm="24" :md="12" :lg="12">
                            <a-form-item
                                :label="$t('website.custom_css')"
                                name="custom_css"
                                :help="rules.custom_css ? rules.custom_css.message : null"
                                :validateStatus="rules.custom_css ? 'error' : null"
                            >
                                <a-textarea
                                    v-model:value="newFormData.custom_css"
                                    :placeholder="$t('website.custom_css_placeholder')"
                                    :rows="8"
                                    style="font-family: monospace; font-size: 12px"
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :xs="24" :sm="24" :md="12" :lg="12">
                            <a-form-item
                                :label="$t('website.custom_js')"
                                name="custom_js"
                                :help="rules.custom_js ? rules.custom_js.message : null"
                                :validateStatus="rules.custom_js ? 'error' : null"
                            >
                                <a-textarea
                                    v-model:value="newFormData.custom_js"
                                    :placeholder="$t('website.custom_js_placeholder')"
                                    :rows="8"
                                    style="font-family: monospace; font-size: 12px"
                                />
                            </a-form-item>
                        </a-col>
                    </a-row>
                </a-tab-pane>
            </a-tabs>
        </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-drawer>
</template>

<script>
import { defineComponent, ref, onMounted, watch, computed } from "vue";
import { PlusOutlined, LoadingOutlined, SaveOutlined, HomeOutlined, DeleteOutlined, QuestionCircleOutlined } from "@ant-design/icons-vue";
import { ColorPicker } from "vue3-colorpicker";
import "vue3-colorpicker/style.css";
import apiAdmin from "@/common/composable/apiAdmin";
import common from "@/common/composable/common";
import { countryCodes, getFlagEmoji, filterCountryOption, getLocaleBasedDefaultLanguage, getLanguageInfoFromCountry } from "@/common/scripts/countryCodes";
import WebsiteCategoryAddButton from "../website-categories/AddButton.vue";

export default defineComponent({
    props: [
        "formData",
        "data",
        "visible",
        "url",
        "addEditType",
        "pageTitle",
        "successMessage",
        "appType",
    ],
    emits: ["addListSuccess", "addEditSuccess", "closed"],
    components: {
        PlusOutlined,
        LoadingOutlined,
        SaveOutlined,
        HomeOutlined,
        DeleteOutlined,
        QuestionCircleOutlined,
        ColorPicker,
        WebsiteCategoryAddButton,
    },
    setup(props, { emit }) {
        const { appSetting, permsArray } = common();
        const newFormData = ref({});
        const { addEditRequestAdmin, loading, rules } = apiAdmin();
        const enableSecondaryColor = ref(false);
        const availableThemes = ref([]);
        const websiteCategories = ref([]);
        const activeTab = ref("basic");

        // Permission checks for language management
        const canCreateLanguage = computed(() => {
            return permsArray.value.includes('admin') || permsArray.value.includes('website_languages_create');
        });
        const canEditLanguage = computed(() => {
            return permsArray.value.includes('admin') || permsArray.value.includes('website_languages_edit');
        });
        const canDeleteLanguage = computed(() => {
            return permsArray.value.includes('admin') || permsArray.value.includes('website_languages_delete');
        });

        // Country options for language flags
        const countryOptions = computed(() => {
            return countryCodes.map((country) => ({
                code: country.code,
                label: getFlagEmoji(country.code),
                filterLabel: `${country.name} ${country.code}`,
            }));
        });

        // Default language entry based on user's browser locale/location
        const getDefaultLanguage = () => getLocaleBasedDefaultLanguage();

        // Generate slug from name
        const generateSlug = (name) => {
            if (!name) return "";
            return name
                .toLowerCase()
                .trim()
                .replace(/[^\w\s-]/g, "") // Remove special characters
                .replace(/\s+/g, "-") // Replace spaces with hyphens
                .replace(/-+/g, "-") // Replace multiple hyphens with single
                .replace(/^-+|-+$/g, ""); // Remove leading/trailing hyphens
        };

        // Watch name changes to auto-generate slug (only in add mode)
        watch(
            () => newFormData.value.name,
            (newName) => {
                if (props.addEditType === "add" && newName) {
                    newFormData.value.slug = generateSlug(newName);
                }
            }
        );

        onMounted(() => {
            fetchAvailableThemes();
            fetchWebsiteCategories();
        });

        const fetchAvailableThemes = () => {
            window.axiosAdmin
                .get("website-settings/available-themes")
                .then((response) => {
                    availableThemes.value = response.data;
                })
                .catch((error) => {
                    console.error("Error fetching available themes:", error);
                });
        };

        const fetchWebsiteCategories = () => {
            window.axiosAdmin
                .get("website-categories?limit=10000")
                .then((response) => {
                    websiteCategories.value = response.data;
                })
                .catch((error) => {
                    console.error("Error fetching website categories:", error);
                });
        };

        const categoryAdded = (xid) => {
            window.axiosAdmin
                .get("website-categories?limit=10000")
                .then((response) => {
                    websiteCategories.value = response.data;
                    // Auto-select the newly created category
                    if (xid) {
                        newFormData.value.website_category_id = xid;
                    }
                });
        };

        // Language management functions
        const addLanguage = () => {
            // Get default language info for US
            const defaultLangInfo = getLanguageInfoFromCountry('US');
            newFormData.value.languages.push({
                name: defaultLangInfo.name,
                key: defaultLangInfo.key,
                flag_code: 'US',
                is_rtl: defaultLangInfo.is_rtl,
                enabled: true,
                is_default: false,
            });
        };

        const removeLanguage = (index) => {
            if (newFormData.value.languages.length > 1 && !newFormData.value.languages[index].is_default) {
                newFormData.value.languages.splice(index, 1);
            }
        };

        const setDefaultLanguage = (index) => {
            newFormData.value.languages.forEach((lang, i) => {
                lang.is_default = i === index;
            });
        };

        const onFlagCodeChange = (index) => {
            const lang = newFormData.value.languages[index];
            if (lang.flag_code) {
                const langInfo = getLanguageInfoFromCountry(lang.flag_code);
                lang.key = langInfo.key;
                lang.name = langInfo.name;
                lang.is_rtl = langInfo.is_rtl;
            }
        };

        const onSubmit = () => {
            // Ensure all languages have required fields
            if (newFormData.value.languages && newFormData.value.languages.length > 0) {
                for (let i = 0; i < newFormData.value.languages.length; i++) {
                    const lang = newFormData.value.languages[i];
                    // If key is empty, derive it from flag_code
                    if (!lang.key && lang.flag_code) {
                        const langInfo = getLanguageInfoFromCountry(lang.flag_code);
                        lang.key = langInfo.key;
                        lang.name = lang.name || langInfo.name;
                        lang.is_rtl = lang.is_rtl ?? langInfo.is_rtl;
                    }
                }
            }

            // Clear secondary color if toggle is off
            const submitData = { ...newFormData.value };
            if (!enableSecondaryColor.value) {
                submitData.theme_secondary_color = null;
            }

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

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

        watch(
            () => props.visible,
            (newVal, oldVal) => {
                if (newVal) {
                    newFormData.value = {
                        ...props.formData,
                        languages: props.formData.languages || [getDefaultLanguage()],
                        use_same_header_across_all_pages: props.formData.use_same_header_across_all_pages ?? true,
                        use_same_footer_across_all_pages: props.formData.use_same_footer_across_all_pages ?? true,
                    };

                    // Set secondary color toggle based on existing value
                    enableSecondaryColor.value = !!props.formData.theme_secondary_color;

                    if (props.addEditType === "edit" && props.data) {
                        // Edit mode: Use x_website_category_id from data
                        if (props.data.x_website_category_id) {
                            newFormData.value.website_category_id =
                                props.data.x_website_category_id;
                        }
                        // Edit mode: Set is_primary from data
                        newFormData.value.is_primary = props.data.is_primary || false;

                        // Edit mode: Set header/footer settings from data
                        newFormData.value.use_same_header_across_all_pages = props.data.use_same_header_across_all_pages ?? true;
                        newFormData.value.use_same_footer_across_all_pages = props.data.use_same_footer_across_all_pages ?? true;

                        // Edit mode: Load existing languages if available
                        // API returns website_languages (snake_case) or websiteLanguages (camelCase) from the include parameter
                        const existingLangs = props.data.website_languages || props.data.websiteLanguages;
                        if (existingLangs && existingLangs.length > 0) {
                            newFormData.value.languages = existingLangs.map(lang => ({
                                id: lang.id,
                                xid: lang.xid,
                                name: lang.name,
                                key: lang.key,
                                flag_code: lang.flag_code,
                                is_rtl: lang.is_rtl,
                                enabled: lang.enabled,
                                is_default: lang.is_default,
                            }));
                        }
                    }

                    // Reset to first tab
                    activeTab.value = "basic";
                }
            }
        );

        return {
            appSetting,
            loading,
            rules,
            onClose,
            onSubmit,
            newFormData,
            enableSecondaryColor,
            availableThemes,
            websiteCategories,
            categoryAdded,
            appType: props.appType,
            activeTab,
            countryOptions,
            filterCountryOption,
            getFlagEmoji,
            addLanguage,
            removeLanguage,
            setDefaultLanguage,
            onFlagCodeChange,
            canCreateLanguage,
            canEditLanguage,
            canDeleteLanguage,

            drawerWidth: window.innerWidth <= 991 ? "90%" : "60%",
        };
    },
});
</script>
