<template>
    <div class="container-fluid">
        <!-- Breadcrumb -->
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Chi tiết ví</h4>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item">
                        <router-link to="/">Trang chủ</router-link>
                    </li>
                    <li class="breadcrumb-item">
                        <router-link to="/finances/wallets">Quản lý ví</router-link>
                    </li>
                    <li class="breadcrumb-item active" aria-current="page">Chi tiết ví</li>
                </ol>
            </div>
        </div>

        <!-- Loading State -->
        <div v-if="loading" class="text-center py-5">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Đang tải...</span>
            </div>
            <p class="mt-2 text-muted">Đang tải thông tin ví...</p>
        </div>

        <!-- Main Content -->
        <div v-else>
            <!-- Card thông tin ví và thống kê -->
            <div class="row mb-4">
                <div class="col-12">
                    <div class="card wallet-stats-card mb-4">
                        <div class="card-header">
                            <h5 class="mb-0">
                                <i class="fas fa-wallet me-2"></i>
                                Thông tin ví
                            </h5>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <!-- Cột số dư -->
                                <div class="col-lg-4">
                                    <div class="text-center">
                                        <div class="balance-display">
                                            <small class="text-muted d-block">Số dư hiện tại</small>
                                            <span class="h2 fw-bold text-dark">{{ formatCurrency(wallet?.Balance)
                                            }}</span>
                                        </div>
                                    </div>
                                </div>

                                <!-- Cột thông tin ví -->
                                <div class="col-lg-8">
                                    <div class="ps-lg-4">
                                        <!-- Nút hành động -->
                                        <div class="row mb-3" v-if="wallet?.CanAdjustBalance">
                                            <div class="col-md-6">
                                                <button class="btn btn-outline-secondary"
                                                    @click="showAdjustBalanceModal">
                                                    <i class="fas fa-balance-scale me-2"></i>
                                                    Cân ví
                                                </button>
                                            </div>
                                        </div>

                                        <!-- Thông tin ví -->
                                        <div class="wallet-info-horizontal mb-4">
                                            <div class="row">
                                                <div class="col-md-4">
                                                    <div class="info-item-horizontal">
                                                        <small class="text-muted d-block">Trạng thái</small>
                                                        <span class="badge"
                                                            :class="getStatusBadgeClass(wallet?.WalletStatus)">
                                                            {{ getStatusText(wallet?.WalletStatus) }}
                                                        </span>
                                                    </div>
                                                </div>
                                                <div class="col-md-4">
                                                    <div class="info-item-horizontal">
                                                        <small class="text-muted d-block">Chủ sở hữu</small>
                                                        <span class="fw-medium">{{ wallet?.FullName }}</span>
                                                    </div>
                                                </div>
                                                <div class="col-md-4">
                                                    <div class="info-item-horizontal">
                                                        <small class="text-muted d-block">Tài khoản</small>
                                                        <span class="fw-medium">{{ wallet?.UserName }}</span>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Danh sách giao dịch toàn màn hình -->
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div class="d-flex align-items-center">
                                <i class="fas fa-history text-secondary me-3"></i>
                                <h5 class="card-title mb-0">Lịch sử giao dịch</h5>
                            </div>
                            <div class="d-flex gap-2">
                                <button class="btn btn-outline-secondary btn-sm" @click="refreshData">
                                    <i class="fas fa-sync-alt"></i> Làm mới
                                </button>
                                <button class="btn btn-outline-success btn-sm" @click="exportTransactions">
                                    <i class="fas fa-download"></i> Xuất Excel
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <!-- Filter Section -->
                        <div class="p-3 border-bottom">
                            <div class="row mb-3">
                                <div class="col-md-3">
                                    <label class="form-label">Từ khóa</label>
                                    <input type="text" class="form-control"
                                        v-model="searchModel.Search.PredicateObject.Keyword" placeholder="Tìm kiếm..."
                                        @keyup.enter="search">
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Loại giao dịch</label>
                                    <select class="form-select"
                                        v-model="searchModel.Search.PredicateObject.TransactionType">
                                        <option value="">Tất cả</option>
                                        <option value="1">Cước vận chuyển</option>
                                        <option value="2">Thu hộ COD</option>
                                        <option value="3">Chi phí nhiên liệu</option>
                                        <option value="4">Lương</option>
                                        <option value="5">Chuyển khoản</option>
                                        <option value="6">Nạp tiền</option>
                                        <option value="7">Rút tiền</option>
                                        <option value="8">Hoàn tiền</option>
                                        <option value="9">Phạt</option>
                                        <option value="10">Thưởng</option>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Hướng giao dịch</label>
                                    <select class="form-select"
                                        v-model="searchModel.Search.PredicateObject.TransactionDirection">
                                        <option value="">Tất cả</option>
                                        <option value="1">Thu</option>
                                        <option value="2">Chi</option>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <label class="form-label">Khoảng thời gian</label>
                                    <VueDatePicker ref="createDatePicker" v-model="date" :enable-time-picker="false"
                                        range multi-calendars auto-apply :format="format"
                                        @update:model-value="handleDate">
                                        <template #left-sidebar>
                                            <DateRangeSidebar @change-date="onChangeDate"></DateRangeSidebar>
                                        </template>
                                    </VueDatePicker>
                                </div>
                            </div>

                            <!-- Action Buttons -->
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <button class="btn btn-secondary btn-sm" @click="search">
                                        <i class="fas fa-search"></i> Tìm kiếm
                                    </button>
                                    <button class="btn btn-outline-secondary btn-sm ms-2" @click="resetFilters">
                                        <i class="fas fa-undo"></i> Đặt lại
                                    </button>
                                </div>
                                <div class="text-muted">
                                    Tổng: {{ searchModel.Pagination.Total }} giao dịch
                                </div>
                            </div>
                        </div>

                        <!-- Thống kê giao dịch -->
                        <div class="p-3 bg-white">
                            <h6 class="text-muted mb-3">
                                <i class="fas fa-chart-bar me-2"></i>
                                Thống kê giao dịch
                            </h6>

                            <!-- Loading state -->
                            <div v-if="!statistics" class="text-center py-3">
                                <span class="spinner-border spinner-border-sm me-2"></span>
                                Đang tải thống kê...
                            </div>

                            <!-- Statistics content -->
                            <div
                                v-else-if="statistics && (statistics.TotalIncome !== undefined || statistics.TotalOutcome !== undefined)">
                                <div class="row">
                                    <div class="col-md-4">
                                        <div class="summary-card">
                                            <div class="d-flex align-items-center">
                                                <div class="summary-icon income me-3">
                                                    <i class="fas fa-arrow-up"></i>
                                                </div>
                                                <div>
                                                    <div class="summary-label">Tổng thu</div>
                                                    <div class="summary-value text-success">
                                                        {{ formatCurrency(statistics.TotalIncome || 0) }}
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="summary-card">
                                            <div class="d-flex align-items-center">
                                                <div class="summary-icon outcome me-3">
                                                    <i class="fas fa-arrow-down"></i>
                                                </div>
                                                <div>
                                                    <div class="summary-label">Tổng chi</div>
                                                    <div class="summary-value text-danger">
                                                        {{ formatCurrency(statistics.TotalOutcome || 0) }}
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="summary-card">
                                            <div class="d-flex align-items-center">
                                                <div class="summary-icon net me-3">
                                                    <i :class="getNetBalanceIcon(statistics.NetBalance || 0)"></i>
                                                </div>
                                                <div>
                                                    <div class="summary-label">Số dư ròng</div>
                                                    <div class="summary-value"
                                                        :class="getNetBalanceClass(statistics.NetBalance || 0)">
                                                        {{ formatCurrency(statistics.NetBalance || 0) }}
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- No data state -->
                            <div v-else class="text-center py-3 text-muted">
                                <i class="fas fa-chart-bar fa-2x mb-2"></i>
                                <p>Không có dữ liệu thống kê</p>
                            </div>
                        </div>

                        <!-- Transaction List -->
                        <div v-if="loadingTransactions" class="text-center py-3">
                            <div class="spinner-border spinner-border-sm text-secondary" role="status">
                                <span class="visually-hidden">Đang tải...</span>
                            </div>
                            <span class="ms-2">Đang tải giao dịch...</span>
                        </div>

                        <div v-else-if="items.length === 0" class="text-center py-5">
                            <i class="fas fa-inbox fa-3x text-muted mb-3"></i>
                            <p class="text-muted">Không có giao dịch nào</p>
                        </div>

                        <div v-else class="table-responsive">
                            <table class="table table-hover mb-0">
                                <thead class="table-light">
                                    <tr>
                                        <th width="120">Thời gian</th>
                                        <th width="200">Mô tả</th>
                                        <th width="100">Loại</th>
                                        <th width="80">Hướng</th>
                                        <th width="120">Số tiền</th>
                                        <th width="100">Tiền mặt</th>
                                        <th width="100">Chuyển khoản</th>
                                        <th width="120">Người gửi/nhận</th>
                                        <th width="150">Mã đơn hàng</th>
                                        <th width="120">Số dư sau GD</th>
                                        <th width="80">Thao tác</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr v-for="item in items" :key="item.Id" class="transaction-row"
                                        :class="getTransactionRowClass(item.TransactionDirection)">
                                        <td>
                                            <div class="transaction-time">
                                                <span class="fw-medium">{{ item.CreatedTimeDisplay ||
                                                    formatDateTime(item.TransactionDate)
                                                }}</span>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="transaction-description">
                                                <div class="d-flex align-items-center">
                                                    <span class="transaction-icon me-2">
                                                        <span v-if="item.TransactionIcon">{{ item.TransactionIcon
                                                        }}</span>
                                                        <i v-else :class="getTransactionIcon(item.TransactionType)"></i>
                                                    </span>
                                                    <div>
                                                        <div class="fw-medium">{{ item.ShortDescription ||
                                                            item.Description }}</div>
                                                        <small class="text-muted" v-if="item.Note">{{ item.Note
                                                        }}</small>
                                                        <div class="d-flex align-items-center mt-1">
                                                            <span v-if="item.IsIncome"
                                                                class="badge bg-success me-1">Thu</span>
                                                            <span v-if="item.IsOutcome"
                                                                class="badge bg-danger me-1">Chi</span>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </td>
                                        <td>
                                            <span class="badge"
                                                :class="getTransactionTypeBadgeClass(item.TransactionType)">
                                                {{ item.TransactionTypeName ||
                                                    getTransactionTypeName(item.TransactionType) }}
                                            </span>
                                        </td>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <span class="transaction-direction-icon me-2"
                                                    :class="getAmountClass(item.TransactionDirection)">
                                                    <i :class="getDirectionIcon(item.TransactionDirection)"></i>
                                                </span>
                                                <span class="fw-medium"
                                                    :class="getAmountClass(item.TransactionDirection)">
                                                    {{ item.TransactionDirectionName || (item.TransactionDirection === 1
                                                        ? 'Thu' : 'Chi') }}
                                                </span>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="d-flex flex-column">
                                                <span class="fw-bold"
                                                    :class="getAmountColorClass(item.AmountColor, item.TransactionDirection)">
                                                    {{ item.FormattedAmount || (item.TransactionDirection === 1 ? '+' :
                                                        '-') +
                                                        formatCurrency(item.Amount) }}
                                                </span>
                                                <small class="text-muted">
                                                    {{ item.FormattedAmountWithCurrency || formatCurrency(item.Amount) +
                                                        ' VND' }}
                                                </small>
                                            </div>
                                        </td>
                                        <td>
                                            <span class="text-info" v-if="item.CashAmount > 0">
                                                {{ formatCurrency(item.CashAmount) }}
                                            </span>
                                            <span class="text-muted" v-else>-</span>
                                        </td>
                                        <td>
                                            <span class="text-primary" v-if="item.TransferAmount > 0">
                                                {{ formatCurrency(item.TransferAmount) }}
                                            </span>
                                            <span class="text-muted" v-else>-</span>
                                        </td>
                                        <td>
                                            <div v-if="item.FromUserFullName || item.FromUserName" class="user-info">
                                                <div class="fw-medium">{{ item.FromUserFullName || item.FromUserName }}
                                                </div>
                                                <small class="text-muted" v-if="item.FromUserPhone">{{
                                                    item.FromUserPhone }}</small>
                                            </div>
                                            <span class="text-muted" v-else>-</span>
                                        </td>
                                        <td>
                                            <div v-if="item.OrderCodes && item.OrderCodes.length > 0"
                                                class="order-codes">
                                                <div v-for="(code, index) in item.OrderCodes.slice(0, 2)" :key="index"
                                                    class="badge bg-light text-dark me-1 mb-1">
                                                    {{ code }}
                                                </div>
                                                <div v-if="item.OrderCodes.length > 2" class="text-muted small">
                                                    +{{ item.OrderCodes.length - 2 }} đơn khác
                                                </div>
                                            </div>
                                            <span class="text-muted" v-else>-</span>
                                        </td>
                                        <td>
                                            <span class="text-muted">
                                                {{ item.FormattedBalance || formatCurrency(item.BalanceAfterTransaction)
                                                }}
                                            </span>
                                        </td>
                                        <td>
                                            <router-link :to="`/chi-tiet-giao-dich/${item.Id}`"
                                                class="btn btn-sm btn-outline-primary">
                                                <i class="fas fa-eye"></i> Chi tiết
                                            </router-link>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>

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

    <!-- Modal Cân ví -->
    <LadaDialog :visible="showAdjustModal">
        <template #header>
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-balance-scale me-2"></i>
                    Cân ví
                </h5>
                <button @click="closeAdjustModal" type="button" class="close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
        </template>
        <template #body>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Số dư hiện tại</label>
                    <input type="text" class="form-control" :value="formatCurrency(wallet?.Balance)" readonly>
                </div>
                <div class="mb-3">
                    <label class="form-label">Số dư mong muốn <span class="text-danger">*</span></label>
                    <input type="number" class="form-control" v-model.number="adjustForm.desiredBalance" min="0"
                        step="1000" placeholder="Nhập số dư mong muốn"
                        :class="{ 'is-invalid': adjustFormErrors.desiredBalance }">
                    <div class="invalid-feedback" v-if="adjustFormErrors.desiredBalance">
                        {{ adjustFormErrors.desiredBalance }}
                    </div>
                </div>
                <div class="mb-3" v-if="adjustmentAmount !== 0">
                    <div class="alert" :class="adjustmentAmount > 0 ? 'alert-success' : 'alert-warning'">
                        <i :class="adjustmentAmount > 0 ? 'fas fa-arrow-up' : 'fas fa-arrow-down'" class="me-2"></i>
                        <strong>{{ adjustmentAmount > 0 ? 'Cộng tiền:' : 'Trừ tiền:' }}</strong>
                        {{ formatCurrency(Math.abs(adjustmentAmount)) }}
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label">Lý do điều chỉnh <span class="text-danger">*</span></label>
                    <textarea class="form-control" v-model="adjustForm.reason" rows="3" maxlength="500"
                        placeholder="Nhập lý do điều chỉnh số dư..."
                        :class="{ 'is-invalid': adjustFormErrors.reason }"></textarea>
                    <div class="invalid-feedback" v-if="adjustFormErrors.reason">
                        {{ adjustFormErrors.reason }}
                    </div>
                    <small class="text-muted">{{ adjustForm.reason.length }}/500 ký tự</small>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" @click="closeAdjustModal" :disabled="adjusting">
                    Hủy
                </button>
                <button type="button" class="btn btn-primary" @click="handleAdjustBalance" :disabled="adjusting">
                    <span v-if="adjusting" class="spinner-border spinner-border-sm me-2"></span>
                    <i v-else class="fas fa-check me-2"></i>
                    Xác nhận
                </button>
            </div>
        </template>
    </LadaDialog>
