<template>
    <div v-loading="loading" class="default-main partnership-page">
        <section class="setting-grid">
            <div class="panel setting-panel">
                <div class="panel-title">{{ t('embed.partnership.settingTitle') }}</div>
                <div class="panel-body setting-form">
                    <div class="form-row">
                        <label>{{ t('embed.partnership.headerImage') }}:</label>
                        <el-input v-model="settings.headerImage" placeholder="e.g. https://image.png" />
                    </div>

                    <div class="form-row textarea-row">
                        <label>{{ t('embed.partnership.footerConfig') }}:</label>
                        <el-input v-model="settings.footerConfig" type="textarea" :rows="8" :placeholder="footerTemplate" resize="vertical" />
                    </div>
                    <div class="form-row template-row">
                        <label></label>
                        <el-button size="small" @click="settings.footerConfig = footerTemplate">
                            {{ t('embed.partnership.loadTemplate') }}
                        </el-button>
                    </div>

                    <div class="form-row textarea-row">
                        <label>{{ t('embed.partnership.customConfig') }}:</label>
                        <el-input v-model="settings.customConfig" type="textarea" :rows="7" :placeholder="customTemplate" resize="vertical" />
                    </div>
                    <div class="form-row template-row">
                        <label></label>
                        <el-button size="small" @click="settings.customConfig = customTemplate">
                            {{ t('embed.partnership.loadTemplate') }}
                        </el-button>
                    </div>

                    <div class="color-grid">
                        <div v-for="item in colorFields" :key="item.key" class="color-item">
                            <label>{{ t(item.label) }}:</label>
                            <el-color-picker v-model="settings[item.key]" />
                            <span>{{ settings[item.key] }}</span>
                        </div>
                    </div>

                    <el-button type="success" class="save-button" :loading="savingSettings" @click="saveSettings">
                        {{ t('embed.partnership.save') }}
                    </el-button>
                </div>
            </div>

            <div class="panel embed-panel">
                <div class="panel-title">{{ t('embed.partnership.embedCode') }}</div>
                <div class="panel-body">
                    <el-input v-model="embedCode" type="textarea" :rows="19" readonly resize="none" />
                    <el-button class="copy-button" @click="copyEmbedCode">{{ t('embed.partnership.copyCode') }}</el-button>
                </div>
            </div>
        </section>

        <section class="panel data-panel">
            <div class="panel-title">{{ t('embed.partnership.dataTitle') }}</div>
            <div class="table-wrap">
                <el-table :data="partners" border :empty-text="t('embed.partnership.empty')">
                    <el-table-column prop="displayOrder" :label="t('embed.partnership.displayOrder')" width="140" />
                    <el-table-column prop="name" :label="t('embed.partnership.partnerName')" min-width="180" />
                    <el-table-column prop="currency" :label="t('embed.partnership.currency')" width="130" />
                    <el-table-column :label="t('embed.partnership.logoImage')" min-width="240">
                        <template #default="{ row }">
                            <a v-if="row.logoImage" class="image-link" :href="row.logoImage" target="_blank" rel="noopener noreferrer">
                                {{ row.logoImage }}
                            </a>
                            <span v-else>-</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="option" :label="t('embed.partnership.option')" min-width="180" show-overflow-tooltip />
                    <el-table-column prop="config" :label="t('embed.partnership.config')" min-width="220" show-overflow-tooltip />
                    <el-table-column :label="t('embed.partnership.status')" width="110" align="center">
                        <template #default="{ row }">
                            <el-tag :type="row.status === 1 ? 'success' : 'info'" effect="plain">
                                {{ row.status === 1 ? t('embed.partnership.active') : t('embed.partnership.inactive') }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column :label="t('embed.partnership.action')" width="150" fixed="right">
                        <template #default="{ row }">
                            <el-button link type="primary" @click="openDialog('edit', row)">{{ t('embed.partnership.edit') }}</el-button>
                            <el-button link type="danger" @click="removePartner(row)">{{ t('embed.partnership.delete') }}</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </section>

        <div class="bottom-actions">
            <el-button type="success" class="create-button" @click="openDialog('create')">
                {{ t('embed.partnership.create') }}
            </el-button>
            <el-button type="primary" @click="exportPartners">{{ t('embed.partnership.export') }}</el-button>
            <el-upload
                accept=".json,application/json"
                :auto-upload="false"
                :show-file-list="false"
                :on-change="importPartners"
            >
                <el-button type="warning">{{ t('embed.partnership.import') }}</el-button>
            </el-upload>
        </div>

        <el-dialog
            v-model="dialogVisible"
            :title="dialogMode === 'create' ? t('embed.partnership.createTitle') : t('embed.partnership.editTitle')"
            width="600px"
            destroy-on-close
        >
            <el-form ref="formRef" :model="form" :rules="rules" label-position="top">
                <div class="dialog-grid">
                    <el-form-item :label="t('embed.partnership.displayOrder')" prop="displayOrder">
                        <el-input-number v-model="form.displayOrder" :min="0" />
                    </el-form-item>
                    <el-form-item :label="t('embed.partnership.currency')" prop="currency">
                        <el-input v-model="form.currency" placeholder="AUD" />
                    </el-form-item>
                </div>
                <el-form-item :label="t('embed.partnership.partnerName')" prop="name">
                    <el-input v-model="form.name" />
                </el-form-item>
                <el-form-item :label="t('embed.partnership.logoImage')" prop="logoImage">
                    <el-input v-model="form.logoImage" placeholder="https://image.png" />
                </el-form-item>
                <el-form-item :label="t('embed.partnership.option')">
                    <el-input v-model="form.option" type="textarea" :rows="3" placeholder="{}" />
                </el-form-item>
                <el-form-item :label="t('embed.partnership.config')">
                    <el-input v-model="form.config" type="textarea" :rows="3" placeholder="{}" />
                </el-form-item>
                <el-form-item :label="t('embed.partnership.status')">
                    <el-select v-model="form.status">
                        <el-option :label="t('embed.partnership.active')" :value="1" />
                        <el-option :label="t('embed.partnership.inactive')" :value="2" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">{{ t('embed.partnership.cancel') }}</el-button>
                <el-button type="primary" @click="submitForm">{{ t('embed.partnership.confirm') }}</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules, UploadFile } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { computed, onMounted, reactive, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { partnership, savePartnershipSet } from '/@/api/backend/embed'

defineOptions({
    name: 'embed/partnership',
})

interface PartnerRow {
    id: number
    displayOrder: number
    name: string
    currency: string
    logoImage: string
    option: string
    config: string
    status: number
}

interface PartnershipSetting {
    header_image_url?: string | null
    footer_config?: string | Record<string, unknown> | null
    custom_config?: string | Record<string, unknown> | null
    base_color_1?: string | null
    base_color_2?: string | null
    border_color?: string | null
    highlight_color?: string | null
    title_color?: string | null
    text_color?: string | null
}

interface PartnerSourceRow {
    id?: number | string
    display_order?: number | string
    displayOrder?: number | string
    weigh?: number | string
    partner_name?: string
    name?: string
    currency?: string
    logo_image?: string
    logoImage?: string
    option?: string | Record<string, unknown> | null
    config?: string | Record<string, unknown> | null
    status?: number | string
}

type ColorSettingKey = 'baseColor1' | 'baseColor2' | 'borderColor' | 'highlightColor' | 'titleColor' | 'textColor'

const { t } = useI18n()

const footerTemplate = `{
    "infoText": "We specialise in curating Asia's top licensed gaming and entertainment platforms, delivering the safest, most transparent, and most rewarding experience for every member.",
    "label": {
        "highlight": ["PAGCOR Licensed", "SSL Encrypted"],
        "normal": ["10+ Top Platforms", "Instant Payouts", "24/7 Support"]
    },
    "sections": [
        {
            "title": "Partner Advantages",
            "items": [
                "Exclusive negotiated deals you won't find anywhere else",
                "New member welcome bonus up to 200% on first deposit",
                "Unlimited daily cashback, the more you play, the more you earn"
            ]
        },
        {
            "title": "Security Guarantee",
            "items": [
                "Platform-wide 256-bit SSL encryption end-to-end",
                "RNG independently certified by third-party auditors",
                "Segregated player funds"
            ]
        },
        {
            "title": "Withdrawal Promise",
            "items": [
                "As fast as 3 minutes",
                "24-hour withdrawal channel",
                "Zero transaction fees"
            ]
        }
    ]
}`

const customTemplate = `{
    "hideSection": [
        "partnerCard",
        "partnerWithdrawal",
        "payoutRates",
        "partnerReviews",
        "footer"
    ]
}`

const settings = reactive<Record<ColorSettingKey, string> & {
    headerImage: string
    footerConfig: string
    customConfig: string
}>({
    headerImage: '',
    footerConfig: footerTemplate,
    customConfig: '',
    baseColor1: '#151921',
    baseColor2: '#1c2130',
    borderColor: '#2a3147',
    highlightColor: '#f0b429',
    titleColor: '#e2e8f0',
    textColor: '#718096',
})

const colorFields: { key: ColorSettingKey; label: string }[] = [
    { key: 'baseColor1', label: 'embed.partnership.baseColor1' },
    { key: 'highlightColor', label: 'embed.partnership.highlightColor' },
    { key: 'baseColor2', label: 'embed.partnership.baseColor2' },
    { key: 'titleColor', label: 'embed.partnership.titleColor' },
    { key: 'borderColor', label: 'embed.partnership.borderColor' },
    { key: 'textColor', label: 'embed.partnership.textColor' },
]

const embedCode = ref(`<div style="position: relative;max-width: 1000px;margin: 0 auto;overflow: hidden;border: none;">
    <iframe id="partnershipIframe" src="https://1xaud.em7bd7.co/embed/partnership/partnership.asp" style="width: 100%;overflow: hidden;border: none;"></iframe>
    <script>
        (() => {
            const merchantId = (typeof _ !== "undefined" && typeof _.getVar === "function") ? (_.getVar("merchantId") ?? "") : "";
            if (!merchantId) {
                console.log("merchantId not found");
                return;
            }
            function init(iframe) {
                iframe.addEventListener('load', function() {
                    iframe.contentWindow.postMessage({ type: 'setIframeData', clientMerchant: merchantId }, '*');
                });
                window.addEventListener("message", function(event) {
                    if (event.data && event.data.type === "setPartnershipIframeHeight") {
                        iframe.style.height = event.data.height + "px";
                    }
                }, false);
            }
            var el = document.getElementById('partnershipIframe');
            if (el) { init(el); return; }
            var attempts = 0;
            var timer = setInterval(function() {
                attempts++;
                var el = document.getElementById('partnershipIframe');
                if (el) {
                    clearInterval(timer);
                    init(el);
                } else if (attempts >= 5) {
                    clearInterval(timer);
                    alert("iframe not found");
                }
            }, 1000);
        })();
    <\/script>
</div>`)

const partners = ref<PartnerRow[]>([])
const loading = ref(false)

const formatJsonValue = (value: string | Record<string, unknown> | null | undefined) => {
    if (!value) return ''
    return typeof value === 'string' ? value : JSON.stringify(value, null, 2)
}

const applyPartnershipSetting = (setting?: PartnershipSetting) => {
    if (!setting) return
    settings.headerImage = setting.header_image_url ?? ''
    settings.footerConfig = formatJsonValue(setting.footer_config)
    settings.customConfig = formatJsonValue(setting.custom_config)
    settings.baseColor1 = setting.base_color_1 ?? ''
    settings.baseColor2 = setting.base_color_2 ?? ''
    settings.borderColor = setting.border_color ?? ''
    settings.highlightColor = setting.highlight_color ?? ''
    settings.titleColor = setting.title_color ?? ''
    settings.textColor = setting.text_color ?? ''
}

const normalizePartnerData = (value: unknown): PartnerRow[] => {
    if (!Array.isArray(value)) return []
    return value.map((item: PartnerSourceRow, index) => ({
        id: Number(item.id) || index + 1,
        displayOrder: Number(item.display_order ?? item.displayOrder ?? item.weigh) || index + 1,
        name: String(item.partner_name ?? item.name ?? ''),
        currency: String(item.currency ?? ''),
        logoImage: String(item.logo_image ?? item.logoImage ?? ''),
        option: formatJsonValue(item.option),
        config: formatJsonValue(item.config),
        status: Number(item.status) === 1 ? 1 : 2,
    }))
}

const loadPartnership = async () => {
    loading.value = true
    try {
        const response = await partnership()
        const data = response.data ?? response
        applyPartnershipSetting(data?.partnership_setting)
        partners.value = normalizePartnerData(data?.partner_data)
    } finally {
        loading.value = false
    }
}

const parseJsonObject = (value: string) => {
    if (!value.trim()) return {}
    const parsed = JSON.parse(value)
    if (!parsed || Array.isArray(parsed) || typeof parsed !== 'object') throw new Error()
    return parsed as Record<string, unknown>
}

const savingSettings = ref(false)

const saveSettings = async () => {
    let footerConfig: Record<string, unknown>
    let customConfig: Record<string, unknown>
    try {
        footerConfig = parseJsonObject(settings.footerConfig)
        customConfig = parseJsonObject(settings.customConfig)
    } catch {
        ElMessage.error(t('embed.partnership.invalidConfig'))
        return
    }

    savingSettings.value = true
    try {
        await savePartnershipSet({
            header_image_url: settings.headerImage,
            footer_config: footerConfig,
            custom_config: customConfig,
            base_color_1: settings.baseColor1,
            base_color_2: settings.baseColor2,
            border_color: settings.borderColor,
            highlight_color: settings.highlightColor,
            title_color: settings.titleColor,
            text_color: settings.textColor,
        })
        await loadPartnership()
    } finally {
        savingSettings.value = false
    }
}

const copyEmbedCode = async () => {
    try {
        await navigator.clipboard.writeText(embedCode.value)
        ElMessage.success(t('embed.partnership.copied'))
    } catch {
        ElMessage.error(t('embed.partnership.copyFailed'))
    }
}

onMounted(loadPartnership)

const dialogVisible = ref(false)
const dialogMode = ref<'create' | 'edit'>('create')
const editingId = ref<number>()
const formRef = ref<FormInstance>()
const form = reactive({
    displayOrder: 0,
    name: '',
    currency: 'AUD',
    logoImage: '',
    option: '',
    config: '',
    status: 1,
})
const rules = computed<FormRules>(() => ({
    name: [{ required: true, message: t('embed.partnership.nameRequired'), trigger: 'blur' }],
    currency: [{ required: true, message: t('embed.partnership.currencyRequired'), trigger: 'blur' }],
}))

const openDialog = (mode: 'create' | 'edit', row?: PartnerRow) => {
    dialogMode.value = mode
    editingId.value = row?.id
    Object.assign(
        form,
        row ?? {
            displayOrder: partners.value.length + 1,
            name: '',
            currency: 'AUD',
            logoImage: '',
            option: '',
            config: '',
            status: 1,
        }
    )
    dialogVisible.value = true
}

const submitForm = async () => {
    if (!(await formRef.value?.validate().catch(() => false))) return
    try {
        if (form.option) JSON.parse(form.option)
        if (form.config) JSON.parse(form.config)
    } catch {
        ElMessage.error(t('embed.partnership.invalidPartnerConfig'))
        return
    }

    if (dialogMode.value === 'create') {
        const nextId = Math.max(0, ...partners.value.map((partner) => partner.id)) + 1
        partners.value.push({ id: nextId, ...form })
    } else {
        const index = partners.value.findIndex((partner) => partner.id === editingId.value)
        if (index >= 0) partners.value[index] = { id: editingId.value!, ...form }
    }
    partners.value.sort((a, b) => a.displayOrder - b.displayOrder)
    dialogVisible.value = false
    ElMessage.success(t('embed.partnership.operationSuccess'))
}

const removePartner = async (row: PartnerRow) => {
    try {
        await ElMessageBox.confirm(t('embed.partnership.deleteConfirm', { name: row.name }), t('embed.partnership.warning'), {
            type: 'warning',
            confirmButtonText: t('embed.partnership.confirm'),
            cancelButtonText: t('embed.partnership.cancel'),
        })
        partners.value = partners.value.filter((partner) => partner.id !== row.id)
        ElMessage.success(t('embed.partnership.deleted'))
    } catch {
        return
    }
}

const exportPartners = () => {
    const blob = new Blob([JSON.stringify(partners.value, null, 2)], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = 'partner-data.json'
    link.click()
    URL.revokeObjectURL(url)
    ElMessage.success(t('embed.partnership.exported'))
}

const importPartners = async (uploadFile: UploadFile) => {
    if (!uploadFile.raw) return
    try {
        const data = JSON.parse(await uploadFile.raw.text())
        if (!Array.isArray(data)) throw new Error('Invalid partner data')
        const imported = data.map((item, index) => ({
            id: Number(item.id) || index + 1,
            displayOrder: Number(item.displayOrder) || index + 1,
            name: String(item.name ?? ''),
            currency: String(item.currency ?? ''),
            logoImage: String(item.logoImage ?? ''),
            option: typeof item.option === 'string' ? item.option : JSON.stringify(item.option ?? {}),
            config: typeof item.config === 'string' ? item.config : JSON.stringify(item.config ?? {}),
            status: Number(item.status) === 2 ? 2 : 1,
        }))
        await ElMessageBox.confirm(t('embed.partnership.importConfirm', { total: imported.length }), t('embed.partnership.warning'), {
            type: 'warning',
            confirmButtonText: t('embed.partnership.confirm'),
            cancelButtonText: t('embed.partnership.cancel'),
        })
        partners.value = imported
        ElMessage.success(t('embed.partnership.imported'))
    } catch (error) {
        if (error === 'cancel' || error === 'close') return
        ElMessage.error(t('embed.partnership.importFailed'))
    }
}
</script>

<style scoped lang="scss">
.partnership-page {
    padding: var(--ba-main-space);
    color: var(--el-text-color-primary);
}

.setting-grid {
    display: grid;
    grid-template-columns: minmax(560px, 7fr) minmax(380px, 3fr);
    gap: 14px;
    margin-bottom: 14px;
}

.panel {
    overflow: hidden;
    border: 1px solid var(--el-border-color);
    border-radius: 4px;
    background: var(--el-bg-color);
}

.panel-title {
    padding: 10px 14px;
    color: #fff;
    font-size: 14px;
    font-weight: 700;
    background: #333;
}

.panel-body {
    padding: 16px;
}

.setting-form {
    min-height: 510px;
}

.form-row {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 8px;

    > label {
        width: 195px;
        flex: 0 0 195px;
        text-align: right;
        font-weight: 600;
    }

    :deep(.el-input) {
        flex: 1;
    }
}

.textarea-row {
    align-items: flex-start;
}

.template-row {
    margin-top: -2px;
    margin-bottom: 10px;
}

.color-grid {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: 12px 22px;
    margin: 18px 0;
}

.color-item {
    display: flex;
    align-items: center;
    gap: 8px;

    label {
        min-width: 145px;
        text-align: right;
        font-weight: 600;
    }

    span {
        color: var(--el-text-color-secondary);
        font-family: monospace;
        font-size: 12px;
    }
}

.save-button {
    width: calc(100% - 207px);
    margin-left: 207px;
    font-weight: 700;
}

.embed-panel {
    :deep(textarea) {
        padding: 14px;
        color: var(--el-text-color-primary);
        background: var(--el-fill-color-light);
        font-family: monospace;
        font-size: 12px;
        line-height: 1.55;
    }
}

.copy-button {
    width: 100%;
    margin-top: 12px;
}

.table-wrap {
    overflow-x: auto;
}

.image-link {
    display: block;
    overflow: hidden;
    color: var(--el-color-primary);
    text-overflow: ellipsis;
    white-space: nowrap;
}

.bottom-actions {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
    margin-top: 14px;

    .create-button {
        grid-column: 1 / -1;
    }

    .el-button,
    :deep(.el-upload),
    :deep(.el-upload .el-button) {
        width: 100%;
        height: 38px;
        margin: 0;
        font-weight: 700;
    }
}

.dialog-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 16px;
}

@media (max-width: 1100px) {
    .setting-grid {
        grid-template-columns: 1fr;
    }
}

@media (max-width: 720px) {
    .partnership-page {
        padding: 12px;
    }

    .form-row {
        align-items: stretch;
        flex-direction: column;
        gap: 6px;

        > label {
            width: auto;
            flex-basis: auto;
            text-align: left;
        }
    }

    .color-grid,
    .dialog-grid,
    .bottom-actions {
        grid-template-columns: 1fr;
    }

    .color-item label {
        min-width: 130px;
        text-align: left;
    }

    .save-button {
        width: 100%;
        margin-left: 0;
    }

    .bottom-actions .create-button {
        grid-column: auto;
    }
}
</style>
