<template>
    <div class="default-main admin-report-page submitted-rewards">
        <nav class="admin-report-tabs reward-tabs" :aria-label="t('user.submittedReward.Promotion type')">
            <button
                v-for="tab in promotionTabs"
                :key="tab.value"
                type="button"
                :class="{ active: filters.gameId === tab.value }"
                @click="changePromotion(tab.value)"
            >
                {{ tab.label }}
            </button>
        </nav>

        <section class="admin-report-filter reward-panel">
            <header class="admin-report-heading panel-heading">
                <span>{{ t('user.submittedReward.Submitted Rewards') }} ({{ activePromotionLabel }})</span>
                <strong>{{ t('user.submittedReward.Running') }}</strong>
            </header>

            <div class="admin-report-filter-content filter-panel">
                <div class="filter-item">
                    <label>{{ t('user.submittedReward.Start Date') }}:</label>
                    <el-date-picker v-model="filters.start" type="date" value-format="YYYY-MM-DD" :clearable="false" />
                </div>
                <div class="filter-item">
                    <label>{{ t('user.submittedReward.End Date') }}:</label>
                    <el-date-picker v-model="filters.end" type="date" value-format="YYYY-MM-DD" :clearable="false" />
                </div>
                <div class="filter-item">
                    <label>{{ t('user.submittedReward.Status') }}:</label>
                    <el-select v-model="filters.status">
                        <el-option :label="t('user.submittedReward.All status')" value="all" />
                        <el-option :label="t('user.submittedReward.Approve Reward')" value="1" />
                        <el-option :label="t('user.submittedReward.Reject Reward')" value="2" />
                        <el-option :label="t('user.submittedReward.In process')" value="0" />
                    </el-select>
                </div>
                <div class="filter-item">
                    <label>{{ t('user.submittedReward.Username') }}:</label>
                    <el-input
                        v-model.trim="filters.username"
                        :placeholder="t('user.submittedReward.Search by username')"
                        clearable
                        @keyup.enter="search"
                    />
                </div>
                <div class="admin-report-actions filter-actions">
                    <el-button type="primary" @click="search">{{ t('Search') }}</el-button>
                    <el-button @click="clearFilters">{{ t('user.submittedReward.Clear') }}</el-button>
                </div>
            </div>
        </section>

        <div class="admin-report-summary date-summary">
            <strong>{{ t('user.submittedReward.Date of data') }}:</strong>
            {{ dateRangeText }}
        </div>

        <div v-loading="loading" class="admin-report-table-wrap reward-table-wrap">
            <table class="admin-report-table reward-table">
                <thead>
                    <tr>
                        <th class="submitted-time">{{ t('user.submittedReward.Submitted Time') }}</th>
                        <th class="username">{{ t('user.submittedReward.Username') }}</th>
                        <th class="reward-claim">{{ t('user.submittedReward.Reward Claim') }}</th>
                        <th>{{ t('user.submittedReward.Status') }}</th>
                        <th class="action">{{ t('user.submittedReward.Action') }}</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="row in rows" :key="row.id">
                        <td>{{ row.submittedTime }}</td>
                        <td>{{ row.username }}</td>
                        <td>{{ row.rewardClaim }}</td>
                        <td>{{ row.status }}</td>
                        <td>
                            <div v-if="row.statusCode === 0" class="action-buttons">
                                <el-button type="success" size="small" :loading="actionLoadingId === row.id" @click="confirmReward(row, 1)">
                                    {{ t('user.submittedReward.Agree') }}
                                </el-button>
                                <el-button type="danger" size="small" :loading="actionLoadingId === row.id" @click="confirmReward(row, 2)">
                                    {{ t('user.submittedReward.Reject') }}
                                </el-button>
                            </div>
                        </td>
                    </tr>
                    <tr v-if="!loading && rows.length === 0">
                        <td class="empty-row" colspan="5">{{ t('user.submittedReward.No records') }}</td>
                    </tr>
                </tbody>
            </table>
        </div>

        <div class="admin-report-footer table-footer">
            <span>{{ t('user.submittedReward.Total records', { total: pagination.total }) }}</span>
            <el-pagination
                v-if="pagination.total > 0"
                v-model:current-page="pagination.currentPage"
                background
                layout="prev, pager, next"
                :page-size="pagination.pageSize"
                :total="pagination.total"
                @current-change="changePage"
            />
        </div>
    </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessageBox } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { editReward, getSubmittedRewards, type SubmittedRewardParams } from '/@/api/backend/user/submittedReward'

defineOptions({
    name: 'user/submittedReward',
})

type GameId = 268 | 269 | 270

interface RewardRow {
    id: number | string
    submittedTime: string
    username: string
    rewardClaim: string
    status: string
    statusCode: number
}

const { t } = useI18n()

