<template>
  <div>
    <!-- 1. Breadcrumb Header -->
    <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"><a href="javascript:void(0);">Trang chủ</a></li>
          <li class="breadcrumb-item"><a href="javascript:void(0);">Tài chính</a></li>
          <li class="breadcrumb-item active" aria-current="page">Chi tiết ví</li>
        </ol>
      </div>
    </div>

    <!-- 2. Main Content Container -->
    <div class="row row-sm">
      <div class="col-sm-12 col-md-12 col-lg-12 col-xl-12 grid-margin">

        <!-- 3. 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>

        <!-- 4. Error State -->
        <div v-else-if="hasError" class="alert alert-danger">
          <h5>Đã xảy ra lỗi</h5>
          <p>{{ errorMessage }}</p>
          <button @click="retry" class="btn btn-outline-danger">
            Thử lại
          </button>
        </div>

        <!-- 5. Main Content -->
        <div v-else>
          <!-- Card thông tin ví và danh sách giao dịch -->
          <div class="row mb-4">
            <div class="col-12">
              <!-- Card gộp thông tin ví -->
              <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">{{ formattedBalance }}</span>
                        </div>
                      </div>
                    </div>

                    <!-- Cột thông tin ví -->
                    <div class="col-lg-8">
                      <div class="ps-lg-4">
                        <!-- Thông tin ví -->
                        <div class="wallet-info-horizontal">
                          <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="statusInfo.class">
                                  {{ statusInfo.text }}
                                </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>

          <!-- Card 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">
                <!-- Search Form -->
                <div class="p-3 border-bottom">
                  <div class="row">
                    <div class="col-lg-6 col-md-8 mb-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-lg-6 col-md-4 mb-3 d-flex align-items-end">
                      <button class="btn btn-secondary" @click="search" :disabled="loadingTransactions">
                        <i v-show="!loadingTransactions" class="fas fa-search"></i>
                        <span v-show="loadingTransactions" class="spinner-border spinner-border-sm"></span>
                        <span>Tìm kiếm</span>
                      </button>
                    </div>
                  </div>
                </div>

                <!-- Transaction Table -->
                <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>Thời gian</th>
                        <th>Loại</th>
                        <th>Hướng</th>
                        <th>Số tiền</th>
                        <th>Tiền mặt</th>
                        <th>Chuyển khoản</th>
                        <th>Ghi chú</th>
                        <th>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>
                          <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.TransactionDirection === 1 ? 'Thu' : 'Chi' }}
                            </span>
                          </div>
                        </td>
                        <td>
                          <span class="fw-bold" :class="getAmountClass(item.TransactionDirection)">
                            {{ (item.TransactionDirection === 1 ? '+' : '-') + formatCurrency(item.Amount) }}
                          </span>
                        </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>
                          <span class="text-muted">{{ item.Note || '-' }}</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>
    </div>
  </div>
</template>

<script setup>
//#region Imports
// 1. Vue core
import { ref, reactive, onMounted, onErrorCaptured, computed } from 'vue'

// 2. Vue Router
import { useRoute } from 'vue-router'

// 3. Third-party libraries
import { useToast } from "vue-toastification"

// 4. Internal utilities
import { formatCurrency, formatDateTime } from "@/infrastructure/utilities/currencyHelper"

// 5. Internal services
import walletService from "@/services/walletService"
import transactionService from "@/services/transactionService"
//#endregion

//#region Constants
const toast = useToast()
const route = useRoute()
//#endregion

//#region Reactive State
const wallet = reactive({})
const items = reactive([])
const loading = ref(false)
const loadingTransactions = ref(false)
const hasError = ref(false)
const errorMessage = ref('')

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

const ctrlPager = ref()
//#endregion

//#region Error Handling
const handleError = (error, context = 'API call') => {
  console.error(`${context}:`, error)
  hasError.value = true

  if (error.response) {
    const { status, data } = error.response
    switch (status) {
      case 400:
        errorMessage.value = data.message || 'Dữ liệu không hợp lệ'
        break
      case 401:
        errorMessage.value = 'Phiên đăng nhập đã hết hạn'
        break
      case 403:
        errorMessage.value = 'Bạn không có quyền thực hiện hành động này'
        break
      case 404:
        errorMessage.value = 'Không tìm thấy dữ liệu ví'
        break
      case 500:
        errorMessage.value = 'Lỗi máy chủ, vui lòng thử lại sau'
        break
      default:
        errorMessage.value = data.message || 'Có lỗi xảy ra'
    }
  } else if (error.request) {
    errorMessage.value = 'Không thể kết nối đến máy chủ'
  } else {
    errorMessage.value = error.message || 'Có lỗi không xác định'
  }

  toast.error(errorMessage.value)
}

const retry = () => {
  hasError.value = false
  errorMessage.value = ''
  refreshData()
}

onErrorCaptured((error, instance, info) => {
  handleError(error, 'Component error')
  return false
})
//#endregion

//#region Data Loading
const loadWallet = async () => {
  try {
    loading.value = true
    const response = await walletService.getById(route.params.id)
    Object.assign(wallet, response)
  } catch (error) {
    handleError(error, 'Lỗi khi tải thông tin ví')
  } finally {
    loading.value = false
  }
}

const loadTransactions = async () => {
  try {
    loadingTransactions.value = true
    items.splice(0, items.length)

    const searchResult = await walletService.getTransactions(searchModel)

    if (searchResult?.Items?.length > 0) {
      searchResult.Items.forEach(transaction => {
        items.push(transaction)
      })
    }

    searchModel.Pagination.Total = searchResult?.TotalRecord || 0
  } catch (error) {
    handleError(error, 'Lỗi khi tải danh sách giao dịch')
  } finally {
    loadingTransactions.value = false
  }
}

const refreshData = () => {
  loadWallet()
  loadTransactions()
}
//#endregion

//#region Search Functions
const search = async () => {
  searchModel.Pagination.PageIndex = 1
  ctrlPager.value?.Refresh()
  loadTransactions()
}

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

const PageIndexChanged = (pageIndex) => {
  searchModel.Pagination.PageIndex = pageIndex
  loadTransactions()
}
//#endregion

//#region Computed Properties
const formattedBalance = computed(() => {
  return wallet?.Balance ? formatCurrency(wallet.Balance) : '0 VND'
})

const statusInfo = computed(() => {
  const status = wallet?.WalletStatus
  switch (status) {
    case 'Active':
    case 1:
      return { class: 'bg-success', text: 'Đang hoạt động' }
    case 'Inactive':
    case 2:
      return { class: 'bg-danger', text: 'Đã khóa' }
    default:
      return { class: 'bg-secondary', text: 'Không xác định' }
  }
})

const totalItems = computed(() => searchModel.Pagination.Total)
const hasItems = computed(() => items.length > 0)
//#endregion

//#region 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 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 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'
}
//#endregion

//#region Lifecycle
onMounted(() => {
  refreshData()
})
//#endregion
</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;
}

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

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

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

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

.pagination .page-item.disabled .page-link {
  color: #6c757d;
  pointer-events: none;
  background-color: #fff;
  border-color: #dee2e6;
}

/* Loading overlay */
.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

/* Responsive design */
@media (max-width: 768px) {

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

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

  .table-responsive {
    font-size: 0.875rem;
  }
}

/* Animation */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>