</template>

<script setup>
import { ref, onMounted, reactive, nextTick, computed } from "vue";
import { useRoute } from "vue-router";
import { formatCurrency, formatDateTime } from "@/infrastructure/utilities/currencyHelper";
import walletService from "@/services/walletService";
import transactionService from "@/services/transactionService";
import BalanceHistoryChart from "@/components/charts/BalanceHistoryChart.vue";
import TransactionStatisticsChart from "@/components/charts/TransactionStatisticsChart.vue";
import DatepickerInstance from "@vuepic/vue-datepicker";
import { DateRangeSidebar, LadaDialog } from '@/components/index';
import { useToast } from 'vue-toastification';

const toast = useToast();

const route = useRoute();
const wallet = reactive({});
const loading = ref(false);
const loadingTransactions = ref(false);
const loadingBalanceHistory = ref(false);
const items = reactive([]);
const statistics = ref(null);
const balanceHistory = ref(null);

// Chart collapse state
const isChartCollapsed = ref(false); // Default to expanded

const searchModel = reactive({
    Pagination: {
        Total: 0,
        PageIndex: 1,
        PageSize: 25
    },
    Sort: {
        Predicate: '',
        Reverse: true
    },
    Search: {
        PredicateObject: {
            WalletId: route.params.id,
            Keyword: '',
            TransactionType: '',
            TransactionDirection: '',
            CreatedStart: null,
            CreatedEnd: null,
        }
    }
});

