<template>
    <div class="ai-section-button-wrapper">
        <!-- AI Generate Button -->
        <a-button
            v-if="aiConfigured && selectedWebsite?.xid"
            type="default"
            @click="showAiGenerator"
            class="ai-generate-btn"
            :loading="loadingData"
            block
        >
            <template #icon><ThunderboltOutlined /></template>
            {{ $t("ai_settings.generate_with_ai") }}
        </a-button>

        <!-- AI Section Generation Modal -->
        <a-modal
            v-model:open="aiGeneratorVisible"
            :title="modalTitle"
            width="900px"
            :footer="null"
            :destroyOnClose="true"
            @cancel="closeAiGenerator"
        >
            <AiSectionGeneration
                v-if="aiGeneratorVisible && selectedWebsite?.xid"
                ref="sectionGenerationRef"
                :websiteXid="selectedWebsite.xid"
                :category="selectedWebsite?.website_category?.name || ''"
                :description="selectedWebsite?.description || ''"
                :languages="languagesForAi"
                :websitePages="websitePagesForAi"
                :websiteSettings="websiteSettingsForAi"
                :selectedPage="selectedPageForAi"
                :showSuccessHeader="false"
                :showFooter="true"
                :showSkipButton="true"
                @generated="onSectionsGenerated"
                @saved="onSectionsSaved"
                @skip="onSkip"
            />
        </a-modal>
    </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { ThunderboltOutlined } from "@ant-design/icons-vue";
import { message, notification } from "ant-design-vue";
import { useI18n } from "vue-i18n";
import { useAuthStore } from "../../store/authStore";
import { storeToRefs } from "pinia";
import { AiSectionGeneration } from "../../../common/core/ui/ai";

// Props - selectedPage is optional, if provided we generate for single page only
const props = defineProps({
    selectedPage: {
        type: Object,
        default: null, // { xid, page_key, name }
    },
});

const emit = defineEmits(["saved"]);

const { t } = useI18n();
const axiosAdmin = window.axiosAdmin;

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

// State
const aiGeneratorVisible = ref(false);
const aiConfigured = ref(false);
const loadingData = ref(false);
const sectionGenerationRef = ref(null);
const languages = ref([]);
const websitePages = ref([]);
const websiteSettings = ref({
    use_same_header_across_all_pages: true,
    use_same_footer_across_all_pages: true,
});

// Computed property to format languages for AiSectionGeneration component
const languagesForAi = computed(() => {
    return languages.value.map((lang) => ({
        key: lang.key,
        name: lang.name,
        flag_code: lang.flag_code,
        is_default: lang.is_default,
        is_rtl: lang.is_rtl || false,
    }));
});

// Computed property to format website pages for AiSectionGeneration component
const websitePagesForAi = computed(() => {
    return websitePages.value.map((page) => ({
        xid: page.xid,
        page_key: page.page_key,
        name: page.translations?.[0]?.name || page.page_key,
    }));
});

// Computed property to get website settings for header/footer
const websiteSettingsForAi = computed(() => ({
    use_same_header_across_all_pages: websiteSettings.value.use_same_header_across_all_pages,
    use_same_footer_across_all_pages: websiteSettings.value.use_same_footer_across_all_pages,
}));

// Computed property to format selected page for AiSectionGeneration component
// When selectedPage is provided, we generate sections only for that page
const selectedPageForAi = computed(() => {
    if (!props.selectedPage) return null;
    return {
        xid: props.selectedPage.xid,
        page_key: props.selectedPage.page_key,
        name: props.selectedPage.name || props.selectedPage.page_key,
    };
});

// Dynamic modal title based on whether we're generating for a single page or all pages
const modalTitle = computed(() => {
    if (selectedPageForAi.value) {
        return t("ai_settings.generate_page_sections", [selectedPageForAi.value.name]);
    }
    return t("ai_settings.generate_website_sections");
});

// Check if AI is configured
const checkAiConfig = async () => {
    try {
        const response = await axiosAdmin.get("ai/config");
        aiConfigured.value = response.data?.configured || false;
    } catch (error) {
        aiConfigured.value = false;
    }
};

// Fetch languages for the selected website
const fetchLanguages = async () => {
    if (!selectedWebsite.value?.xid) {
        languages.value = [];
        return;
    }

    try {
        const response = await axiosAdmin.get(
            `website-languages?website_id=${selectedWebsite.value.xid}&limit=10000`
        );
        languages.value = response.data || [];
    } catch (error) {
        console.error("Error fetching languages:", error);
        languages.value = [];
    }
};

