<template>
  <div>
    <!-- 1. Breadcrumb Header -->
    <div class="breadcrumb-header justify-content-between">
      <div class="my-auto">
        <h4 class="page-title">Quản lý 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">Quản lý 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. Error State -->
        <div v-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>

        <!-- 4. Main Content -->
        <div v-else>
          <div class="card card-search shadow-none">
            <form class="card-body" @submit.prevent="search">
              <div class="row">
                <div class="col-lg-3 col-md-4 mb-3">
                  <label>Từ khóa</label>
                  <input type="text" v-model="searchModel.Search.PredicateObject.Keyword" class="form-control"
                    placeholder="từ khóa...">
                </div>
                <div class="col-lg-3 col-md-4 mb-3">
                  <label>Ngày tạo</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 class="col-lg-3 col-md-4 mb-3">
                  <label>Trạng thái</label>
                  <v-select label="Name" :options="statuses" v-model="searchModel.Search.PredicateObject.Status"
                    :reduce="(option) => option.Id"></v-select>
                </div>



              </div>
              <div class="row">
                <div class="col-lg mb-3">
                  <button type="submit" class="btn btn-dark" :disabled="loading">
                    <i v-show="!loading" class="fe fe-search"></i>
                    <span v-show="loading" class="spinner-border spinner-border-sm"></span>
                    <span>Tìm kiếm</span>
                  </button>
                </div>
              </div>

            </form>
          </div>


          <div class="card card-table shadow-none">
            <div class="card-body card-table-body">
              <div class="d-flex flex-row justify-content-between mg-b-10">
                <!-- <button @click="fnCreateOrUpdate(0)" type="button"
                                class="btn btn-outline-primary mx-2 button-icon mb-1">
                                <i class="fe fe-plus me-2"></i>
                                Tạo chi nhánh
                            </button> -->
                <!-- <button type="button" class="btn btn-outline-success mx-2 button-icon mb-1">
                                <i class="fe fe-download me-2"></i>Xuất excel</button> -->
              </div>
              <div class="table-responsive border-top mg-b-10">
                <table class="table table-vcenter mb-0" style="min-height:300px">
                  <thead>
                    <tr>
                      <th class="wd-lg-12p min-width-1"><span>ID</span></th>
                      <th class="wd-lg-20p min-width-1"><span>Chủ sở hữu</span></th>
                      <th class="wd-lg-20p min-width-2"><span>Loại ví</span></th>
                      <th class="wd-lg-20p min-width-2"><span>Số dư</span></th>
                      <th class="wd-lg-20p min-width-1"><span>Trạng thái</span></th>
                      <th class="wd-lg-8p"></th>
                    </tr>
                  </thead>
                  <tbody v-if="loading">
                    <tr>
                      <td colspan="7" class="tx-semibold text-center text-default">
                        <span class="spinner-border spinner-border-sm"></span>
                      </td>
                    </tr>
                  </tbody>
                  <tbody v-if="!loading && items.length <= 0">
                    <tr>
                      <td colspan="7" class="tx-semibold text-center text-danger">
                        Không tìm thấy bản ghi nào!
                      </td>
                    </tr>
                  </tbody>
                  <tbody v-if="!loading && items.length > 0">

                    <tr v-for="item in items" :key="item.Id">

                      <td class="text-wrap align-top">

                        <div>
                          {{ item.Id }}
                        </div>

                      </td>
                      <td class="text-wrap align-top">
                        {{ item.FullName }} - {{ item.UserName }}

                      </td>
                      <td class="text-wrap align-top">
                        <div> {{ item.WalletType }}</div>

                      </td>

                      <td class="text-wrap align-top">
                        <span class="fw-bold text-success">
                          {{ item.Balance }}
                        </span>
                      </td>

                      <td class="text-wrap align-top">
                        <span v-if="item.Status === 1" class="badge bg-success">Đang hoạt động</span>
                        <span v-else-if="item.Status === 2" class="badge bg-danger">Dừng hoạt động</span>
                        <span v-else class="badge bg-secondary">Không xác định</span>
                      </td>
                      <td class="align-top pt-2">
                        <button type="button" data-bs-toggle="dropdown"
                          class="mb-1 mt-1 mr-1 btn btn-light dropdown-toggle btn-sm" aria-expanded="false"><i
                            class="fas fa-cog"></i> Quản lý
                        </button>
                        <div class="dropdown-menu dropdown-menu-arrow">
                          <router-link :to="'/quan-ly-vi-tien/' + item.Id" class="dropdown-item">
                            <i class="fe fe-eye"></i>
                            <span class="mg-l-6">Xem chi tiết</span>
                          </router-link>
                          <a @click="fnCreateOrUpdate(item.Id)" class="dropdown-item" href="javascript:void(0);"><i
                              class="fe fe-edit-2"></i>
                            <span class="mg-l-6">Cập nhật</span>
                          </a>
                          <a @click="updateStatus(item.Id, 3, 'Kích hoạt')"
                            v-if="item.Status == 1 || item.Status == 4 || item.Status == 5" class="dropdown-item"
                            href="javascript:void(0);">
                            <i class="fe fe-check"></i>
                            <span class="mg-l-6">Kích hoạt</span></a>
                          <a @click="updateStatus(item.Id, 4, 'Khóa 1 chiều')"
                            v-if="item.Status == 1 || item.Status == 3 || item.Status == 5" class="dropdown-item"
                            href="javascript:void(0);">
                            <i class="fe fe-lock"></i>
                            <span class="mg-l-6">Khóa 1 chiều</span></a>
                          <a @click="updateStatus(item.Id, 5, 'Dừng hoạt động')"
                            v-if="item.Status == 1 || item.Status == 3 || item.Status == 4" class="dropdown-item"
                            href="javascript:void(0);">
                            <i class="fe fe-power"></i>
                            <span class="mg-l-6">Dừng hoạt động</span></a>
                        </div>
                      </td>
                    </tr>

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

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

