<template>
    <div>
        <!-- Breadcrumb Header -->
        <div v-if="!hideHeader" class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Giám sát Đơn hàng BothPay thiếu Cashier</h4>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="javascript:void(0);">Trang chủ</a></li>
                    <li class="breadcrumb-item"><router-link to="/giam-sat">Giám sát</router-link></li>
                    <li class="breadcrumb-item active" aria-current="page">Đơn hàng BothPay thiếu Cashier</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">

                <!-- Risk Info Alert -->
                <div v-if="!hideHeader && riskInfo" class="alert alert-warning alert-dismissible fade show"
                    role="alert">
                    <div class="d-flex align-items-start">
                        <i class="fe fe-alert-triangle me-3" style="font-size: 24px;"></i>
                        <div class="flex-grow-1">
                            <h5 class="alert-heading mb-2">{{ riskInfo.Name }}</h5>
                            <p class="mb-2">{{ riskInfo.Description }}</p>
                            <hr>
                            <div class="row">
                                <div class="col-md-6">
                                    <strong>Mức độ:</strong>
                                    <span :class="getSeverityClass(riskInfo.Severity)" class="badge ms-1">
                                        {{ riskInfo.Severity }}
                                    </span>
                                </div>
                                <div class="col-md-6">
                                    <strong>Giải pháp:</strong> {{ riskInfo.Solution }}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Filter Card -->
                <div class="card card-search shadow-none">
                    <form class="card-body" @submit.prevent="search">
                        <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>

                <!-- Data Table Card -->
                <div class="card card-table shadow-none">
                    <div class="card-body card-table-body">
                        <!-- Summary Stats -->
                        <div v-if="!loading && orders.length > 0" class="row mb-3">
                            <div class="col-md-12">
                                <div class="alert alert-info">
                                    <div class="row text-center">
                                        <div class="col-md-3">
                                            <h6 class="mb-0">Tổng đơn hàng</h6>
                                            <h4 class="mb-0">{{ formatNumber(totalRecords) }}</h4>
                                        </div>
                                        <div class="col-md-3">
                                            <h6 class="mb-0">Tổng phí lấy hàng</h6>
                                            <h4 class="mb-0">{{ calculateTotalSourceFee() }}</h4>
                                        </div>
                                        <div class="col-md-3">
                                            <h6 class="mb-0">Tổng phí giao hàng</h6>
                                            <h4 class="mb-0">{{ calculateTotalDestFee() }}</h4>
                                        </div>
                                        <div class="col-md-3">
                                            <h6 class="mb-0">Tổng phí</h6>
                                            <h4 class="mb-0">{{ calculateTotalFee() }}</h4>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Table -->
                        <div class="table-responsive border-top mg-b-10" style="max-height: 500px; overflow-y: auto;">
                            <table class="table table-vcenter mb-0">
                                <thead>
                                    <tr>
                                        <th class="wd-lg-8p"><span>Mã đơn</span></th>
                                        <th class="wd-lg-8p"><span>Ngày tạo</span></th>
                                        <th class="wd-lg-12p"><span>Khách hàng</span></th>
                                        <th class="wd-lg-12p"><span>Người gửi</span></th>
                                        <th class="wd-lg-12p"><span>Người nhận</span></th>
                                        <th class="wd-lg-8p"><span>Phí lấy</span></th>
                                        <th class="wd-lg-8p"><span>Phí giao</span></th>
                                        <th class="wd-lg-8p"><span>Tổng phí</span></th>
                                        <th class="wd-lg-12p"><span>Trạng thái</span></th>
                                    </tr>
                                </thead>

                                <!-- Loading State -->
                                <tbody v-if="loading">
                                    <tr>
                                        <td colspan="9" class="tx-semibold text-center text-default">
                                            <span class="spinner-border spinner-border-sm"></span>
                                            <span class="ms-2">Đang tải dữ liệu...</span>
                                        </td>
                                    </tr>
                                </tbody>

                                <!-- Empty State -->
                                <tbody v-if="!loading && orders.length <= 0">
                                    <tr>
                                        <td colspan="9" class="tx-semibold text-center text-danger">
                                            Không tìm thấy bản ghi nào!
                                        </td>
                                    </tr>
                                </tbody>

                                <!-- Data Rows -->
                                <tbody v-if="!loading && orders.length > 0">
                                    <tr v-for="order in orders" :key="order.Id">
                                        <td class="align-top">
                                            <router-link :to="{ name: 'orderTrack', params: { code: order.Code } }"
                                                target="_blank">
                                                {{ order.Code }}
                                            </router-link>
                                        </td>
                                        <td class="align-top">
                                            {{ formatDate(order.CreatedTime) }}
                                        </td>
                                        <td class="align-top text-wrap">
                                            <div><strong>{{ order.CustomerName || '-' }}</strong></div>
                                            <div class="text-muted small">{{ order.CustomerPhone || '-' }}</div>
                                        </td>
                                        <td class="align-top text-wrap">
                                            <div><strong>{{ order.SenderName || '-' }}</strong></div>
                                            <div class="text-muted small">{{ order.SenderPhone || '-' }}</div>
                                        </td>
                                        <td class="align-top text-wrap">
                                            <div><strong>{{ order.ReceiverName || '-' }}</strong></div>
                                            <div class="text-muted small">{{ order.ReceiverPhone || '-' }}</div>
                                        </td>
                                        <td class="align-top">
                                            <strong class="text-warning">{{ formatCurrency(order.SourceFee) }}</strong>
                                        </td>
                                        <td class="align-top">
                                            <strong class="text-success">{{ formatCurrency(order.DestFee) }}</strong>
                                        </td>
                                        <td class="align-top">
                                            <strong class="text-primary">{{ formatCurrency(order.TotalFee) }}</strong>
                                        </td>
                                        <td class="align-top">
                                            <span class="badge bg-warning">
                                                <i class="fe fe-alert-triangle me-1"></i>
                                                Thiếu Cashier
                                            </span>
                                            <div class="small text-muted mt-1">
                                                {{ getMissingCashierInfo(order) }}
                                            </div>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>

                        <!-- Pagination -->
                        <pager ref="ctrlPager" v-show="!loading && orders.length > 0" @PageSizeChanged="PageSizeChanged"
                            @PageIndexChanged="PageIndexChanged" :Total="totalRecords" :TotalCurrent="orders.length" />
                    </div>
                </div>

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

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { useToast } from 'vue-toastification'
import monitorService from '@/services/monitorService'
import DatepickerInstance from "@vuepic/vue-datepicker"
import { DateRangeSidebar } from '@/components/index'

