<template>
    <div>
        <!-- Breadcrumb -->
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Quản lý 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);">Quản lý Dầu</a></li>
                    <li class="breadcrumb-item active" aria-current="page">Thẻ Xăng Dầu</li>
                </ol>
            </div>
        </div>

        <!-- Tabs -->
        <div class="row row-sm">
            <div class="col-lg-12">
                <div class="card shadow-none">
                    <div class="card-body p-0">
                        <ul class="nav nav-tabs" role="tablist">
                            <li class="nav-item">
                                <a class="nav-link" :class="{ active: activeTab === 'cards' }" 
                                   @click="activeTab = 'cards'" href="javascript:void(0);" role="tab">
                                    <i class="fas fa-credit-card me-2"></i>Danh sách thẻ
                                </a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" :class="{ active: activeTab === 'transactions' }" 
                                   @click="activeTab = 'transactions'" href="javascript:void(0);" role="tab">
                                    <i class="fas fa-list me-2"></i>Lịch sử giao dịch
                                </a>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>

        <!-- Search Form -->
        <div class="row row-sm" v-show="activeTab === 'cards'">
            <div class="col-lg-12">
                <div class="card shadow-none">
                    <div class="card-header">
                        <h5 class="card-title mb-0">
                            <i class="fas fa-search me-2"></i>
                            Tìm kiếm
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-lg-6 col-md-6 mb-3">
                                <label class="form-label">Từ khóa</label>
                                <input type="text" class="form-control" v-model="searchKeyword"
                                    placeholder="Nhập số thẻ, tên chủ thẻ..." @keyup.enter="search">
                            </div>
                            <div class="col-lg-3 col-md-6 mb-3">
                                <label class="form-label">Trạng thái</label>
                                <select class="form-select" v-model="selectedStatus">
                                    <option :value="null">Tất cả</option>
                                    <option :value="1">Đang hoạt động</option>
                                    <option :value="2">Ngừng hoạt động</option>
                                    <option :value="3">Đã mất</option>
                                    <option :value="4">Hết hạn</option>
                                </select>
                            </div>
                            <div class="col-lg-3 col-md-6 mb-3 d-flex align-items-end">
                                <button type="button" class="btn btn-primary me-2" @click="search">
                                    <i class="fas fa-search me-2"></i>Tìm kiếm
                                </button>
                                <button type="button" class="btn btn-secondary" @click="resetSearch">
                                    <i class="fas fa-redo me-2"></i>Làm mới
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Data Table -->
        <div class="row row-sm" v-show="activeTab === 'cards'">
            <div class="col-lg-12">
                <div class="card card-table shadow-none">
                    <div class="card-body card-table-body">
                        <div class="d-flex flex-row justify-content-between mg-b-10">
                            <button type="button" class="btn btn-outline-primary mx-2 button-icon mb-1" @click="goToCreate">
                                <i class="fe fe-plus me-2"></i>Thêm thẻ mới
                            </button>
                            <button type="button" class="btn btn-outline-success mx-2 button-icon mb-1" @click="openImportModal">
                                <i class="fe fe-upload me-2"></i>Import giao dịch
                            </button>
                        </div>
                        <div class="table-responsive border-top mg-b-10">
                            <table class="table table-vcenter mb-0" style="min-height:300px">
                                <thead>
                                    <tr>
                                        <th class="wd-lg-5p min-width-1"><span>STT</span></th>
                                        <th class="wd-lg-12p min-width-2"><span>Số thẻ</span></th>
                                        <th class="wd-lg-12p min-width-2"><span>Chủ thẻ</span></th>
                                        <th class="wd-lg-10p min-width-1"><span>Ngân hàng</span></th>
                                        
                                        <th class="wd-lg-10p min-width-2"><span>Người phụ trách</span></th>
                                        <th class="wd-lg-8p min-width-1"><span>Trạng thái</span></th>
                                        <th class="wd-lg-10p min-width-2"><span>Hạn mức</span></th>
                                        <th class="wd-lg-10p min-width-2"><span>Nợ hiện tại</span></th>
                                        <th class="wd-lg-10p"><span>Hành động</span></th>
                                    </tr>
                                </thead>
                                <tbody v-if="loading">
                                    <tr>
                                        <td colspan="11" class="tx-semibold text-center text-default">
                                            <span class="spinner-border spinner-border-sm"></span>
                                        </td>
                                    </tr>
                                </tbody>
                                <tbody v-if="!loading && (!fuelCards.Items || fuelCards.Items.length <= 0)">
                                    <tr>
                                        <td colspan="11" class="tx-semibold text-center text-danger">
                                            Không tìm thấy bản ghi nào!
                                        </td>
                                    </tr>
                                </tbody>
                                <tbody v-if="!loading && fuelCards.Items && fuelCards.Items.length > 0">
                                    <tr v-for="(item, index) in fuelCards.Items" :key="item.Id">
                                        <td class="text-wrap align-top">{{ getRowNumber(index) }}</td>
                                        <td class="text-wrap align-top">
                                            <div class="fw-bold">{{ item.CardNumber }}</div>
                                            <div class="small text-muted">{{ item.CardType }}</div>
                                        </td>
                                        <td class="text-wrap align-top">{{ item.CardholderName }}</td>
                                        <td class="text-wrap align-top">{{ item.BankName }}</td>
                                        
                                        <td class="text-wrap align-top">
                                            <span v-if="item.ResponsibleUserName" class="badge bg-info">
                                                <i class="fas fa-user me-1"></i>{{ item.ResponsibleUserName }}
                                            </span>
                                            <span v-else class="text-muted">-</span>
                                        </td>
                                        <td class="text-wrap align-top">
                                            <span :class="getStatusBadgeClass(item.Status)">
                                                {{ item.StatusStr }}
                                            </span>
                                        </td>
                                        <td class="text-wrap align-top text-end">{{ formatCurrency(item.CreditLimit) }}</td>
                                        <td class="text-wrap align-top text-end">
                                            <span :class="item.CurrentDebt > 0 ? 'text-danger fw-bold' : ''">
                                                {{ formatCurrency(item.CurrentDebt) }}
                                            </span>
                                        </td>
                                        <td class="align-top pt-2">
                                            <button type="button" data-bs-toggle="dropdown"
                                                class="mb-1 mt-1 mr-1 btn btn-light dropdown-toggle btn-sm"
                                                aria-expanded="false"><i class="fas fa-cog"></i> Quản lý
                                            </button>
                                            <div class="dropdown-menu dropdown-menu-arrow">
                                                <a @click="viewDetail(item.Id)" class="dropdown-item"
                                                    href="javascript:void(0);"><i class="fe fe-eye"></i>
                                                    <span class="mg-l-6">Xem chi tiết</span>
                                                </a>
                                                <a @click="editCard(item.Id)" class="dropdown-item"
                                                    href="javascript:void(0);"><i class="fe fe-edit-2"></i>
                                                    <span class="mg-l-6">Cập nhật</span>
                                                </a>
                                                <a @click="deleteCard(item)" class="dropdown-item"
                                                    href="javascript:void(0);">
                                                    <i class="fe fe-trash"></i>
                                                    <span class="mg-l-6">Xóa</span></a>
                                            </div>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                        <pager ref="ctrlPager" v-show="!loading && fuelCards.Items && fuelCards.Items.length > 0"
                            @PageSizeChanged="PageSizeChanged" @PageIndexChanged="PageIndexChanged"
                            :Total="searchModel.Pagination.Total" :TotalCurrent="fuelCards.Items.length">
                        </pager>
                    </div>
                </div>
            </div>
        </div>

        <!-- All Transaction History -->
        <div class="row row-sm" v-show="activeTab === 'transactions'">
            <div class="col-lg-12">
                <AllTransactionHistory />
            </div>
        </div>


        <!-- Import Modal -->
        <div v-if="showImportModal" class="modal fade show" style="display: block; background-color: rgba(0,0,0,0.5);"
            tabindex="-1" role="dialog">
            <div class="modal-dialog modal-lg" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">Import Lịch sử Giao dịch Thẻ</h5>
                        <button type="button" class="btn-close" @click="closeImportModal"></button>
                    </div>
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-12 mb-3">
                                <label class="form-label">Chọn file Excel <span class="text-danger">*</span></label>
                                <input type="file" class="form-control" @change="handleFileChange"
                                    accept=".xlsx, .xls">
                                <small class="text-muted">Hỗ trợ định dạng .xlsx, .xls</small>
                            </div>
                            <div class="col-md-12 mb-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="overwriteExisting"
                                        v-model="importOptions.OverwriteExisting">
                                    <label class="form-check-label" for="overwriteExisting">
                                        Ghi đè giao dịch nếu đã tồn tại (dựa trên Thẻ + Ngày + Số tiền)
                                    </label>
                                </div>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Chỉ import từ ngày (Tùy chọn)</label>
                                <input type="date" class="form-control" v-model="importOptions.FromDate">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Chỉ import đến ngày (Tùy chọn)</label>
                                <input type="date" class="form-control" v-model="importOptions.ToDate">
                            </div>

                            <!-- Import Result & Warnings -->
                            <div v-if="importResult" class="col-md-12 mt-3">
                                <div :class="['alert', importResult.Result === 1 ? 'alert-success' : 'alert-danger']">
                                    <h6 class="alert-heading fw-bold">
                                        <i :class="['fas', importResult.Result === 1 ? 'fa-check-circle' : 'fa-exclamation-triangle', 'me-2']"></i>
                                        {{ importResult.Message }}
                                    </h6>
                                    <hr>
                                    <div class="row small">
                                        <div class="col-6">Tổng số dòng: <strong>{{ importResult.TotalRows }}</strong></div>
                                        <div class="col-6">Đã xử lý: <strong>{{ importResult.ProcessedRows }}</strong></div>
                                        <div class="col-6 text-danger">Lỗi: <strong>{{ importResult.ErrorRows }}</strong></div>
                                        <div class="col-6 text-warning">Bỏ qua: <strong>{{ importResult.SkippedRows }}</strong></div>
                                        <div class="col-6 text-info">Trùng lặp: <strong>{{ importResult.DuplicateRows }}</strong></div>
                                    </div>
                                    
                                    <!-- Warnings/Unknown Cards -->
                                    <div v-if="importResult.UnknownCards && importResult.UnknownCards.length > 0" class="mt-2">
                                        <div class="text-warning fw-bold mb-1">Thẻ chưa có trong hệ thống ({{ importResult.UnknownCardsCount }}):</div>
                                        <ul class="mb-0 ps-3" style="max-height: 100px; overflow-y: auto;">
                                            <li v-for="(card, idx) in importResult.UnknownCards" :key="idx">{{ card }}</li>
                                        </ul>
                                    </div>
                                    
                                    <!-- Error Messages -->
                                    <div v-if="importResult.ErrorMessages && importResult.ErrorMessages.length > 0" class="mt-2">
                                        <div class="text-danger fw-bold mb-1">Chi tiết lỗi:</div>
                                        <ul class="mb-0 ps-3" style="max-height: 100px; overflow-y: auto;">
                                            <li v-for="(err, idx) in importResult.ErrorMessages" :key="idx">{{ err }}</li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" @click="closeImportModal">Đóng</button>
                        <button type="button" class="btn btn-primary" @click="submitImport" 
                            :disabled="isImporting || !importFile">
                            <span v-if="isImporting" class="spinner-border spinner-border-sm me-2"></span>
                            {{ isImporting ? 'Đang xử lý...' : 'Thực hiện Import' }}
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

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

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