// Fetch website pages for the selected website
const fetchWebsitePages = async () => {
    if (!selectedWebsite.value?.xid) {
        websitePages.value = [];
        return;
    }

    try {
        const response = await axiosAdmin.get(
            `website-pages?website_id=${selectedWebsite.value.xid}&order=sort_order&limit=10000`
        );
        websitePages.value = response.data || [];
    } catch (error) {
        console.error("Error fetching website pages:", error);
        websitePages.value = [];
    }
};

// Fetch website settings (header/footer settings) from website-settings API
const fetchWebsiteSettings = async () => {
    if (!selectedWebsite.value?.xid) {
        return;
    }

    try {
        // First try to get from selectedWebsite (already loaded in store)
        if (
            selectedWebsite.value.use_same_header_across_all_pages !== undefined ||
            selectedWebsite.value.use_same_footer_across_all_pages !== undefined
        ) {
            websiteSettings.value = {
                use_same_header_across_all_pages:
                    selectedWebsite.value.use_same_header_across_all_pages ?? true,
                use_same_footer_across_all_pages:
                    selectedWebsite.value.use_same_footer_across_all_pages ?? true,
            };
            return;
        }

        // Fallback: fetch from website-settings API
        const response = await axiosAdmin.get(
            `website-settings?website_id=${selectedWebsite.value.xid}`
        );
        if (response.data) {
            websiteSettings.value = {
                use_same_header_across_all_pages:
                    response.data.use_same_header_across_all_pages ?? true,
                use_same_footer_across_all_pages:
                    response.data.use_same_footer_across_all_pages ?? true,
            };
        }
    } catch (error) {
        console.error("Error fetching website settings:", error);
        // Default to true if fetch fails
        websiteSettings.value = {
            use_same_header_across_all_pages: true,
            use_same_footer_across_all_pages: true,
        };
    }
};

// Show AI generator modal
const showAiGenerator = async () => {
    if (!selectedWebsite.value?.xid) {
        message.warning(t("common.please_select_website"));
        return;
    }

    loadingData.value = true;

    try {
        // Fetch languages, pages, and website settings if not already loaded
        if (languages.value.length === 0) {
            await fetchLanguages();
        }

        if (languages.value.length === 0) {
            message.warning(t("ai_settings.no_languages_configured"));
            return;
        }

        if (websitePages.value.length === 0) {
            await fetchWebsitePages();
        }

        if (websitePages.value.length === 0) {
            message.warning(t("ai_settings.no_pages_configured"));
            return;
        }

        // Fetch website settings for header/footer configuration
        await fetchWebsiteSettings();

        aiGeneratorVisible.value = true;
    } finally {
        loadingData.value = false;
    }
};

// Close AI generator modal
const closeAiGenerator = () => {
    aiGeneratorVisible.value = false;
};

// Handle sections generated
const onSectionsGenerated = (sections) => {
    // Sections have been generated, waiting for save
};

// Handle sections saved
const onSectionsSaved = (result) => {
    aiGeneratorVisible.value = false;
    notification.success({
        message: t("common.success"),
        description: t("ai_settings.sections_saved_success"),
        placement: "bottomRight",
    });
    emit("saved", result);
};

// Handle skip button click - close the modal without generating
const onSkip = () => {
    aiGeneratorVisible.value = false;
};

// Initialize
onMounted(() => {
    checkAiConfig();
    if (selectedWebsite.value?.xid) {
        fetchLanguages();
        fetchWebsitePages();
    }
});

// Watch for website changes
watch(
    () => selectedWebsite.value?.xid,
    (newXid) => {
        // Reset state when website changes
        languages.value = [];
        websitePages.value = [];
        if (newXid) {
            fetchLanguages();
            fetchWebsitePages();
        }
    }
);

// Expose methods for parent component
defineExpose({
    showAiGenerator,
    closeAiGenerator,
    isAiConfigured: () => aiConfigured.value,
});
</script>

<style scoped>
.ai-section-button-wrapper {
    display: block;
    width: 100%;
}

/* AI Generate Button */
.ai-generate-btn {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    color: #fff;
}

.ai-generate-btn:hover {
    background: linear-gradient(135deg, #5a6fd6 0%, #6a4190 100%);
    color: #fff;
}

.ai-generate-btn:disabled {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    opacity: 0.6;
}
</style>