const ctrlPager = ref();

// Date picker variables
const date = ref();
const createDatePicker = ref(DatepickerInstance);

// Load wallet information
const loadWallet = async () => {
    try {
        loading.value = true;
        const response = await walletService.getById(route.params.id);
        Object.assign(wallet, response);
    } catch (error) {
        console.error("Lỗi khi tải thông tin ví:", error);
    } finally {
        loading.value = false;
    }
};

// Load transaction statistics from transaction list response
const loadStatistics = (transactionResponse) => {
    try {
        console.log("Loading statistics from transaction response:", transactionResponse);

        if (transactionResponse && (transactionResponse.TotalIncome !== undefined || transactionResponse.TotalOutcome !== undefined)) {
            // Use statistics from transaction list response
            const data = {
                TotalIncome: transactionResponse.TotalIncome || 0,
                TotalOutcome: transactionResponse.TotalOutcome || 0,
                NetBalance: transactionResponse.NetBalance || ((transactionResponse.TotalIncome || 0) - (transactionResponse.TotalOutcome || 0)),
                TotalTransactions: transactionResponse.TotalRecord || 0,
                TotalCash: transactionResponse.TotalCash,
                TotalTransfer: transactionResponse.TotalTransfer,
            };

            statistics.value = data;
            console.log("Statistics data assigned from transaction response:", statistics.value);

            // Also load daily balance history if available
            if (transactionResponse.DailyBalanceHistory && transactionResponse.DailyBalanceHistory.length > 0) {
                balanceHistory.value = {
                    DailyBalanceHistory: transactionResponse.DailyBalanceHistory,
                    FormattedInitialBalance: transactionResponse.DailyBalanceHistory[0]?.FormattedStartBalance || "0 VND",
                    FormattedCurrentBalance: transactionResponse.DailyBalanceHistory[transactionResponse.DailyBalanceHistory.length - 1]?.FormattedEndBalance || "0 VND",
                    InitialBalance: transactionResponse.DailyBalanceHistory[0]?.StartOfDayBalance || 0,
                    CurrentBalance: transactionResponse.DailyBalanceHistory[transactionResponse.DailyBalanceHistory.length - 1]?.EndOfDayBalance || 0
                };
                console.log("Daily balance history loaded from transaction response:", balanceHistory.value);
            }
        } else {
            console.log("No valid statistics data found in transaction response");
        }
    } catch (error) {
        console.error("Lỗi khi xử lý thống kê từ danh sách giao dịch:", error);
    }
};

