<template>
    <div>
        <!-- Breadcrumb -->
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Chi tiết Thẻ Xăng Dầu</h4>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="/">Trang chủ</a></li>
                    <li class="breadcrumb-item"><a href="javascript:void(0);" @click="$router.push({ name: 'FuelCardList' })">Thẻ Xăng Dầu</a></li>
                    <li class="breadcrumb-item active" aria-current="page">Chi tiết</li>
                </ol>
            </div>
            <div class="d-flex my-xl-auto right-content">
                <button type="button" class="btn btn-secondary me-2" @click="$router.go(-1)">
                    <i class="fas fa-arrow-left me-2"></i>Quay lại
                </button>
                <button v-if="fuelCard" type="button" class="btn btn-warning" @click="editCard">
                    <i class="fas fa-edit me-2"></i>Chỉnh sửa
                </button>
            </div>
        </div>

        <div v-if="loading" class="text-center">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
        </div>

        <div v-else-if="!fuelCard" class="alert alert-danger">
            Không tìm thấy thông tin thẻ!
        </div>

        <div v-else class="row row-sm">
            <!-- Basic Info -->
            <div class="col-lg-4 col-xl-3">
                <div class="card">
                    <div class="card-body">
                        <div class="main-profile-overview">
                            <div class="d-flex justify-content-between">
                                <div>
                                    <h5 class="main-profile-name">{{ fuelCard.CardNumber }}</h5>
                                    <p class="main-profile-name-text">{{ fuelCard.CardType }}</p>
                                </div>
                                <div>
                                    <span :class="getStatusBadgeClass(fuelCard.Status)">{{ fuelCard.StatusStr }}</span>
                                </div>
                            </div>
                            
                            <hr>
                            
                            <div class="row">
                                <div class="col-md-12 mb-2">
                                    <label class="fw-bold">Chủ thẻ:</label>
                                    <div>{{ fuelCard.CardholderName }}</div>
                                </div>
                                <div class="col-md-12 mb-2">
                                    <label class="fw-bold">Ngân hàng:</label>
                                    <div>{{ fuelCard.BankName }}</div>
                                </div>
                                <div class="col-md-12 mb-2">
                                    <label class="fw-bold">Xe hiện tại:</label>
                                    <div>
                                        <span v-if="fuelCard.TruckLicensePlate" class="badge bg-info">{{ fuelCard.TruckLicensePlate }}</span>
                                        <span v-else class="text-muted">-</span>
                                    </div>
                                </div>
                                <div class="col-md-12 mb-2">
                                    <label class="fw-bold">Lái xe hiện tại:</label>
                                    <div>{{ fuelCard.CurrentDriverName || '-' }}</div>
                                </div>
                                <div class="col-md-12 mb-2">
                                    <label class="fw-bold">Ngày hết hạn:</label>
                                    <div>{{ formatDate(fuelCard.ExpiryDate) }}</div>
                                </div>
                                <div class="col-md-12 mb-2">
                                    <label class="fw-bold">Hạn mức:</label>
                                    <div class="text-primary fw-bold">{{ formatCurrency(fuelCard.CreditLimit) }}</div>
                                </div>
                                <div class="col-md-12 mb-2">
                                    <label class="fw-bold">Nợ hiện tại:</label>
                                    <div :class="fuelCard.CurrentDebt > 0 ? 'text-danger fw-bold' : ''">
                                        {{ formatCurrency(fuelCard.CurrentDebt) }}
                                    </div>
                                </div>
                                <div class="col-md-12 mb-2" v-if="fuelCard.Notes">
                                    <label class="fw-bold">Ghi chú:</label>
                                    <div>{{ fuelCard.Notes }}</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Tabs: Transactions & Refills -->
            <div class="col-lg-8 col-xl-9">
                <div class="card mg-b-20">
                    <div class="card-body">
                        <div class="panel panel-primary tabs-style-2">
                            <div class="tab-menu-heading">
                                <div class="tabs-menu1">
                                    <ul class="nav panel-tabs main-nav-line">
                                        <li>
                                            <a href="#tab-transactions" @click="setActiveTab(1)"
                                                :class="{ 'active': activeTab === 1 }" class="nav-link me-1"
                                                data-bs-toggle="tab">Lịch sử Giao dịch</a>
                                        </li>
                                        <li>
                                            <a href="#tab-refills" @click="setActiveTab(2)"
                                                :class="{ 'active': activeTab === 2 }" class="nav-link me-1"
                                                data-bs-toggle="tab">Lịch sử Đổ dầu</a>
                                        </li>
                                    </ul>
                                </div>
                            </div>
                            <div class="panel-body tabs-menu-body main-content-body-right border">
                                <div class="tab-content">
                            <!-- Tab Transactions -->
                            <div :class="{ 'active': activeTab === 1 }" class="tab-pane"
                                id="tab-transactions">
                                <TransactionHistory v-if="fuelCard" ref="transactionHistoryRef" :fuelCardId="fuelCardId" />
                            </div>

                            <!-- Tab Refills -->
                            <div :class="{ 'active': activeTab === 2 }" class="tab-pane"
                                id="tab-refills">
                                <RefillHistory v-if="fuelCard" ref="refillHistoryRef" :fuelCardId="fuelCardId" />
                            </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import fuelCardService from '@/services/fuelCardService';