//#region DATA
const activeTab = ref('cards');
const loading = ref(false);
const searchKeyword = ref('');
const selectedStatus = ref(null);

const fuelCards = reactive({
    Items: [],
    TotalRecord: 0,
    NumberOfPages: 0
});

const searchModel = reactive({
    Pagination: {
        Total: 0,
        PageIndex: 1,
        PageSize: 15
    },
    Sort: {
        Predicate: 'CardNumber',
        Reverse: false
    },
    Search: {
        PredicateObject: {
            Keyword: '',
            Status: null
        }
    }
});

const ctrlPager = ref();

//#region IMPORT
const showImportModal = ref(false);
const isImporting = ref(false);
const importFile = ref(null);
const importOptions = reactive({
    OverwriteExisting: false,
    FromDate: null,
    ToDate: null
});
const importResult = ref(null);
//#endregion
//#endregion

//#region LIFECYCLE
onMounted(() => {
    search();
});
//#endregion

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

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 getRowNumber(index) {
    return (searchModel.Pagination.PageIndex - 1) * searchModel.Pagination.PageSize + index + 1;
}

async function search() {
    loading.value = true;
    try {
        // Update search model
        searchModel.Search.PredicateObject.Keyword = searchKeyword.value;
        searchModel.Search.PredicateObject.Status = selectedStatus.value;

        const result = await fuelCardService.searchFuelCards(searchModel);
        if (result && result.Items) {
            fuelCards.Items.splice(0, fuelCards.Items.length);
            result.Items.forEach(item => {
                fuelCards.Items.push(item);
            });
            fuelCards.TotalRecord = result.TotalRecord || 0;
            fuelCards.NumberOfPages = result.NumberOfPages || 0;
            searchModel.Pagination.Total = result.TotalRecord || 0;
        } else {
            toast.error('Không thể tải dữ liệu');
        }
    } catch (error) {
        console.error('Error searching fuel cards:', error);
        toast.error('Có lỗi xảy ra khi tải dữ liệu');
    } finally {
        loading.value = false;
    }
}