// Load balance history
const loadBalanceHistory = async () => {
    try {
        loadingBalanceHistory.value = true;
        const response = await transactionService.getBalanceHistory(route.params.id);
        console.log("Balance History API response:", response);

        // Handle different response structures
        let data = null;
        if (response.Result === 1) {
            // Check if data is in response.Data or response itself
            data = response.Data || response;
        } else if (response.DailyBalanceHistory !== undefined) {
            // Direct response structure without Result field
            data = response;
        } else {
            console.log("Balance History API failed:", response.Message || "Unknown error");
            return;
        }

        if (data && (data.DailyBalanceHistory || data.TransactionBalanceHistory)) {
            balanceHistory.value = data;
            console.log("Balance History data assigned:", balanceHistory.value);
        } else {
            console.log("No valid balance history data found");
        }
    } catch (error) {
        console.error("Lỗi khi tải lịch sử số dư:", error);
    } finally {
        loadingBalanceHistory.value = false;
    }
};

// Load transactions
const loadTransactions = async () => {
    console.log("Loading transactions with searchModel:", searchModel); // Debug log
    loadingTransactions.value = true;
    items.splice(0, items.length);

    try {
        const searchResult = await transactionService.search(searchModel);
        console.log("Search result:", searchResult); // Debug log

        // Kiểm tra cấu trúc response
        if (searchResult && searchResult.Items) {
            console.log("Found Items in response:", searchResult.Items.length);
            searchResult.Items.forEach(transaction => {
                items.push(transaction);
            });
            searchModel.Pagination.Total = searchResult.TotalRecord || searchResult.TotalCount || 0;
            // Load statistics from response
            loadStatistics(searchResult);
        } else if (searchResult && Array.isArray(searchResult)) {
            // Nếu response là array trực tiếp
            console.log("Response is array:", searchResult.length);
            searchResult.forEach(transaction => {
                items.push(transaction);
            });
        } else {
            console.log("No valid data structure found in response");
        }

        console.log("Final items count:", items.length);
    } catch (error) {
        console.error("Lỗi khi tải giao dịch:", error);
    } finally {
        loadingTransactions.value = false;
    }
};