const formatDate = (date: Date) => {
    const pad = (value: number) => String(value).padStart(2, '0')
    return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`
}

const today = () => formatDate(new Date())

const promotionTabs: { label: string; value: GameId }[] = [
    { label: 'Plinko Ball', value: 268 },
    { label: 'Smash Eggs', value: 269 },
    { label: 'Spin Wheel', value: 270 },
]

const filters = reactive({
    gameId: 268 as GameId,
    start: today(),
    end: today(),
    status: 'all' as 'all' | SubmittedRewardParams['status'],
    username: '',
})

const pagination = reactive({
    currentPage: 1,
    pageSize: 20,
    total: 0,
})

const rows = ref<RewardRow[]>([])
const loading = ref(false)
const actionLoadingId = ref<number | string | null>(null)

const activePromotionLabel = computed(() => {
    const labelMap: Record<GameId, string> = {
        268: 'Plinko Ball',
        269: 'Smash Eggs',
        270: 'Spin Wheel',
    }
    return labelMap[filters.gameId]
})

const dateRangeText = computed(() => {
    const start = new Date(`${filters.start}T00:00:00`)
    const end = new Date(`${filters.end}T00:00:00`)
    const duration = Math.max(1, Math.floor((end.getTime() - start.getTime()) / 86400000) + 1)
    const range = filters.start === filters.end ? filters.start : `${filters.start} ${t('user.submittedReward.to')} ${filters.end}`
    return `${range} (${duration} ${duration === 1 ? t('user.submittedReward.Day') : t('user.submittedReward.Days')})`
})

const mapRow = (item: Record<string, any>, index: number): RewardRow => {
    return {
        id: item.id ?? `${pagination.currentPage}-${index}`,
        submittedTime: String(item.submitted_time ?? ''),
        username: String(item.username ?? ''),
        rewardClaim: String(item.reward_claim ?? ''),
        status: String(item.status_text ?? ''),
        statusCode: Number(item.status),
    }
}

const normalizeResponse = (responseData: any) => {
    const source = responseData?.data ?? responseData ?? {}
    const list = source.list ?? {}
    const data = Array.isArray(list.data) ? list.data : []
    const total = Number(list.total ?? list.count ?? data.length)
    const pageSize = Number(list.per_page ?? list.page_size ?? pagination.pageSize)
    const currentPage = Number(list.current_page ?? list.page ?? pagination.currentPage)

    return {
        rows: data.map((item: Record<string, any>, index: number) => mapRow(item, index)),
        total: Number.isFinite(total) ? total : 0,
        pageSize: Number.isFinite(pageSize) && pageSize > 0 ? pageSize : 20,
        currentPage: Number.isFinite(currentPage) && currentPage > 0 ? currentPage : 1,
    }
}

const loadRewards = async (page = pagination.currentPage) => {
    loading.value = true
    try {
        const response = await getSubmittedRewards({
            start: filters.start,
            end: filters.end,
            status: filters.status === 'all' ? '' : filters.status,
            username: filters.username,
            game_id: filters.gameId,
            page,
        })
        const normalized = normalizeResponse(response.data)
        rows.value = normalized.rows
        pagination.total = normalized.total
        pagination.pageSize = normalized.pageSize
        pagination.currentPage = normalized.currentPage
    } finally {
        loading.value = false
    }
}

const search = () => {
    pagination.currentPage = 1
    loadRewards(1)
}

const clearFilters = () => {
    filters.start = today()
    filters.end = today()
    filters.status = 'all'
    filters.username = ''
    pagination.currentPage = 1
    loadRewards(1)
}

const changePromotion = (gameId: GameId) => {
    filters.gameId = gameId
    pagination.currentPage = 1
    loadRewards(1)
}

const changePage = (page: number) => {
    loadRewards(page)
}

const confirmReward = (row: RewardRow, status: 1 | 2) => {
    const action = status === 1 ? t('user.submittedReward.Agree') : t('user.submittedReward.Reject')

    ElMessageBox.confirm(
        t('user.submittedReward.Confirm reward action', {
            action,
            username: row.username,
        }),
        t('Confirm'),
        {
            confirmButtonText: t('Confirm'),
            cancelButtonText: t('Cancel'),
            type: status === 1 ? 'success' : 'warning',
        }
    )
        .then(() => {
            actionLoadingId.value = row.id
            return editReward({ id: row.id, status })
        })
        .then(() => loadRewards(pagination.currentPage))
        .finally(() => {
            actionLoadingId.value = null
        })
        .catch(() => {
            // Closing the confirmation dialog does not require feedback.
        })
}

onMounted(() => {
    loadRewards(1)
})
</script>

<style scoped lang="scss">
.submitted-rewards {
    padding: var(--ba-main-space);
}

.reward-tabs {
    button {
        min-width: 136px;

        &:last-child {
            min-width: 112px;
        }
    }
}

.panel-heading {
    justify-content: flex-start;

    strong {
        margin-left: 4px;
    }
}

.filter-panel {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 12px 24px;
}

.filter-item {
    label {
        min-width: 76px;
        text-align: right;
    }

    :deep(.el-date-editor),
    :deep(.el-select),
    :deep(.el-input) {
        width: 200px;
    }
}

.filter-actions {
    .el-button {
        min-width: 92px;
    }
}

.reward-table {
    min-width: 850px;

    .submitted-time {
        width: 150px;
    }

    .username {
        width: 100px;
    }

    .reward-claim {
        width: 180px;
    }

    .action {
        width: 180px;
    }
}

.action-buttons {
    display: flex;
    gap: 8px;

    .el-button {
        margin: 0;
    }
}

@media (max-width: 900px) {
    .submitted-rewards {
        padding: 12px;
    }

    .reward-tabs {
        width: 100%;
        overflow-x: auto;

        button {
            min-width: 125px;
        }
    }

    .filter-panel {
        align-items: flex-start;
        flex-direction: column;
    }
}
</style>
