<template>
    <admin-page-header>
        <template #header>
            <a-page-header :title="$t(`menu.website_languages`)" 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_languages`) }}
                </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_languages_create') ||
                                    permsArray.includes('admin')
                                "
                            >
                                <a-button type="primary" @click="addItem">
                                    <PlusOutlined />
                                    {{ $t("website_language.add") }}
                                </a-button>
                            </template>
                            <a-button
                                v-if="
                                    table.selectedRowKeys.length > 0 &&
                                    (permsArray.includes('website_languages_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="16" :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_language.name'),
                                            ])
                                        "
                                    />
                                </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"
                    @addEditSuccess="addEditSuccess"
                    @closed="onCloseAddEdit"
                />

                <a-row>
                    <a-col :span="24">
                        <div class="table-responsive">
                            <a-table
                                :row-selection="{
                                    selectedRowKeys: table.selectedRowKeys,
                                    onChange: onRowSelectChange,
                                    getCheckboxProps: (record) => ({
                                        disabled: record.is_default,
                                        name: record.xid,
                                    }),
                                }"
                                :columns="columns"
                                :row-key="(record) => record.xid"
                                :data-source="table.data"
                                :pagination="table.pagination"
                                :loading="table.loading"
                                @change="handleTableChange"
                                bordered
                                size="middle"
                            >
                                <template #bodyCell="{ column, record }">
                                    <template v-if="column.dataIndex === 'name'">
                                        <div class="lang-name-cell">
                                            <span class="flag-emoji">{{
                                                getFlagEmoji(record.flag_code)
                                            }}</span>
                                            <span
                                                class="lang-name-link"
                                                @click="editItem(record)"
                                                >{{ record.name }}</span
                                            >
                                        </div>
                                    </template>
                                    <template v-else-if="column.dataIndex === 'is_rtl'">
                                        <a-tag
                                            :color="record.is_rtl ? 'blue' : 'default'"
                                        >
                                            {{
                                                record.is_rtl
                                                    ? $t("website_language.rtl")
                                                    : $t("website_language.ltr")
                                            }}
                                        </a-tag>
                                    </template>
                                    <template v-else-if="column.dataIndex === 'enabled'">
                                        <a-tag
                                            :color="
                                                record.enabled ? 'success' : 'default'
                                            "
                                        >
                                            {{
                                                record.enabled
                                                    ? $t("common.enabled")
                                                    : $t("common.disabled")
                                            }}
                                        </a-tag>
                                    </template>
                                    <template
                                        v-else-if="column.dataIndex === 'is_default'"
                                    >
                                        <a-switch
                                            :checked="record.is_default"
                                            :loading="settingDefault === record.xid"
                                            :disabled="record.is_default"
                                            @change="() => setAsDefault(record.xid)"
                                            checked-children="Yes"
                                            un-checked-children="No"
                                            size="small"
                                        />
                                    </template>
                                    <template v-else-if="column.dataIndex === 'action'">
                                        <a-space>
                                            <a-button
                                                v-if="
                                                    permsArray.includes(
                                                        'website_languages_view'
                                                    ) || permsArray.includes('admin')
                                                "
                                                type="primary"
                                                @click="viewItem(record)"
                                            >
                                                <template #icon><EyeOutlined /></template>
                                            </a-button>
                                            <a-button
                                                v-if="
                                                    permsArray.includes(
                                                        'website_languages_edit'
                                                    ) || permsArray.includes('admin')
                                                "
                                                type="primary"
                                                @click="editItem(record)"
                                            >
                                                <template #icon
                                                    ><EditOutlined
                                                /></template>
                                            </a-button>
                                            <a-button
                                                v-if="
                                                    !record.is_default &&
                                                    (permsArray.includes(
                                                        'website_languages_delete'
                                                    ) ||
                                                        permsArray.includes('admin'))
                                                "
                                                type="primary"
                                                @click="showDeleteConfirm(record.xid)"
                                            >
                                                <template #icon
                                                    ><DeleteOutlined
                                                /></template>
                                            </a-button>
                                        </a-space>
                                    </template>
                                </template>
                            </a-table>
                        </div>
                    </a-col>
                </a-row>
                <View
                    :data="viewData"
                    :visible="detailsVisible"
                    @closed="onCloseDetails"
                />
            </admin-page-table-content>
        </a-col>
    </a-row>
</template>

<script setup>
import { ref, watch, createVNode } from "vue";
import {
    EyeOutlined,
    PlusOutlined,
    EditOutlined,
    DeleteOutlined,
    ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import { Modal, notification } from "ant-design-vue";
import { forEach } from "lodash-es";
import fields from "./fields";
import AddEdit from "./AddEdit.vue";
import View from "./View.vue";
import { useAuthStore } from "../../store/authStore";
import { storeToRefs } from "pinia";
import SelectedWebsiteBreadcrumb from "../../../common/components/SelectedWebsiteBreadcrumb.vue";
import { useI18n } from "vue-i18n";
import { getFlagEmoji } from "../../../common/scripts/countryCodes";

// 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);

const {
    url,
    addEditUrl,
    initData,
    columns,
    filterableColumns,
    hashableColumns,
} = fields();

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

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

// Loading state for set default action
const settingDefault = ref(null);

// Set a language as default
const setAsDefault = (xid) => {
    settingDefault.value = xid;
    axiosAdmin
        .post(`website-languages/${xid}/set-default`)
        .then((response) => {
            if (response.status === "success") {
                // Update local table data - set this as default, unset others
                // Also enable the language if it was disabled
                table.data.forEach((lang) => {
                    if (lang.xid === xid) {
                        lang.is_default = true;
                        lang.enabled = true;
                    } else {
                        lang.is_default = false;
                    }
                });
                notification.success({
                    message: t("common.success"),
                    description: t("website_language.default_updated"),
                    placement: "bottomRight",
                });
            }
        })
        .catch(() => {
            notification.error({
                message: t("common.error"),
                description: t("common.something_went_wrong"),
                placement: "bottomRight",
            });
        })
        .finally(() => {
            settingDefault.value = null;
        });
};

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

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

// Define setUrlData BEFORE the watcher that uses it
const setUrlData = () => {
    // Set hashable columns BEFORE fetching data so website_id is properly converted
    crudhashableColumns.value = [...hashableColumns];

    tableUrl.value = {
        url,
        extraFilters,
    };

    table.filterableColumns = filterableColumns;

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

    // 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();
        }
    },
    { immediate: true }
);

// Custom delete confirm handler
const showDeleteConfirm = (id) => {
    Modal.confirm({
        title: t("common.delete") + "?",
        icon: createVNode(ExclamationCircleOutlined),
        content: t("website_language.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_language.deleted"),
                        placement: "bottomRight",
                    });
                })
                .catch(() => {});
        },
        onCancel() {},
    });
};

// Custom selected delete confirm handler
const showSelectedDeleteConfirm = () => {
    Modal.confirm({
        title: t("common.delete") + "?",
        icon: createVNode(ExclamationCircleOutlined),
        content: t("website_language.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_language.deleted"),
                    placement: "bottomRight",
                });
            });
        },
        onCancel() {},
    });
};

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

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

.lang-name-cell {
    display: flex;
    align-items: center;
    gap: 12px;
}

.flag-emoji {
    font-size: 24px;
    line-height: 1;
}

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

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

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

:global(.dark_theme) .lang-name-link:hover {
    color: #3c9ae8;
}
</style>
