<template>
    <admin-page-header>
        <template #header>
            <a-page-header :title="$t(`menu.website_pages`)" class="p-0" />
        </template>
        <template #breadcrumb>
            <a-breadcrumb separator="-" style="font-size: 12px">
                <a-breadcrumb-item>
                    <router-link :to="{ name: 'admin.dashboard.index' }">
                        {{ $t(`menu.dashboard`) }}
                    </router-link>
                </a-breadcrumb-item>
                <a-breadcrumb-item>
                    {{ $t(`menu.website_pages`) }}
                </a-breadcrumb-item>
                <SelectedWebsiteBreadcrumb />
            </a-breadcrumb>
        </template>
    </admin-page-header>

    <a-row>
        <a-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <admin-page-filters>
                <a-row :gutter="[16, 16]">
                    <a-col :xs="24" :sm="24" :md="12" :lg="10" :xl="10">
                        <a-space>
                            <template
                                v-if="
                                    permsArray.includes('website_pages_create') ||
                                    permsArray.includes('admin')
                                "
                            >
                                <a-button type="primary" @click="addItem">
                                    <PlusOutlined />
                                    {{ $t("website_page.add") }}
                                </a-button>
                                <AiPageButton @saved="onAiPagesSaved" />
                            </template>
                            <a-button
                                v-if="
                                    table.selectedRowKeys.length > 0 &&
                                    (permsArray.includes('website_pages_delete') ||
                                        permsArray.includes('admin'))
                                "
                                type="primary"
                                @click="showSelectedDeleteConfirm"
                                danger
                            >
                                <template #icon><DeleteOutlined /></template>
                                {{ $t("common.delete") }}
                            </a-button>
                        </a-space>
                    </a-col>
                    <a-col :xs="24" :sm="24" :md="12" :lg="14" :xl="14">
                        <a-row :gutter="[16, 16]" justify="end">
                            <a-col :xs="24" :sm="24" :md="12" :lg="8" :xl="8">
                                <a-input-group compact>
                                    <a-input-search
                                        style="width: 100%"
                                        v-model:value="table.searchString"
                                        show-search
                                        @change="onTableSearch"
                                        @search="onTableSearch"
                                        :loading="table.filterLoading"
                                        :placeholder="
                                            $t('common.placeholder_search_text', [
                                                $t('website_page.page_key'),
                                            ])
                                        "
                                    />
                                </a-input-group>
                            </a-col>
                        </a-row>
                    </a-col>
                </a-row>
            </admin-page-filters>

            <admin-page-table-content>
                <AddEdit
                    :addEditType="addEditType"
                    :visible="addEditVisible"
                    :url="crudAddEditUrl"
                    :formData="formData"
                    :data="viewData"
                    :pageTitle="pageTitle"
                    :successMessage="successMessage"
                    :languages="languages"
                    @addEditSuccess="addEditSuccess"
                    @closed="onCloseAddEdit"
                />

                <a-row>
                    <a-col :span="24">
                        <a-spin :spinning="savingOrder">
                            <div class="table-responsive" ref="tableRef">
                                <a-table
                                    :row-selection="{
                                        selectedRowKeys: table.selectedRowKeys,
                                        onChange: onRowSelectChange,
                                        getCheckboxProps: (record) => ({
                                            disabled: record.page_key === 'home',
                                            name: record.xid,
                                        }),
                                    }"
                                    :columns="columns"
                                    :row-key="(record) => record.xid"
                                    :data-source="table.data"
                                    :pagination="false"
                                    :loading="table.loading"
                                    bordered
                                    size="middle"
                                >
                                    <template #bodyCell="{ column, record }">
                                        <template v-if="column.dataIndex === 'drag'">
                                            <div class="drag-handle">
                                                <DragOutlined />
                                            </div>
                                        </template>
                                        <template v-else-if="column.dataIndex === 'name'">
                                            <span
                                                class="page-name-link"
                                                @click="editItem(record)"
                                                >{{ getDefaultLangTranslationName(record) }}</span
                                            >
                                        </template>
                                        <template v-else-if="column.dataIndex === 'action'">
                                            <a-space>
                                                <a-button
                                                    v-if="
                                                        permsArray.includes(
                                                            'website_pages_edit'
                                                        ) || permsArray.includes('admin')
                                                    "
                                                    type="primary"
                                                    @click="editItem(record)"
                                                >
                                                    <template #icon
                                                        ><EditOutlined
                                                    /></template>
                                                </a-button>
                                                <a-button
                                                    v-if="
                                                        record.page_key !== 'home' &&
                                                        (permsArray.includes(
                                                            'website_pages_delete'
                                                        ) || permsArray.includes('admin'))
                                                    "
                                                    type="primary"
                                                    @click="showDeleteConfirm(record.xid)"
                                                >
                                                    <template #icon
                                                        ><DeleteOutlined
                                                    /></template>
                                                </a-button>
                                            </a-space>
                                        </template>
                                    </template>
                                </a-table>
                            </div>
                        </a-spin>
                    </a-col>
                </a-row>
            </admin-page-table-content>
        </a-col>
    </a-row>