// Props
const props = defineProps({
    hideHeader: {
        type: Boolean,
        default: false
    },
    initialFilters: {
        type: Object,
        default: () => ({})
    }
})

const route = useRoute()
const toast = useToast()

// Data
const loading = ref(false)
const orders = reactive([])
const riskInfo = ref(null)
const dateRange = ref(null)
const datePicker = ref(null)
const ctrlPager = ref(null)
const totalRecords = ref(0)
const totalPages = ref(0)
const pageNumber = ref(1)
const pageSize = ref(50)

const filters = ref({
    fromDate: null,
    toDate: null,
    page: 1,
    pageSize: 50
})

// Format functions
const formatCurrency = (amount) => {
    if (!amount) return '0 VND'
    return new Intl.NumberFormat('vi-VN', {
        style: 'currency',
        currency: 'VND'
    }).format(amount)
}

const formatNumber = (num) => {
    if (!num) return '0'
    return new Intl.NumberFormat('vi-VN').format(num)
}

const formatDate = (dateString) => {
    if (!dateString) return '-'
    try {
        const date = new Date(dateString)
        return date.toLocaleDateString('vi-VN') + ' ' + date.toLocaleTimeString('vi-VN', { hour: '2-digit', minute: '2-digit' })
    } catch {
        return '-'
    }
}

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}`
}

const getSeverityClass = (severity) => {
    const severityMap = {
        'Low': 'bg-info',
        'Medium': 'bg-warning',
        'High': 'bg-orange',
        'Critical': 'bg-danger'
    }
    return severityMap[severity] || 'bg-secondary'
}

const getMissingCashierInfo = (order) => {
    const missingSource = !order.SourceFeeCashierId || order.SourceFeeCashierId === 0
    const missingDest = !order.DestFeeCashierId || order.DestFeeCashierId === 0

    if (missingSource && missingDest) {
        return 'Thiếu cả 2 Cashier'
    } else if (missingSource) {
        return 'Thiếu Source Cashier'
    } else if (missingDest) {
        return 'Thiếu Dest Cashier'
    }
    return '-'
}

// Calculate totals
const calculateTotalSourceFee = () => {
    const total = orders.reduce((sum, order) => sum + (order.SourceFee || 0), 0)
    return formatCurrency(total)
}

const calculateTotalDestFee = () => {
    const total = orders.reduce((sum, order) => sum + (order.DestFee || 0), 0)
    return formatCurrency(total)
}

const calculateTotalFee = () => {
    const total = orders.reduce((sum, order) => sum + (order.TotalFee || 0), 0)
    return formatCurrency(total)
}

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

// Search and load data
const search = async () => {
    filters.value.page = 1
    ctrlPager.value?.Refresh()
    await loadData()
}

const loadData = async () => {
    try {
        loading.value = true
        orders.splice(0, orders.length)

        const result = await monitorService.getBothPayMissingCashierList(filters.value)

        if (result && result.Orders) {
            result.Orders.forEach(order => {
                orders.push(order)
            })

            totalRecords.value = result.TotalRecords || 0
            totalPages.value = result.TotalPages || 0
            pageNumber.value = result.PageNumber || 1
            pageSize.value = result.PageSize || 50
            riskInfo.value = result.RiskInfo || null
        } else {
            toast.warning('Không có dữ liệu')
        }
    } catch (error) {
        console.error('Error loading data:', error)
        toast.error('Có lỗi xảy ra khi tải dữ liệu')
    } finally {
        loading.value = false
    }
}

// Pagination handlers
const PageSizeChanged = (newPageSize) => {
    filters.value.pageSize = newPageSize
    filters.value.page = 1
    loadData()
}

const PageIndexChanged = (newPageIndex) => {
    filters.value.page = newPageIndex
    loadData()
}

// Initialize from query params or props
const initializeFromQuery = () => {
    // Use initial filters from props if provided
    if (props.initialFilters?.fromDate) {
        filters.value.fromDate = props.initialFilters.fromDate
    } else if (route.query.fromDate) {
        filters.value.fromDate = route.query.fromDate
    }

    if (props.initialFilters?.toDate) {
        filters.value.toDate = props.initialFilters.toDate
    } else if (route.query.toDate) {
        filters.value.toDate = route.query.toDate
    }

    // Set dateRange for date picker
    if (filters.value.fromDate && filters.value.toDate) {
        dateRange.value = [
            new Date(filters.value.fromDate),
            new Date(filters.value.toDate)
        ]
    }
}

// Lifecycle
onMounted(() => {
    initializeFromQuery()
    loadData()
})
</script>

<style scoped>
.table th {
    background-color: #f8f9fa;
    font-weight: 600;
    text-transform: uppercase;
    font-size: 0.85rem;
}

.card-table-body {
    padding: 1.5rem;
}

.text-wrap {
    white-space: normal;
    word-wrap: break-word;
}

.alert-heading {
    font-size: 1.25rem;
}
</style>