// Search function
const search = () => {
    searchModel.Pagination.PageIndex = 1;
    ctrlPager.value?.Refresh();
    loadTransactions();
};

// Reset filters
const resetFilters = () => {
    searchModel.Search.PredicateObject.Keyword = '';
    searchModel.Search.PredicateObject.TransactionType = '';
    searchModel.Search.PredicateObject.TransactionDirection = '';
    searchModel.Search.PredicateObject.CreatedStart = null;
    searchModel.Search.PredicateObject.CreatedEnd = null;
    date.value = null;
    search();
};

// Refresh all data
const refreshData = () => {
    loadWallet();
    loadTransactions(); // This will also load statistics and balance history from the response
};

// Export transactions
const exportTransactions = () => {
    // TODO: Implement export functionality
    console.log("Export transactions");
};

// Pagination handlers
const PageSizeChanged = (pagesize) => {
    searchModel.Pagination.PageSize = pagesize;
    searchModel.Pagination.PageIndex = 1;
    loadTransactions();
};

const PageIndexChanged = (pageIndex) => {
    searchModel.Pagination.PageIndex = pageIndex;
    loadTransactions();
};

// Utility functions
const getStatusBadgeClass = (status) => {
    switch (status) {
        case 'Active':
        case 1:
            return 'bg-success';
        case 'Inactive':
        case 2:
            return 'bg-danger';
        default:
            return 'bg-secondary';
    }
};