</template>

<script setup>
import { ref, watch, createVNode, nextTick, onBeforeUnmount } from "vue";
import {
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    ExclamationCircleOutlined,
    DragOutlined,
} from "@ant-design/icons-vue";
import { Modal, notification } from "ant-design-vue";
import { forEach } from "lodash-es";
import Sortable from "sortablejs";
import fields from "./fields";
import AddEdit from "./AddEdit.vue";
import AiPageButton from "./AiPageButton.vue";
import { useAuthStore } from "../../store/authStore";
import { storeToRefs } from "pinia";
import SelectedWebsiteBreadcrumb from "../../../common/components/SelectedWebsiteBreadcrumb.vue";
import { useI18n } from "vue-i18n";

// Get composables from global window object
const crud = window.__composables.crud;
const common = window.__composables.common;
const axiosAdmin = window.axiosAdmin;

const { t } = useI18n();
const { permsArray } = common();

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

// Languages list
const languages = ref([]);
const {
    url,
    addEditUrl,
    initData,
    columns,
    filterableColumns,
    hashableColumns,
} = fields();

// Call crud() and destructure all returns
const {
    table,
    addEditVisible,
    addEditType,
    addEditUrl: crudAddEditUrl,
    formData,
    viewData,
    pageTitle,
    successMessage,
    addItem,
    editItem,
    onCloseAddEdit,
    onRowSelectChange,
    tableUrl,
    crudUrl,
    langKey,
    initData: crudInitData,
    fetch,
    hashableColumns: crudhashableColumns,
} = crud();

// Sortable state
const tableRef = ref(null);
const savingOrder = ref(false);
let sortableInstance = null;

// Extra filters for business
const extraFilters = ref({
    website_id: undefined,
});

// Get translation name for default language
const getDefaultLangTranslationName = (record) => {
    if (record.translations && record.translations.length > 0) {
        // Find the default language
        const defaultLang = languages.value.find(lang => lang.is_default);
        if (defaultLang) {
            // Find the translation for the default language using x_website_language_id (hashid)
            const defaultTranslation = record.translations.find(
                t => t.x_website_language_id === defaultLang.xid
            );
            if (defaultTranslation) {
                return defaultTranslation.name;
            }
        }
        // Fallback to first translation if default not found
        return record.translations[0].name;
    }
    return record.page_key;
};

// Custom table search handler
const onTableSearch = () => {
    table.filterLoading = true;
    fetchData();
    table.filterLoading = false;
};

// Custom fetch function with proper parameters
const fetchData = () => {
    fetch({
        page: 1,
    });
};