function resetSearch() {
    searchKeyword.value = '';
    selectedStatus.value = null;
    searchModel.Pagination.PageIndex = 1;
    if (ctrlPager.value) {
        ctrlPager.value.Refresh();
    }
    search();
}

function PageSizeChanged(pagesize) {
    searchModel.Pagination.PageSize = pagesize;
    searchModel.Pagination.PageIndex = 1;
    search();
}

function PageIndexChanged(pageIndex) {
    searchModel.Pagination.PageIndex = pageIndex;
    search();
}

function goToCreate() {
    router.push({ name: 'FuelCardCreate' });
}

function viewDetail(id) {
    router.push({ name: 'FuelCardDetail', params: { id } });
}

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

async function deleteCard(item) {
    if (!confirm(`Bạn có chắc chắn muốn xóa thẻ "${item.CardNumber}"?\n\nLưu ý: Không thể xóa thẻ đã có giao dịch.`)) {
        return;
    }

    try {
        const result = await fuelCardService.deleteFuelCard(item.Id);
        if (result && result.Result === 1) {
            toast.success(result.Message || 'Xóa thẻ thành công');
            search();
        } else {
            toast.error(result.Message || 'Không thể xóa thẻ');
        }
    } catch (error) {
        console.error('Error deleting fuel card:', error);
        toast.error('Có lỗi xảy ra khi xóa thẻ');
    }
}