const getStatusText = (status) => {
    switch (status) {
        case 'Active':
        case 1:
            return 'Đang hoạt động';
        case 'Inactive':
        case 2:
            return 'Đã khóa';
        default:
            return 'Không xác định';
    }
};

const getTransactionIcon = (type) => {
    const icons = {
        '1': '💰', // Cước vận chuyển
        '2': '📦', // Thu hộ COD
        '3': '⛽', // Chi phí nhiên liệu
        '4': '💼', // Lương
        '5': '💸', // Chuyển khoản
        '6': '📥', // Nạp tiền
        '7': '📤', // Rút tiền
        '8': '↩️', // Hoàn tiền
        '9': '⚠️', // Phạt
        '10': '🎁' // Thưởng
    };
    return icons[type] || '💳';
};

const getTransactionTypeName = (type) => {
    const names = {
        '1': 'Cước vận chuyển',
        '2': 'Thu hộ COD',
        '3': 'Chi phí nhiên liệu',
        '4': 'Lương',
        '5': 'Chuyển khoản',
        '6': 'Nạp tiền',
        '7': 'Rút tiền',
        '8': 'Hoàn tiền',
        '9': 'Phạt',
        '10': 'Thưởng'
    };
    return names[type] || type;
};

const getTransactionTypeBadgeClass = (type) => {
    const classes = {
        '1': 'bg-primary',   // Cước vận chuyển
        '2': 'bg-info',      // Thu hộ COD
        '3': 'bg-warning',   // Chi phí nhiên liệu
        '4': 'bg-success',   // Lương
        '5': 'bg-secondary', // Chuyển khoản
        '6': 'bg-success',   // Nạp tiền
        '7': 'bg-danger',    // Rút tiền
        '8': 'bg-info',      // Hoàn tiền
        '9': 'bg-danger',    // Phạt
        '10': 'bg-warning'   // Thưởng
    };
    return classes[type] || 'bg-secondary';
};

const getAmountClass = (direction) => {
    return direction === 1 || direction === 'Income' ? 'text-success' : 'text-danger';
};

const getAmountColorClass = (amountColor, direction) => {
    if (amountColor) {
        switch (amountColor.toLowerCase()) {
            case 'green':
                return 'text-success';
            case 'red':
                return 'text-danger';
            case 'blue':
                return 'text-primary';
            case 'orange':
                return 'text-warning';
            default:
                return direction === 1 || direction === 'Income' ? 'text-success' : 'text-danger';
        }
    }
    return direction === 1 || direction === 'Income' ? 'text-success' : 'text-danger';
};

const getDirectionIcon = (direction) => {
    return direction === 1 || direction === 'Income' ? 'fas fa-arrow-up' : 'fas fa-arrow-down';
};

const getTransactionRowClass = (direction) => {
    return direction === 1 || direction === 'Income' ? 'income-highlight' : 'outcome-highlight';
};

const getNetBalanceClass = (netBalance) => {
    return netBalance >= 0 ? 'text-success' : 'text-danger';
};

const getNetBalanceIcon = (netBalance) => {
    return netBalance >= 0 ? 'fas fa-trending-up' : 'fas fa-trending-down';
};