import { useToast } from 'vue-toastification';
import moment from 'moment';
import TransactionHistory from './components/TransactionHistory.vue';
import RefillHistory from './components/RefillHistory.vue';

const route = useRoute();
const router = useRouter();
const toast = useToast();

const fuelCardId = route.params.id;
const fuelCard = ref(null);
const loading = ref(false);

const activeTab = ref(1);
const transactionHistoryRef = ref(null);
const refillHistoryRef = ref(null);

const setActiveTab = (id) => {
    activeTab.value = id;
    // Load data khi tab được active
    if (id === 1 && transactionHistoryRef.value) {
        transactionHistoryRef.value.search();
    } else if (id === 2 && refillHistoryRef.value) {
        refillHistoryRef.value.search();
    }
};

onMounted(async () => {
    if (fuelCardId) {
        await loadFuelCardDetail();
        // Load tab đầu tiên sau khi load xong fuel card detail
        setTimeout(() => {
            if (transactionHistoryRef.value) {
                transactionHistoryRef.value.search();
            }
        }, 300);
    }
});

async function loadFuelCardDetail() {
    loading.value = true;
    try {
        const result = await fuelCardService.getFuelCardById(fuelCardId);
        if (result) {
            fuelCard.value = result;
        } else {
            toast.error("Không tìm thấy thông tin thẻ");
        }
    } catch (error) {
        console.error("Error loading fuel card:", error);
        toast.error("Lỗi khi tải thông tin thẻ");
    } finally {
        loading.value = false;
    }
}

function editCard() {
    router.push({ name: 'FuelCardEdit', params: { id: fuelCardId } });
}

function getStatusBadgeClass(status) {
    const classes = {
        1: 'badge bg-success',      // Active
        2: 'badge bg-warning',      // Inactive
        3: 'badge bg-danger',       // Lost
        4: 'badge bg-secondary'     // Expired
    };
    return classes[status] || 'badge bg-secondary';
}

function formatCurrency(value) {
    if (value == null || value == undefined) return '0 ₫';
    return new Intl.NumberFormat('vi-VN', { style: 'currency', currency: 'VND' }).format(value);
}

function formatDate(date) {
    if (!date) return '';
    return moment(date).format('DD/MM/YYYY');
}
</script>

<style scoped>
.main-profile-name {
    font-weight: 700;
    font-size: 20px;
    margin-bottom: 5px;
}
.main-profile-name-text {
    color: #7d7d7d;
    font-size: 13px;
    margin-bottom: 0;
}
</style>