// 2. Third-party libraries
import DatepickerInstance from "@vuepic/vue-datepicker"
import { useToast } from "vue-toastification"

// 3. Internal utilities
// import { formatCurrency } from "@/infrastructure/utilities/currencyHelper" // Removed - Balance already formatted from API

// 4. Internal components
import { DateRangeSidebar } from '@/components/index'

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

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

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

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

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

const ctrlPager = ref()
//#endregion

//#region Static Data
const statuses = [
  { Id: 1, Name: 'Đang hoạt động' },
  { Id: 2, Name: 'Dừng hoạt động' }
]
//#endregion

//#region Computed Properties
const totalItems = computed(() => searchModel.Pagination.Total)
const hasItems = computed(() => items.length > 0)
const isSearching = computed(() => loading.value)

const filteredItems = computed(() => {
  // This could be used for client-side filtering if needed
  return items
})
//#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'
        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 = ''
  search()
}

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

//#region Data Loading
const loadData = async () => {
  try {
    loading.value = true
    items.splice(0, items.length)

    const searchResult = await walletService.search(searchModel)

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

    searchModel.Pagination.Total = searchResult?.TotalRecord || 0
  } catch (error) {
    handleError(error, 'Lỗi khi tải danh sách ví')
  } finally {
    loading.value = false
  }
}
//#endregion

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

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

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

//#region Date Picker Functions
const format = (dates) => {
  if (!dates || dates.length < 2) return ''

  const start = dates[0]
  const 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}`
}

const onChangeDate = async (newDates) => {
  date.value = newDates
  createDatePicker.value?.closeMenu()
  handleDate(newDates)
}

const handleDate = (modelData) => {
  if (modelData != null && modelData.length >= 2) {
    searchModel.Search.PredicateObject.CreatedStart = modelData[0]
    searchModel.Search.PredicateObject.CreatedEnd = modelData[1]
  } else {
    searchModel.Search.PredicateObject.CreatedStart = null
    searchModel.Search.PredicateObject.CreatedEnd = null
  }
}
//#endregion

//#region Action Functions
const updateStatus = async (id, status, statusName) => {
  const confirmed = confirm(`Bạn chắc chắn muốn ${statusName.toLowerCase()}?`)
  if (!confirmed) return

  try {
    loading.value = true
    const result = await walletService.updateStatus(id, status)

    if (result?.Result === 1) {
      toast.success('Cập nhật trạng thái thành công!')
      search()
    } else {
      toast.error('Thất bại: ' + (result?.Message || 'Có lỗi xảy ra'))
    }
  } catch (error) {
    handleError(error, 'Lỗi khi cập nhật trạng thái')
  } finally {
    loading.value = false
  }
}

const fnCreateOrUpdate = (id) => {
  // TODO: Implement create/update functionality
  console.log('Create or update wallet:', id)
}
//#endregion

//#region Lifecycle
onMounted(async () => {
  await search()
})
//#endregion
</script>