// Date picker functions
const format = (dates) => {
    let start = dates[0];
    let 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}`;
};

async function onChangeDate(newDates) {
    date.value = newDates;
    createDatePicker.value.closeMenu();
    handleDate(newDates);
}

function handleDate(modelData) {
    if (modelData != null) {
        searchModel.Search.PredicateObject.CreatedStart = modelData[0];
        searchModel.Search.PredicateObject.CreatedEnd = modelData[1];
    } else {
        searchModel.Search.PredicateObject.CreatedStart = null;
        searchModel.Search.PredicateObject.CreatedEnd = null;
    }
}

// Toggle chart collapse
const toggleChartCollapse = () => {
    isChartCollapsed.value = !isChartCollapsed.value;
};


onMounted(() => {
    loadWallet();
    loadTransactions(); // This will also load statistics and balance history from the response
});

// Balance Adjustment
const showAdjustModal = ref(false);
const adjusting = ref(false);
const adjustForm = reactive({
    desiredBalance: 0,
    reason: ''
});
const adjustFormErrors = reactive({
    desiredBalance: '',
    reason: ''
});

const adjustmentAmount = computed(() => {
    return adjustForm.desiredBalance - (wallet?.Balance || 0);
});

const showAdjustBalanceModal = () => {
    adjustForm.desiredBalance = wallet?.Balance || 0;
    adjustForm.reason = '';
    adjustFormErrors.desiredBalance = '';
    adjustFormErrors.reason = '';
    showAdjustModal.value = true;
};

const closeAdjustModal = () => {
    showAdjustModal.value = false;
    adjustForm.desiredBalance = 0;
    adjustForm.reason = '';
    adjustFormErrors.desiredBalance = '';
    adjustFormErrors.reason = '';
};

const validateAdjustForm = () => {
    let isValid = true;
    adjustFormErrors.desiredBalance = '';
    adjustFormErrors.reason = '';

    if (adjustForm.desiredBalance < 0) {
        adjustFormErrors.desiredBalance = 'Số dư mong muốn phải >= 0';
        isValid = false;
    }

    if (!adjustForm.reason || adjustForm.reason.trim() === '') {
        adjustFormErrors.reason = 'Lý do điều chỉnh là bắt buộc';
        isValid = false;
    } else if (adjustForm.reason.length > 500) {
        adjustFormErrors.reason = 'Lý do không được vượt quá 500 ký tự';
        isValid = false;
    }

    return isValid;
};

const handleAdjustBalance = async () => {
    if (!validateAdjustForm()) {
        return;
    }

    if (adjustmentAmount.value === 0) {
        toast.info('Số dư hiện tại đã khớp với số dư mong muốn');
        return;
    }

    const confirmMessage = adjustmentAmount.value > 0
        ? `Bạn có chắc chắn muốn cộng ${formatCurrency(Math.abs(adjustmentAmount.value))} vào ví?`
        : `Bạn có chắc chắn muốn trừ ${formatCurrency(Math.abs(adjustmentAmount.value))} khỏi ví?`;

    if (!confirm(confirmMessage)) {
        return;
    }

    try {
        adjusting.value = true;
        const result = await walletService.adjustBalance(
            route.params.id,
            adjustForm.desiredBalance,
            adjustForm.reason
        );

        if (result.Result === 1) {
            toast.success(result.Message || 'Cân ví thành công');
            closeAdjustModal();
            await loadWallet();
            await loadTransactions();
        } else {
            toast.error(result.Message || 'Có lỗi xảy ra khi cân ví');
        }
    } catch (error) {
        console.error('Error adjusting balance:', error);
        toast.error(error.response?.data?.Message || 'Có lỗi xảy ra khi cân ví');
    } finally {
        adjusting.value = false;
    }
};
</script>

<style scoped>
.wallet-stats-card {
    border: 1px solid #dee2e6;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.card {
    box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
    border: none;
}

.card-header {
    background-color: #f8f9fa;
    border-bottom: 1px solid #dee2e6;
    padding: 1rem 1.25rem;
}

.card-header h5 {
    color: #495057;
    font-weight: 600;
}

.balance-display {
    padding: 1.5rem 0;
}

.wallet-info-horizontal {
    padding: 0.75rem 1rem;
    background-color: #f8f9fa;
    border-radius: 8px;
}

.info-item-horizontal {
    padding: 0.5rem 0;
}

.stat-item {
    padding: 0.5rem;
    border-radius: 0.375rem;
    background-color: #f8f9fa;
}

.transaction-row:hover {
    background-color: #f8f9fa;
}

.transaction-icon {
    font-size: 1.2em;
}

.transaction-time {
    font-size: 0.9em;
}

.transaction-description {
    max-width: 300px;
}

.transaction-direction-icon {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 24px;
    height: 24px;
    border-radius: 50%;
    font-size: 0.8em;
}

.transaction-direction-icon.text-success {
    background-color: rgba(40, 167, 69, 0.1);
    color: #28a745;
}

.transaction-direction-icon.text-danger {
    background-color: rgba(220, 53, 69, 0.1);
    color: #dc3545;
}

.income-highlight {
    background: linear-gradient(135deg, rgba(40, 167, 69, 0.05) 0%, rgba(40, 167, 69, 0.1) 100%);
    border-left: 3px solid #28a745;
}

.outcome-highlight {
    background: linear-gradient(135deg, rgba(220, 53, 69, 0.05) 0%, rgba(220, 53, 69, 0.1) 100%);
    border-left: 3px solid #dc3545;
}

.summary-card {
    padding: 1rem;
    border-radius: 0.5rem;
}

/* Chart collapse animation */
.collapse {
    transition: all 0.35s ease;
    overflow: hidden;
}

.collapse.show {
    height: auto;
    opacity: 1;
}

.collapse:not(.show) {
    height: 0 !important;
    opacity: 0;
    padding: 0;
    margin: 0;
}

/* Chart toggle button */
.btn-outline-light:hover {
    background-color: rgba(255, 255, 255, 0.1);
    border-color: rgba(255, 255, 255, 0.3);
}

.summary-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.income-card {
    border-left: 4px solid #28a745;
}

.outcome-card {
    border-left: 4px solid #dc3545;
}

.net-balance-card {
    border-left: 4px solid #6c757d;
}

.net-balance-card.net-positive {
    border-left-color: #28a745;
    background: linear-gradient(135deg, #f8fff9 0%, #e8f5e8 100%);
}

.net-balance-card.net-negative {
    border-left-color: #dc3545;
    background: linear-gradient(135deg, #fff8f8 0%, #f5e8e8 100%);
}

.summary-icon {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.2em;
}

.income-card .summary-icon {
    background-color: rgba(40, 167, 69, 0.1);
    color: #28a745;
}

.outcome-card .summary-icon {
    background-color: rgba(220, 53, 69, 0.1);
    color: #dc3545;
}

.summary-icon.income {
    background-color: #d1f4e0;
    color: #28a745;
}

.summary-icon.outcome {
    background-color: #f8d7da;
    color: #dc3545;
}

.summary-icon.net {
    background-color: #e2e3e5;
    color: #6c757d;
}

.summary-label {
    font-size: 0.875rem;
    color: #6c757d;
    margin-bottom: 0.25rem;
}

.summary-value {
    font-size: 1.1rem;
    font-weight: 600;
}

.net-balance-card {
    padding: 1rem;
    border-radius: 0.5rem;
    border: 2px solid;
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.9) 0%, rgba(248, 249, 250, 0.9) 100%);
}

.net-balance-card.net-positive {
    border-color: #28a745;
    background: linear-gradient(135deg, rgba(40, 167, 69, 0.05) 0%, rgba(40, 167, 69, 0.1) 100%);
}

.net-balance-card.net-negative {
    border-color: #dc3545;
    background: linear-gradient(135deg, rgba(220, 53, 69, 0.05) 0%, rgba(220, 53, 69, 0.1) 100%);
}

.net-label {
    font-size: 0.875rem;
    color: #6c757d;
    margin-bottom: 0.25rem;
}

.net-value {
    font-size: 1.25rem;
    font-weight: 700;
}

.net-balance-card.net-positive .net-value {
    color: #28a745;
}

.net-balance-card.net-negative .net-value {
    color: #dc3545;
}

.net-icon {
    font-size: 2rem;
}

.net-balance-card.net-positive .net-icon {
    color: #28a745;
}

.net-balance-card.net-negative .net-icon {
    color: #dc3545;
}

.order-codes {
    max-width: 150px;
}

.order-codes .badge {
    font-size: 0.7rem;
    padding: 0.25rem 0.5rem;
}

.transaction-icon {
    font-size: 1.2em;
    min-width: 24px;
    text-align: center;
}

.user-info {
    max-width: 120px;
}

.user-info .fw-medium {
    font-size: 0.9rem;
    line-height: 1.2;
}

.user-info small {
    font-size: 0.75rem;
}

.table th {
    font-weight: 600;
    color: #495057;
    border-top: none;
    background-color: #f8f9fa;
}

.badge {
    font-size: 0.75em;
}

.pagination .page-link {
    padding: 0.375rem 0.75rem;
}

.balance-history-chart {
    position: relative;
}

@media (max-width: 768px) {

    .col-lg-4,
    .col-lg-8 {
        margin-bottom: 1rem;
    }

    .transaction-description {
        max-width: 200px;
    }

    .d-flex.gap-2 {
        flex-direction: column;
        gap: 0.5rem !important;
    }
}
</style>
