<template>
    <div>
        <!-- Breadcrumb Header -->
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Dashboard Giám sát</h4>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="javascript:void(0);">Trang chủ</a></li>
                    <li class="breadcrumb-item active" aria-current="page">Giám sát</li>
                </ol>
            </div>
        </div>

        <!-- Main Content -->
        <div class="row row-sm">
            <div class="col-sm-12 col-md-12 col-lg-12 col-xl-12 grid-margin">

                <!-- Filter Card -->
                <div class="card card-search shadow-none">
                    <form class="card-body" @submit.prevent="loadOverview">
                        <div class="row">
                            <div class="col-lg-4 col-md-6 mb-3">
                                <label>Từ ngày - Đến ngày</label>
                                <DatepickerInstance ref="datePicker" v-model="dateRange" :enable-time-picker="false"
                                    range multi-calendars auto-apply :format="formatDateRange"
                                    @update:model-value="handleDateChange">
                                    <template #left-sidebar>
                                        <DateRangeSidebar @change-date="onChangeDate"></DateRangeSidebar>
                                    </template>
                                </DatepickerInstance>
                            </div>

                            <div class="col-lg-2 col-md-6 mb-3 d-flex align-items-end">
                                <button type="submit" class="btn btn-dark" :disabled="loading">
                                    <i v-show="!loading" class="fe fe-search"></i>
                                    <span v-show="loading" class="spinner-border spinner-border-sm"></span>
                                    <span>Tìm kiếm</span>
                                </button>
                            </div>
                        </div>
                    </form>
                </div>

                <!-- Risk Cards Row -->
                <div v-if="overview || destCashierOverview || bothPayOverview" class="row mt-2">
                    <!-- Source Fee Risk Card -->
                    <RiskSourceFeeCard v-if="overview" :risk-info="overview.RiskInfo"
                        :total-orders="overview.TotalOrders" :total-source-fee="overview.TotalSourceFee"
                        :filters="filters" />

                    <!-- Dest Fee Risk Card -->
                    <RiskDestFeeCard v-if="destCashierOverview" :risk-info="destCashierOverview.RiskInfo"
                        :total-orders="destCashierOverview.TotalOrders"
                        :total-dest-fee="destCashierOverview.TotalDestFee" :filters="filters" />

                    <!-- BothPay Risk Card -->
                    <RiskBothPayCard v-if="bothPayOverview" :risk-info="bothPayOverview.RiskInfo"
                        :total-orders="bothPayOverview.TotalOrders" :total-source-fee="bothPayOverview.TotalSourceFee"
                        :total-dest-fee="bothPayOverview.TotalDestFee" :filters="filters" />

                    <!-- Placeholder for future risk cards -->
                    <!-- Add more risk cards here as needed -->
                </div>

                <!-- Loading State -->
                <div v-if="loading && !overview && !destCashierOverview && !bothPayOverview" class="card shadow-none">
                    <div class="card-body text-center py-5">
                        <span class="spinner-border spinner-border-lg"></span>
                        <p class="mt-3 text-muted">Đang tải dữ liệu...</p>
                    </div>
                </div>

                <!-- Empty State -->
                <div v-if="!loading && !overview && !destCashierOverview && !bothPayOverview" class="card shadow-none">
                    <div class="card-body text-center py-5">
                        <i class="fe fe-inbox" style="font-size: 48px; color: #ccc;"></i>
                        <p class="mt-3 text-muted">Không có dữ liệu giám sát</p>
                        <p class="text-muted small">Thử thay đổi bộ lọc và tìm kiếm lại</p>
                    </div>
                </div>

            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useToast } from 'vue-toastification'
import monitorService from '@/services/monitorService'
import DatepickerInstance from "@vuepic/vue-datepicker"
import { DateRangeSidebar } from '@/components/index'
import RiskSourceFeeCard from './components/source-cashier/RiskSourceFeeCard.vue'
import RiskDestFeeCard from './components/dest-cashier/RiskDestFeeCard.vue'
import RiskBothPayCard from './components/both-pay/RiskBothPayCard.vue'

const toast = useToast()

// Data
const loading = ref(false)
const overview = ref(null)
const destCashierOverview = ref(null)
const bothPayOverview = ref(null)
const dateRange = ref(null)
const datePicker = ref(null)
const filters = ref({
    fromDate: null,
    toDate: null
})

// Format functions
const formatDateRange = (dates) => {
    if (!dates || !dates[0] || !dates[1]) return ''
    const start = dates[0]
    const end = dates[1]
    const dayStart = start.getDate()
    const monthStart = start.getMonth() + 1
    const yearStart = start.getFullYear()
    const dayEnd = end.getDate()
    const monthEnd = end.getMonth() + 1
    const yearEnd = end.getFullYear()

    return `${dayStart}/${monthStart}/${yearStart} - ${dayEnd}/${monthEnd}/${yearEnd}`
}

// Date handlers
const handleDateChange = (modelData) => {
    if (modelData && modelData[0] && modelData[1]) {
        filters.value.fromDate = modelData[0].toISOString().split('T')[0]
        filters.value.toDate = modelData[1].toISOString().split('T')[0]
    } else {
        filters.value.fromDate = null
        filters.value.toDate = null
    }
}

const onChangeDate = (newDates) => {
    dateRange.value = newDates
    datePicker.value?.closeMenu()
    handleDateChange(newDates)
}

// Load overview data
const loadOverview = async () => {
    try {
        loading.value = true

        // Load all 3 overview data in parallel
        const [sourceCashierResult, destCashierResult, bothPayResult] = await Promise.all([
            monitorService.getOrderRiskOverview(filters.value),
            monitorService.getNoDestCashierOverview(filters.value),
            monitorService.getBothPayMissingCashierOverview(filters.value)
        ])

        // Set source cashier overview
        if (sourceCashierResult) {
            overview.value = sourceCashierResult
        } else {
            overview.value = null
        }

        // Set dest cashier overview
        if (destCashierResult) {
            destCashierOverview.value = destCashierResult
        } else {
            destCashierOverview.value = null
        }

        // Set both pay overview
        if (bothPayResult) {
            bothPayOverview.value = bothPayResult
        } else {
            bothPayOverview.value = null
        }

        // Show warning if no data
        if (!sourceCashierResult && !destCashierResult && !bothPayResult) {
            toast.warning('Không có dữ liệu giám sát cho khoảng thời gian này')
        }
    } catch (error) {
        console.error('Error loading overview:', error)
        toast.error('Có lỗi xảy ra khi tải dữ liệu')
    } finally {
        loading.value = false
    }
}

// Lifecycle
onMounted(() => {
    loadOverview()
})
</script>

<style scoped>
/* Add any dashboard-specific styles here if needed */
</style>
