<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-4 col-md-6 mb-2">
                    <input type="text" v-model="searchModel.Search.PredicateObject.Keyword" class="form-control"
                        placeholder="Tìm kiếm (biển số, cây xăng...)" @keyup.enter="search">
                </div>
                <div class="col-lg-4 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 thời gian đổ dầu">
                        <template #left-sidebar>
                            <DateRangeSidebar @change-date="onChangeDateSidebar"></DateRangeSidebar>
                        </template>
                    </VueDatePicker>
                </div>
                <div class="col-lg-4 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-10p">Thời gian</th>
                            <th class="wd-lg-10p">Xe</th>
                            <th class="wd-lg-10p">Lái xe</th>
                            <th class="wd-lg-8p text-end">ODO</th>
                            <th class="wd-lg-10p text-end">Số tiền</th>
                            <th class="wd-lg-8p text-end">Số lít</th>
                            <th class="wd-lg-15p">Cây xăng</th>
                        </tr>
                    </thead>
                    <tbody v-if="loading">
                        <tr>
                            <td colspan="7" class="text-center">
                                <Loader></Loader>
                            </td>
                        </tr>
                    </tbody>
                    <tbody v-if="!loading && items.length <= 0">
                        <tr>
                            <td colspan="7" class="text-center text-muted">Chưa có lịch sử đổ dầu</td>
                        </tr>
                    </tbody>
                    <tbody v-if="!loading && items.length > 0">
                        <tr v-for="item in items" :key="item.Id">
                            <td>{{ formatDateTime(item.RefillTime) }}</td>
                            <td>{{ item.TruckLicensePlate }}</td>
                            <td>{{ item.DriverName }}</td>
                            <td class="text-end">{{ item.CurrentOdo }}</td>
                            <td class="text-end fw-bold">{{ formatCurrency(item.Amount) }}</td>
                            <td class="text-end">{{ item.ActualLiters }}</td>
                            <td>{{ item.StationName }}</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: {
            Keyword: '',
            RefillStart: null,
            RefillEnd: null
        }
    },
    Sort: {
        Predicate: 'RefillTime',
        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 {
        // Create search params with FuelCardId from props
        const searchParams = {
            Pagination: {
                PageIndex: searchModel.Pagination.PageIndex,
                PageSize: searchModel.Pagination.PageSize
            },
            Search: {
                PredicateObject: {
                    FuelCardId: props.fuelCardId,
                    Keyword: searchModel.Search.PredicateObject.Keyword,
                    RefillStart: searchModel.Search.PredicateObject.RefillStart,
                    RefillEnd: searchModel.Search.PredicateObject.RefillEnd
                }
            },
            Sort: {
                Predicate: searchModel.Sort.Predicate,
                Reverse: searchModel.Sort.Reverse
            }
        };
        
        const result = await fuelCardService.searchRefills(searchParams);
        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 refills:", 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.RefillStart = dates[0];
        searchModel.Search.PredicateObject.RefillEnd = dates[1] || dates[0];
    } else {
        searchModel.Search.PredicateObject.RefillStart = null;
        searchModel.Search.PredicateObject.RefillEnd = null;
    }
}

function onChangeDateSidebar(dates) {
    dateRange.value = dates;
    if (dateRangePicker.value) {
        dateRangePicker.value.closeMenu();
    }
    handleDateChange(dates);
}

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