<template>
    <div class="card card-table shadow-none">
        <div class="card-body card-table-body">
            <!-- Search & Filter -->
            <div class="row mb-3">
                <div class="col-lg-3 col-md-6 mb-2">
                    <input type="text" v-model="searchModel.Search.PredicateObject.Keyword" class="form-control"
                        placeholder="Tìm kiếm giao dịch (địa điểm, loại...)" @keyup.enter="search">
                </div>
                <div class="col-lg-3 col-md-6 mb-2">
                    <select v-model="searchModel.Search.PredicateObject.HasRefill" class="form-select">
                        <option :value="null">Tất cả trạng thái</option>
                        <option :value="true">Đã đổ dầu</option>
                        <option :value="false">Chưa đổ dầu</option>
                    </select>
                </div>
                <div class="col-lg-3 col-md-6 mb-2">
                    <VueDatePicker ref="dateRangePicker" v-model="dateRange" :enable-time-picker="false" range multi-calendars auto-apply
                        :format="formatDateRange" @update:model-value="handleDateChange" placeholder="Chọn khoảng thời gian">
                        <template #left-sidebar>
                            <DateRangeSidebar @change-date="onChangeDateSidebar"></DateRangeSidebar>
                        </template>
                    </VueDatePicker>
                </div>
                <div class="col-lg-3 col-md-12 mb-2">
                    <button class="btn btn-primary me-2" @click="search" :disabled="loading">
                        <i v-if="loading" class="fas fa-spinner fa-spin me-1"></i>
                        <i v-else class="fas fa-search me-1"></i> Tìm kiếm
                    </button>
                </div>
            </div>

            <!-- Table -->
            <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-15p">Ngày</th>
                            <th class="wd-lg-10p text-end">Số tiền</th>
                            <th class="wd-lg-10p">Loại</th>
                            <th class="wd-lg-20p">Địa điểm</th>
                            <th class="wd-lg-10p text-center">Trạng thái</th>
                        </tr>
                    </thead>
                    <tbody v-if="loading">
                        <tr>
                            <td colspan="5" class="text-center">
                                <Loader></Loader>
                            </td>
                        </tr>
                    </tbody>
                    <tbody v-if="!loading && items.length <= 0">
                        <tr>
                            <td colspan="5" class="text-center text-muted">Chưa có giao dịch nào</td>
                        </tr>
                    </tbody>
                    <tbody v-if="!loading && items.length > 0">
                        <tr v-for="item in items" :key="item.Id">
                            <td>{{ formatDateTime(item.TransactionDate) }}</td>
                            <td class="text-end fw-bold">{{ formatCurrency(item.Amount) }}</td>
                            <td>{{ item.TransactionType }}</td>
                            <td>{{ item.Location }}</td>
                            <td class="text-center">
                                <span class="badge bg-success">{{ item.StatusStr }}</span>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

        <!-- Pager -->
        <Pager ref="pager" v-show="!loading && items.length > 0" :Total="totalRecord" :TotalCurrent="items.length"
            @PageSizeChanged="handlePageSizeChange" @PageIndexChanged="handlePageIndexChange">
        </Pager>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import fuelCardService from '@/services/fuelCardService';
import moment from 'moment';
import VueDatePicker from '@vuepic/vue-datepicker';
import { DateRangeSidebar, Pager, Loader } from '@/components/index';

const props = defineProps({
    fuelCardId: {
        type: [String, Number],
        required: true
    }
});

const loading = ref(false);
const items = ref([]);
const totalRecord = ref(0);
const dateRange = ref(null);
const dateRangePicker = ref(null);

const searchModel = reactive({
    Pagination: {
        PageIndex: 1,
        PageSize: 20
    },
    Search: {
        PredicateObject: {
            HasRefill: null,
            Keyword: '',
            TransactionStart: null,
            TransactionEnd: null
        }
    },
    Sort: {
        Predicate: 'TransactionDate',
        Reverse: true
    }
});

const pager = ref(null);

// Không tự động search khi mount, chờ parent trigger
// onMounted(() => {
//     search();
// });

// Expose search function để parent có thể gọi
defineExpose({
    search
});

async function search() {
    if (!props.fuelCardId) return;
    
    loading.value = true;
    try {
        const result = await fuelCardService.searchTransactions(props.fuelCardId, searchModel);
        if (result && result.Items) {
            items.value = result.Items;
            totalRecord.value = result.TotalRecord || 0;
        } else {
            items.value = [];
            totalRecord.value = 0;
        }
    } catch (error) {
        console.error("Error searching transactions:", error);
        items.value = [];
        totalRecord.value = 0;
    } finally {
        loading.value = false;
    }
}

function handlePageSizeChange(pageSize) {
    searchModel.Pagination.PageSize = pageSize;
    searchModel.Pagination.PageIndex = 1;
    search();
}

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

// Date Picker Handlers
function formatDateRange(dates) {
    if (!dates || !dates[0]) return '';
    const start = moment(dates[0]).format('DD/MM/YYYY');
    if (!dates[1]) return start;
    const end = moment(dates[1]).format('DD/MM/YYYY');
    return `${start} - ${end}`;
}

function handleDateChange(dates) {
    if (dates && dates[0]) {
        searchModel.Search.PredicateObject.TransactionStart = dates[0];
        searchModel.Search.PredicateObject.TransactionEnd = dates[1] || dates[0];
    } else {
        searchModel.Search.PredicateObject.TransactionStart = null;
        searchModel.Search.PredicateObject.TransactionEnd = null;
    }
}

function onChangeDateSidebar(dates) {
    dateRange.value = dates;
    if (dateRangePicker.value) {
        dateRangePicker.value.closeMenu();
    }
    handleDateChange(dates);
    // Reset HasRefill when changing date to avoid confusion
}

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

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