//#region IMPORT FUNCTIONS
function openImportModal() {
    showImportModal.value = true;
    importFile.value = null;
    importResult.value = null;
    importOptions.OverwriteExisting = false;
    importOptions.FromDate = null;
    importOptions.ToDate = null;
}

function closeImportModal() {
    showImportModal.value = false;
    importResult.value = null; // Clear result for next time
    // Reload search to reflect changes if there were any successful imports
    if (importResult.value && importResult.value.ProcessedRows > 0) {
        search();
    }
}

function handleFileChange(event) {
    const file = event.target.files[0];
    if (file) {
        // Basic validation
        const validExtensions = ['.xlsx', '.xls'];
        const fileExtension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
        
        if (!validExtensions.includes(fileExtension)) {
            toast.error('Vui lòng chọn file Excel (.xlsx, .xls)');
            event.target.value = ''; // Reset input
            importFile.value = null;
            return;
        }
        importFile.value = file;
        importResult.value = null; // Clear previous result
    }
}

async function submitImport() {
    if (!importFile.value) {
        toast.warning('Vui lòng chọn file để import');
        return;
    }

    isImporting.value = true;
    importResult.value = null;

    try {
        const formData = new FormData();
        formData.append('File', importFile.value);
        formData.append('OverwriteExisting', importOptions.OverwriteExisting);
        if (importOptions.FromDate) formData.append('FromDate', importOptions.FromDate);
        if (importOptions.ToDate) formData.append('ToDate', importOptions.ToDate);

        const result = await fuelCardService.importTransactionHistory(formData);
        
        if (result) {
            importResult.value = result;
            if (result.Result === 1) {
                toast.success(result.Message || 'Import hoàn tất');
                // Don't close modal immediately so user can see the result stats
            } else {
                toast.error(result.Message || 'Import thất bại');
            }
        }
    } catch (error) {
        console.error('Error importing transactions:', error);
        toast.error('Có lỗi xảy ra khi import');
    } finally {
        isImporting.value = false;
    }
}
//#endregion
//#endregion
</script>

<style scoped>
.btn-group-sm .btn {
    padding: 0.25rem 0.5rem;
    font-size: 0.875rem;
}
</style>
