<template>
    <div class="container-fluid">
        <!-- Breadcrumb -->
        <div class="breadcrumb-header justify-content-between">
            <div class="my-auto">
                <h4 class="page-title">Ví của tôi</h4>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item">
                        <router-link to="/">Trang chủ</router-link>
                    </li>
                    <li class="breadcrumb-item active" aria-current="page">Ví của tôi</li>
                </ol>
            </div>
        </div>

        <!-- Loading State -->
        <div v-if="loading" class="text-center py-5">
            <div class="spinner-border text-secondary" 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>
            <!-- Thông tin ví và thống kê -->
            <div class="row mb-4">
                <div class="col-12">
                    <!-- Card gộp thông tin ví và thống kê -->
                    <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í và thống kê
                            </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à thống kê -->
                                <div class="col-lg-8">
                                    <div class="ps-lg-4">
                                        <!-- Nút hành động -->
                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <button class="btn btn-outline-primary" @click="showTransferMoneyModal">
                                                    <i class="fas fa-exchange-alt me-2"></i>
                                                    Chuyển tiền
                                                </button>
                                                <button class="mg-l-20 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)">
                                                            {{ wallet?.WalletStatus || 'Không xác định' }}
                                                        </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 -->
            <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>
                            </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)">
                                <!-- Summary Cards -->
                                <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="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-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>
                                            </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 Chuyển tiền -->
    <LadaDialog :visible="showTransferModal">
        <template #header>
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-exchange-alt me-2"></i>
                    Chuyển tiền
                </h5>
            </div>
        </template>
        <template #body>
            <TransferMoneyModal :wallet="wallet" @close="handleTransferClose" @success="handleTransferSuccess" />
        </template>
    </LadaDialog>

    <!-- 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>
            </div>
        </template>
        <template #body>
            <AdjustBalanceModal :wallet="wallet" @close="handleAdjustClose" @success="handleAdjustSuccess" />
        </template>
    </LadaDialog>
</template>

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

const toast = useToast();

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

const searchModel = reactive({
    Pagination: {
        Total: 0,
        PageIndex: 1,
        PageSize: 25
    },
    Sort: {
        Predicate: '',
        Reverse: true
    },
    Search: {
        PredicateObject: {
            WalletId: null,
            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.getMyWallet();
        Object.assign(wallet, response);
        // Set WalletId for transaction search
        searchModel.Search.PredicateObject.WalletId = response.Id;
    } 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 {
        if (transactionResponse && (transactionResponse.TotalIncome !== undefined || transactionResponse.TotalOutcome !== undefined)) {
            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,
                TotalCod: transactionResponse.TotalCod,
            };
            statistics.value = data;
        }
    } catch (error) {
        console.error("Lỗi khi xử lý thống kê:", error);
    }
};

// Load transactions
const loadTransactions = async () => {
    loadingTransactions.value = true;
    items.splice(0, items.length);

    try {
        const searchResult = await transactionService.search(searchModel);

        if (searchResult && searchResult.Items) {
            searchResult.Items.forEach(transaction => {
                items.push(transaction);
            });
            searchModel.Pagination.Total = searchResult.TotalRecord || searchResult.TotalCount || 0;
            loadStatistics(searchResult);
        }
    } 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();
};

// 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) => {
    if (status === 'Hoạt động' || status === 'Active' || status === 1) {
        return 'bg-success';
    }
    return 'bg-secondary';
};

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 getAmountClass = (direction) => {
    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 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 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-primary',   // 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 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 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;
    }
}

onMounted(async () => {
    await loadWallet();
    await loadTransactions();
});


// Adjust Balance Modal
const showAdjustModal = ref(false);

const showAdjustBalanceModal = () => {
    showAdjustModal.value = true;
};


// Transfer Money
const showTransferModal = ref(false);
const transferring = ref(false);
const walletLoading = ref(false);
const walletOptions = reactive([]);
const selectedWallet = ref(null);
const transferForm = reactive({
    destinationWalletId: null,
    amount: 0,
    note: ''
});
const transferFormErrors = reactive({
    destinationWalletId: '',
    amount: ''
});

let walletSearchTimeout = null;

const onWalletSearch = (search, loading) => {
    if (walletSearchTimeout) {
        clearTimeout(walletSearchTimeout);
    }

    walletSearchTimeout = setTimeout(async () => {
        if (search.length) {
            loading(true);
            try {
                const searchModel = {
                    Pagination: {
                        PageIndex: 1,
                        PageSize: 20
                    },
                    Sort: {
                        Predicate: '',
                        Reverse: false
                    },
                    Search: {
                        PredicateObject: {
                            Keyword: search
                        }
                    }
                };
                const result = await walletService.search(searchModel);

                if (result?.Items) {
                    // Lọc bỏ ví hiện tại
                    const filteredWallets = result.Items.filter(w => w.Id !== wallet?.Id);
                    walletOptions.splice(0, walletOptions.length, ...filteredWallets);
                }
            } catch (error) {
                console.error('Error searching wallets:', error);
                toast.error('Lỗi khi tìm kiếm ví');
            } finally {
                loading(false);
            }
        }
    }, 300);
};