// Fetch languages list for selected business
const fetchLanguages = () => {
    if (!selectedWebsite.value?.xid) return;

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

// AI Pages Saved Handler
const onAiPagesSaved = () => {
    // Refresh the table to show the new pages
    fetchData();
};

// Define setUrlData BEFORE the watcher that uses it
const setUrlData = () => {
    // Set hashable columns BEFORE fetching data so website_id is properly converted
    // Note: hashableColumns must be an array for includes() check in datatable.js
    crudhashableColumns.value = [...hashableColumns];

    tableUrl.value = {
        url,
        extraFilters,
    };

    table.filterableColumns = filterableColumns;

    // Set default sort order by sort_order ascending
    table.sorter = {
        field: "sort_order",
        order: "asc",
    };

    crudUrl.value = addEditUrl;
    langKey.value = "website_page";

    // Include website_id in init data for new records
    const initDataWithContext = {
        ...initData,
        website_id: extraFilters.value.website_id,
    };

    crudInitData.value = { ...initDataWithContext };
    formData.value = { ...initDataWithContext };

    // Fetch data after all configuration is set
    fetchData();
};

// Watch for business changes and reload data (immediate to handle initial load)
watch(
    () => selectedWebsite.value?.xid,
    (newBusinessXid) => {
        if (newBusinessXid) {
            extraFilters.value.website_id = newBusinessXid;
            setUrlData();
            fetchLanguages();
        }
    },
    { immediate: true }
);

// Custom delete confirm handler
const showDeleteConfirm = (id) => {
    Modal.confirm({
        title: t("common.delete") + "?",
        icon: createVNode(ExclamationCircleOutlined),
        content: t("website_page.delete_message"),
        centered: true,
        okText: t("common.yes"),
        okType: "danger",
        cancelText: t("common.no"),
        onOk() {
            return axiosAdmin
                .delete(`${crudUrl.value}/${id}`)
                .then(() => {
                    fetchData();
                    notification.success({
                        message: t("common.success"),
                        description: t("website_page.deleted"),
                        placement: "bottomRight",
                    });
                })
                .catch(() => {});
        },
        onCancel() {},
    });
};

// Custom selected delete confirm handler
const showSelectedDeleteConfirm = () => {
    Modal.confirm({
        title: t("common.delete") + "?",
        icon: createVNode(ExclamationCircleOutlined),
        content: t("website_page.selected_delete_message"),
        centered: true,
        okText: t("common.yes"),
        okType: "danger",
        cancelText: t("common.no"),
        onOk() {
            const allDeletePromise = [];
            forEach(table.selectedRowKeys, (selectedRow) => {
                allDeletePromise.push(
                    axiosAdmin.delete(`${crudUrl.value}/${selectedRow}`)
                );
            });

            Promise.all(allDeletePromise).then(() => {
                fetchData();
                notification.success({
                    message: t("common.success"),
                    description: t("website_page.deleted"),
                    placement: "bottomRight",
                });
            });
        },
        onCancel() {},
    });
};

// Custom add/edit success handler
const addEditSuccess = () => {
    formData.value = { ...initData };
    fetchData();
    addEditVisible.value = false;
};

// Handle drag end - save new sort order
const onSortEnd = async (evt) => {
    const { oldIndex, newIndex } = evt;
    if (oldIndex === newIndex) return;

    // Reorder the array
    const movedItem = table.data.splice(oldIndex, 1)[0];
    table.data.splice(newIndex, 0, movedItem);

    savingOrder.value = true;

    try {
        // Build the new order array with xid and sort_order
        const orderData = table.data.map((page, index) => ({
            xid: page.xid,
            sort_order: index,
        }));

        // Save the new order to the backend
        await axiosAdmin.post("website-pages/update-sort-order", {
            pages: orderData,
        });

        // Update local data with new sort_order
        table.data.forEach((page, index) => {
            page.sort_order = index;
        });

        notification.success({
            message: t("common.success"),
            description: t("website_page.sort_order_updated"),
            placement: "bottomRight",
        });
    } catch (error) {
        console.error("Error saving sort order:", error);
        notification.error({
            message: t("common.error"),
            description: t("common.something_went_wrong"),
            placement: "bottomRight",
        });
        // Revert to original order on error
        fetchData();
    } finally {
        savingOrder.value = false;
    }
};

// Initialize Sortable on the table body
const initSortable = () => {
    if (tableRef.value && !sortableInstance) {
        const tableBody = tableRef.value.querySelector('.ant-table-tbody');
        if (tableBody) {
            sortableInstance = Sortable.create(tableBody, {
                handle: ".drag-handle",
                animation: 150,
                ghostClass: "sortable-ghost",
                dragClass: "sortable-drag",
                onEnd: onSortEnd,
            });
        }
    }
};

// Destroy Sortable instance
const destroySortable = () => {
    if (sortableInstance) {
        sortableInstance.destroy();
        sortableInstance = null;
    }
};

// Watch for table loading changes to initialize sortable after data loads
watch(
    () => table.loading,
    (loading) => {
        if (!loading && table.data.length > 0) {
            nextTick(() => {
                destroySortable();
                initSortable();
            });
        }
    }
);

// Clean up on unmount
onBeforeUnmount(() => {
    destroySortable();
});
</script>

<style scoped>
.cursor-pointer {
    cursor: pointer;
}

.page-name-link {
    color: #1890ff;
    font-weight: 500;
    cursor: pointer;
}

.page-name-link:hover {
    color: #40a9ff;
    text-decoration: underline;
}

/* Drag handle styles */
.drag-handle {
    display: flex;
    align-items: center;
    justify-content: center;
    color: #bfbfbf;
    cursor: grab;
    padding: 4px;
}

.drag-handle:hover {
    color: #8c8c8c;
}

.drag-handle:active {
    cursor: grabbing;
}

/* Sortable ghost and drag states */
:deep(.sortable-ghost) {
    opacity: 0.5;
    background: #e6f4ff;
}

:deep(.sortable-drag) {
    opacity: 1;
    background: #fff;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* Dark mode support */
:global(.dark_theme) .page-name-link {
    color: #177ddc;
}

:global(.dark_theme) .page-name-link:hover {
    color: #3c9ae8;
}

:global(.dark_theme) .drag-handle {
    color: #595959;
}

:global(.dark_theme) .drag-handle:hover {
    color: #8c8c8c;
}

:global(.dark_theme) :deep(.sortable-ghost) {
    background: #111d2c;
}

:global(.dark_theme) :deep(.sortable-drag) {
    background: #1f1f1f;
}
</style>