const showTransferMoneyModal = () => {
    transferForm.destinationWalletId = null;
    transferForm.amount = 0;
    transferForm.note = '';
    transferFormErrors.destinationWalletId = '';
    transferFormErrors.amount = '';
    selectedWallet.value = null;
    walletOptions.splice(0, walletOptions.length);
    showTransferModal.value = true;
};

const closeTransferModal = () => {
    showTransferModal.value = false;
    transferForm.destinationWalletId = null;
    transferForm.amount = 0;
    transferForm.note = '';
    transferFormErrors.destinationWalletId = '';
    transferFormErrors.amount = '';
    selectedWallet.value = null;
    walletOptions.splice(0, walletOptions.length);
};

const validateTransferForm = () => {
    let isValid = true;
    transferFormErrors.destinationWalletId = '';
    transferFormErrors.amount = '';

    if (!selectedWallet.value || !selectedWallet.value.Id) {
        transferFormErrors.destinationWalletId = 'Vui lòng chọn ví đích';
        isValid = false;
    } else {
        transferForm.destinationWalletId = selectedWallet.value.Id;

        if (transferForm.destinationWalletId === wallet?.Id) {
            transferFormErrors.destinationWalletId = 'Không thể chuyển tiền cho chính mình';
            isValid = false;
        }
    }

    if (!transferForm.amount || transferForm.amount <= 0) {
        transferFormErrors.amount = 'Số tiền phải lớn hơn 0';
        isValid = false;
    }

    if (transferForm.amount > (wallet?.Balance || 0)) {
        transferFormErrors.amount = `Số dư không đủ. Số dư hiện tại: ${formatCurrency(wallet?.Balance)}`;
        isValid = false;
    }

    return isValid;
};

const handleTransfer = async () => {
    if (!validateTransferForm()) {
        return;
    }

    const confirmMessage = `Bạn có chắc chắn muốn chuyển ${formatCurrency(transferForm.amount)} đến ví của ${selectedWallet.value.FullName} (${selectedWallet.value.UserName})?`;

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

    try {
        transferring.value = true;
        const result = await walletService.transfer(
            transferForm.destinationWalletId,
            transferForm.amount,
            transferForm.note
        );

        if (result.Result === 1) {
            toast.success(result.Message || 'Chuyển tiền thành công');
            closeTransferModal();
            await loadWallet();
            await loadTransactions();
        } else {
            toast.error(result.Message || 'Có lỗi xảy ra khi chuyển tiền');
        }
    } catch (error) {
        console.error('Error transferring money:', error);
        toast.error(error.response?.data?.Message || error.response?.data?.message || 'Có lỗi xảy ra khi chuyển tiền');
    } finally {
        transferring.value = false;
    }
};

// Simple handlers for modal components
const handleAdjustClose = () => {
    showAdjustModal.value = false;
};

const handleAdjustSuccess = async () => {
    await loadWallet();
    await loadTransactions();
};

const handleTransferClose = () => {
    showTransferModal.value = false;
};

const handleTransferSuccess = async () => {
    await loadWallet();
    await loadTransactions();
};
</script>

<style scoped>
/* Minimal color scheme - mainly gray and subtle blue */

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

.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 .info-item {
    display: flex;
    align-items: center;
    padding: 0.75rem 0;
    border-bottom: 1px solid #f1f3f5;
}

.wallet-info .info-item:last-child {
    border-bottom: none;
}

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

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

.summary-card {
    background-color: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 8px;
    padding: 1rem;
    margin-bottom: 1rem;
}

.summary-icon {
    width: 48px;
    height: 48px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.25rem;
}

.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.25rem;
    font-weight: 600;
}

.stat-item {
    padding: 0.5rem;
}

.table-light {
    background-color: #f8f9fa;
}

.table-hover tbody tr:hover {
    background-color: #f8f9fa;
}

.transaction-row {
    border-bottom: 1px solid #f1f3f5;
}

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

.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;
}

.badge {
    font-weight: 500;
    padding: 0.35rem 0.65rem;
}

.btn-outline-secondary {
    border-color: #dee2e6;
    color: #6c757d;
}

.btn-outline-secondary:hover {
    background-color: #f8f9fa;
    border-color: #dee2e6;
    color: #495057;
}

.btn-secondary {
    background-color: #6c757d;
    border-color: #6c757d;
}

.btn-secondary:hover {
    background-color: #5a6268;
    border-color: #545b62;
}
</style>
