<template>
  <div>
    <!-- Breadcrumb Header -->
    <div class="breadcrumb-header justify-content-between">
      <div class="my-auto">
        <h4 class="page-title">Quản lý chi phí</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ý chi phí</li>
        </ol>
      </div>
    </div>

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

        <!-- Search Form Card -->
        <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>
                <DatepickerInstance 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>
                </DatepickerInstance>
              </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 class="col-lg-3 col-md-4 mb-3">
                <label>Danh mục chi phí</label>
                <v-select label="Name" :options="expenseCategories"
                  v-model="searchModel.Search.PredicateObject.ExpenseCategoryId" :reduce="(option) => option.Id">
                  <template v-slot:no-options="{ search, searching }">
                    <template v-if="searching">
                      Không có kết quả cho <em>{{ search }}</em>.
                    </template>
                    <span v-else style="opacity: 0.8">Không có bản ghi nào</span>
                  </template>
                  <template v-slot:option="option">
                    <span :style="{ paddingLeft: (option.Level || 0) * 20 + 'px' }">
                      {{ option.Name }}
                      <small v-if="option.Level > 0" class="text-muted">(Level {{ option.Level }})</small>
                    </span>
                  </template>
                </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>

        <!-- Data Table Card -->
        <div class="card card-table shadow-none">
          <div class="card-body card-table-body">
            <!-- Action Buttons -->
            <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 mới
              </button>
            </div>

            <!-- Table -->
            <div class="table-responsive border-top mg-b-10">
              <table class="table table-vcenter mb-0" style="min-height:300px">
                <thead>
                  <tr>
                    <th class="wd-lg-18p min-width-2"><span>Mô tả</span></th>
                    <th class="wd-lg-10p"><span>Số tiền</span></th>
                    <th class="wd-lg-12p"><span>Danh mục</span></th>
                    <th class="wd-lg-8p"><span>Trạng thái</span></th>
                    <th class="wd-lg-10p"><span>Thông tin ngân hàng</span></th>
                    <th class="wd-lg-8p"><span>Người tạo</span></th>
                    <th class="wd-lg-8p"><span>Người duyệt</span></th>
                    <th class="wd-lg-8p"><span>Ngày tạo</span></th>
                    <th class="wd-lg-18p"></th>
                  </tr>
                </thead>

                <!-- Loading State -->
                <tbody v-if="loading">
                  <tr>
                    <td colspan="9" class="tx-semibold text-center text-default">
                      <span class="spinner-border spinner-border-sm"></span>
                    </td>
                  </tr>
                </tbody>

                <!-- Empty State -->
                <tbody v-if="!loading && expenses.length <= 0">
                  <tr>
                    <td colspan="9" class="tx-semibold text-center text-danger">
                      Không tìm thấy bản ghi nào!
                    </td>
                  </tr>
                </tbody>

                <!-- Data Rows -->
                <tbody v-if="!loading && expenses.length > 0">
                  <tr v-for="expense in expenses" :key="expense.Id">
                    <td class="text-wrap align-top">
                      <div>
                        <strong>{{ expense.Description }}</strong>
                        <div v-if="expense.Note" class="text-muted small">
                          {{ expense.Note }}
                        </div>
                      </div>
                    </td>
                    <td class="align-top">
                      <strong class="text-primary">{{ formatCurrency(expense.Amount) }}</strong>
                    </td>
                    <td class="align-top">
                      <span class="badge bg-info">{{ expense.ExpenseCategoryName }}</span>
                    </td>
                    <td class="align-top">
                      <ExpenseStatusBadge :status="expense.Status" />
                    </td>
                    <td class="align-top text-wrap">
                      <div v-if="expense.UserBankAccountInfo" class="small">
                        <strong>{{ expense.UserBankAccountInfo }}</strong>
                      </div>
                      <div v-else-if="expense.BankAccountNumber" class="small">
                        <div><strong>{{ expense.BankAccountHolderName }}</strong></div>
                        <div class="text-muted">{{ expense.BankAccountNumber }}</div>
                        <div class="text-muted">{{ expense.BankName }}</div>
                      </div>
                      <div v-else class="text-muted small">Chưa có thông tin ngân hàng</div>
                    </td>
                    <td class="align-top">{{ expense.CreatedByUserName || '-' }}</td>
                    <td class="align-top">{{ expense.ApprovedByUserName || '-' }}</td>
                    <td class="align-top">{{ formatDate(expense.CreatedTime) }}</td>
                    <td class="align-top pt-2">
                      <!-- Action Dropdown -->
                      <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">
                        <a @click="viewExpense(expense)" class="dropdown-item" href="javascript:void(0);">
                          <i class="fe fe-eye"></i>
                          <span class="mg-l-6">Xem chi tiết</span>
                        </a>
                        <a @click="fnCreateOrUpdate(expense.Id)" class="dropdown-item" href="javascript:void(0);"
                          v-if="expense.Status === 0">
                          <i class="fe fe-edit-2"></i>
                          <span class="mg-l-6">Chỉnh sửa</span>
                        </a>
                        <a v-if="expense.CanApprove && expense.Status === 0" @click="confirmApprove(expense)"
                          class="dropdown-item" href="javascript:void(0);">
                          <i class="fe fe-check"></i>
                          <span class="mg-l-6">Duyệt</span>
                        </a>
                        <a v-if="expense.CanReject && expense.Status === 0" @click="openRejectModal(expense)"
                          class="dropdown-item" href="javascript:void(0);">
                          <i class="fe fe-x"></i>
                          <span class="mg-l-6">Từ chối</span>
                        </a>
                        <a v-if="expense.Status === 1" @click="openUnapproveModal(expense)" class="dropdown-item"
                          href="javascript:void(0);">
                          <i class="fe fe-x-circle"></i>
                          <span class="mg-l-6">Bỏ duyệt</span>
                        </a>
                        <a @click="openMarkAsPaidModal(expense)" class="dropdown-item" href="javascript:void(0);"
                          v-if="expense.Status === 1 && expense.CanMarkAsPaid">
                          <i class="fe fe-credit-card"></i>
                          <span class="mg-l-6">Đánh dấu đã chuyển tiền</span>
                        </a>
                        <div class="dropdown-divider" v-if="expense.Status === 2 && expense.RejectReason"></div>
                        <a class="dropdown-item disabled" href="javascript:void(0);"
                          v-if="expense.Status === 2 && expense.RejectReason" :title="expense.RejectReason">
                          <i class="fe fe-info"></i>
                          <span class="mg-l-6">Lý do từ chối</span>
                        </a>
                        <a @click="confirmDelete(expense)" class="dropdown-item" href="javascript:void(0);"
                          v-if="expense.Status === 0 && expense.CanDelete">
                          <i class="fe fe-trash"></i>
                          <span class="mg-l-6">Xóa</span>
                        </a>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

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

      </div>
    </div>

    <!-- Create/Edit Modal -->
    <LadaDialog :visible="modalControl.CreateOrUpdate">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title" v-if="selectedId === '0'">Tạo mới</h5>
          <h5 class="modal-title" v-if="selectedId !== '0'">Cập nhật</h5>
          <button @click="closeModal" type="button" class="close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
      </template>
      <template #body>
        <ExpenseForm :id="selectedId" :is-submitting="isSubmitting" @submit="handleSubmit" @cancel="closeModal" />
      </template>
    </LadaDialog>

    <!-- Delete Confirmation Modal -->
    <!-- Approve Modal -->
    <LadaDialog :visible="showApproveModal">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title">Xác nhận duyệt</h5>
          <button type="button" class="btn-close" @click="showApproveModal = false"></button>
        </div>
      </template>

      <template #body>
        <p>Bạn có chắc chắn muốn duyệt chi phí <strong>{{ expenseToApprove?.Description }}</strong>?</p>
      </template>

      <template #footer>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" @click="showApproveModal = false">
            Hủy
          </button>
          <button type="button" class="btn btn-success" @click="handleApprove" :disabled="isSubmitting">
            <span v-if="isSubmitting" class="spinner-border spinner-border-sm me-2"></span>
            Duyệt
          </button>
        </div>
      </template>
    </LadaDialog>

    <!-- Reject Modal -->
    <LadaDialog :visible="showRejectModal">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title">Từ chối chi phí</h5>
          <button type="button" class="btn-close" @click="showRejectModal = false"></button>
        </div>
      </template>

      <template #body>
        <p>Bạn có chắc chắn muốn từ chối chi phí <strong>{{ expenseToReject?.Description }}</strong>?</p>

        <!-- Hiển thị thông tin chi phí -->
        <div class="alert alert-light mb-3">
          <div><strong>Số tiền:</strong> {{ formatCurrency(expenseToReject?.Amount) }}</div>
          <div><strong>Danh mục:</strong> {{ expenseToReject?.ExpenseCategoryName }}</div>
          <div v-if="expenseToReject?.Note"><strong>Ghi chú:</strong> {{ expenseToReject.Note }}</div>
        </div>

        <div class="mb-3">
          <label class="form-label">Lý do từ chối <span class="text-danger">*</span></label>
          <textarea class="form-control" v-model="rejectReason" rows="3" placeholder="Nhập lý do từ chối..."
            required></textarea>
        </div>
      </template>

      <template #footer>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" @click="showRejectModal = false">
            Hủy
          </button>
          <button type="button" class="btn btn-warning" @click="handleReject"
            :disabled="isSubmitting || !rejectReason.trim()">
            <span v-if="isSubmitting" class="spinner-border spinner-border-sm me-2"></span>
            Từ chối
          </button>
        </div>
      </template>
    </LadaDialog>

    <!-- Mark as Paid Modal -->
    <LadaDialog :visible="showMarkAsPaidModal">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title">Đánh dấu đã chuyển tiền</h5>
          <button type="button" class="btn-close" @click="showMarkAsPaidModal = false"></button>
        </div>
      </template>

      <template #body>
        <p>Bạn có chắc chắn muốn đánh dấu chi phí <strong>{{ expenseToMarkAsPaid?.Description }}</strong> đã chuyển
          tiền?</p>

        <!-- Hiển thị thông tin ngân hàng nếu có -->
        <div v-if="expenseToMarkAsPaid?.UserBankAccountInfo || expenseToMarkAsPaid?.BankAccountNumber"
          class="alert alert-info mb-3">
          <h6 class="alert-heading">Thông tin ngân hàng nhận tiền:</h6>
          <div v-if="expenseToMarkAsPaid?.UserBankAccountInfo">
            {{ expenseToMarkAsPaid.UserBankAccountInfo }}
          </div>
          <div v-else-if="expenseToMarkAsPaid?.BankAccountNumber">
            <div><strong>{{ expenseToMarkAsPaid.BankAccountHolderName }}</strong></div>
            <div>Số TK: {{ expenseToMarkAsPaid.BankAccountNumber }}</div>
            <div>Ngân hàng: {{ expenseToMarkAsPaid.BankName }}</div>
            <div v-if="expenseToMarkAsPaid.BankBranchName">Chi nhánh: {{ expenseToMarkAsPaid.BankBranchName }}</div>
          </div>
        </div>

        <div class="mb-3">
          <label class="form-label">Ghi chú</label>
          <textarea class="form-control" v-model="markAsPaidNote" rows="3"
            placeholder="Nhập ghi chú về giao dịch chuyển tiền..."></textarea>
        </div>
      </template>

      <template #footer>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" @click="showMarkAsPaidModal = false">
            Hủy
          </button>
          <button type="button" class="btn btn-info" @click="handleMarkAsPaid" :disabled="isSubmitting">
            <span v-if="isSubmitting" class="spinner-border spinner-border-sm me-2"></span>
            Đánh dấu
          </button>
        </div>
      </template>
    </LadaDialog>

    <!-- Unapprove Modal -->
    <LadaDialog :visible="showUnapproveModal">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title">Bỏ duyệt chi phí</h5>
          <button type="button" class="btn-close" @click="showUnapproveModal = false"></button>
        </div>
      </template>

      <template #body>
        <div class="alert alert-warning">
          <i class="fe fe-alert-triangle me-2"></i>
          <strong>Lưu ý:</strong> Chi phí sẽ quay về trạng thái "Chờ duyệt" sau khi bỏ duyệt.
        </div>
        <p>Bạn có chắc chắn muốn bỏ duyệt chi phí <strong>{{ expenseToUnapprove?.Description }}</strong>?</p>
        <div class="mb-3">
          <label class="form-label">Lý do bỏ duyệt</label>
          <textarea class="form-control" v-model="unapproveReason" rows="3"
            placeholder="Nhập lý do bỏ duyệt..."></textarea>
          <small class="text-muted">Lý do sẽ được lưu vào lịch sử thay đổi</small>
        </div>
      </template>

      <template #footer>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" @click="showUnapproveModal = false">
            Hủy
          </button>
          <button type="button" class="btn btn-warning" @click="handleUnapprove" :disabled="isSubmitting">
            <span v-if="isSubmitting" class="spinner-border spinner-border-sm me-2"></span>
            <i v-else class="fe fe-x-circle me-2"></i>
            Xác nhận bỏ duyệt
          </button>
        </div>
      </template>
    </LadaDialog>

    <!-- Delete Modal -->
    <LadaDialog :visible="showDeleteModal">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title">Xác nhận xóa</h5>
          <button type="button" class="btn-close" @click="closeDeleteModal"></button>
        </div>
      </template>

      <template #body>
        <p>Bạn có chắc chắn muốn xóa chi phí <strong>{{ expenseToDelete?.Description }}</strong>?</p>
        <p class="text-muted">Hành động này không thể hoàn tác.</p>
      </template>

      <template #footer>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" @click="closeDeleteModal">
            Hủy
          </button>
          <button type="button" class="btn btn-danger" @click="handleDelete" :disabled="isDeleting">
            <span v-if="isDeleting" class="spinner-border spinner-border-sm me-2"></span>
            Xóa
          </button>
        </div>
      </template>
    </LadaDialog>

    <!-- Expense Detail Modal -->
    <ExpenseDetailModal :visible="showDetailModal" :expenseId="selectedExpenseId" @close="closeDetailModal"
      @updated="loadData" />
  </div>
</template>

<script setup>
//#region Imports
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useToast } from 'vue-toastification'
import expenseService from '@/services/expenseService'
import expenseCategoryService from '@/services/expenseCategoryService'
//#endregion

//#region Components
import DatepickerInstance from "@vuepic/vue-datepicker";
import { LadaDialog, DateRangeSidebar } from '@/components/index';
import { ExpenseForm, ExpenseStatusBadge, ExpenseDetailModal } from './components';
import vSelect from 'vue-select';
//#endregion

//#region Router & Toast
const router = useRouter()
const toast = useToast();
//#endregion

//#region Data
const loading = ref(false)
const expenses = reactive([])
const searchModel = reactive(expenseService.createDefaultSearchModel())
const ctrlPager = ref()
const date = ref()
const createDatePicker = ref(DatepickerInstance)

//#region Modals
const modalControl = reactive({
  CreateOrUpdate: false
});

const selectedId = ref('0');
const showDeleteModal = ref(false)
const showApproveModal = ref(false)
const showRejectModal = ref(false)
const showMarkAsPaidModal = ref(false)
const showDetailModal = ref(false)
const selectedExpenseId = ref(null)
const isSubmitting = ref(false)
const isDeleting = ref(false)
const expenseToDelete = ref(null)
const expenseToApprove = ref(null)
const expenseToReject = ref(null)
const expenseToMarkAsPaid = ref(null)
const rejectReason = ref('')
const markAsPaidNote = ref('')
const showUnapproveModal = ref(false)
const expenseToUnapprove = ref(null)
const unapproveReason = ref('')
//#endregion

//#region Select Options
const statuses = reactive([
  { Id: 0, Name: 'Chờ duyệt' },
  { Id: 1, Name: 'Đã duyệt' },
  { Id: 2, Name: 'Đã từ chối' },
  { Id: 3, Name: 'Đã chuyển tiền' }
]);

const expenseCategories = reactive([]);
//#endregion

//#region Utility Functions
const formatCurrency = (amount) => {
  if (!amount) return '0 VND'
  return new Intl.NumberFormat('vi-VN', {
    style: 'currency',
    currency: 'VND'
  }).format(amount)
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  try {
    return new Date(dateString).toLocaleDateString('vi-VN')
  } catch {
    return '-'
  }
}

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

//#region SEARCH
async function search() {
  searchModel.Pagination.PageIndex = 1;
  ctrlPager.value.Refresh();
  loadData();
}

async function loadData() {
  loading.value = true;
  expenses.splice(0, expenses.length);
  var searchResult = await expenseService.search(searchModel);
  if (searchResult.Items != null && searchResult.Items.length > 0) {
    searchResult.Items.forEach(expense => {
      expenses.push(expense);
    });
  }
  searchModel.Pagination.Total = searchResult.TotalCount || searchResult.TotalRecord || 0;
  loading.value = false;
}

function PageSizeChanged(pagesize) {
  searchModel.Pagination.PageSize = pagesize;
  searchModel.Pagination.PageIndex = 1;
  loadData();
}

function PageIndexChanged(pageIndex) {
  searchModel.Pagination.PageIndex = pageIndex;
  loadData();
}
//#endregion

//#region Actions
async function fnCreateOrUpdate(id) {
  selectedId.value = id;
  modalControl.CreateOrUpdate = true;
}

function closeModal() {
  modalControl.CreateOrUpdate = false;
  selectedId.value = '0';
  loadData(); // Reload data after modal close
}
//#endregion

const viewExpense = (expense) => {
  selectedExpenseId.value = expense.Id
  showDetailModal.value = true
}

const closeDetailModal = () => {
  showDetailModal.value = false
  selectedExpenseId.value = null
}



const handleSubmit = async (data) => {
  try {
    isSubmitting.value = true
    const result = await expenseService.createOrUpdate(data)

    if (result.Result === 1) {
      toast.success(result.Message || (selectedId.value !== '0' ? 'Cập nhật thành công' : 'Tạo mới thành công'))
      closeModal()
    } else {
      toast.error(result.Message || 'Có lỗi xảy ra')
    }
  } catch (error) {
    console.error('Error submitting form:', error)
    toast.error('Có lỗi xảy ra khi lưu dữ liệu')
  } finally {
    isSubmitting.value = false
  }
}

const confirmApprove = (expense) => {
  expenseToApprove.value = expense
  showApproveModal.value = true
}

const openRejectModal = (expense) => {
  expenseToReject.value = expense
  showRejectModal.value = true
}

const openMarkAsPaidModal = (expense) => {
  expenseToMarkAsPaid.value = expense
  showMarkAsPaidModal.value = true
}

const openUnapproveModal = (expense) => {
  expenseToUnapprove.value = expense
  unapproveReason.value = ''
  showUnapproveModal.value = true
}

const confirmDelete = (expense) => {
  expenseToDelete.value = expense
  showDeleteModal.value = true
}

const closeDeleteModal = () => {
  showDeleteModal.value = false
  expenseToDelete.value = null
}

const handleApprove = async () => {
  try {
    isSubmitting.value = true
    const result = await expenseService.approve(expenseToApprove.value.Id)

    if (result.Result === 1) {
      toast.success(result.Message || 'Duyệt thành công')
      showApproveModal.value = false
      expenseToApprove.value = null
      loadData()
    } else {
      toast.error(result.Message || 'Có lỗi xảy ra khi duyệt')
    }
  } catch (error) {
    console.error('Error approving expense:', error)
    toast.error('Có lỗi xảy ra khi duyệt chi phí')
  } finally {
    isSubmitting.value = false
  }
}

const handleReject = async () => {
  try {
    isSubmitting.value = true
    const result = await expenseService.reject(expenseToReject.value.Id, rejectReason.value)

    if (result.Result === 1) {
      toast.success(result.Message || 'Từ chối thành công')
      showRejectModal.value = false
      expenseToReject.value = null
      rejectReason.value = ''
      loadData()
    } else {
      toast.error(result.Message || 'Có lỗi xảy ra khi từ chối')
    }
  } catch (error) {
    console.error('Error rejecting expense:', error)
    toast.error('Có lỗi xảy ra khi từ chối chi phí')
  } finally {
    isSubmitting.value = false
  }
}

const handleMarkAsPaid = async () => {
  try {
    isSubmitting.value = true
    const result = await expenseService.markAsPaid(expenseToMarkAsPaid.value.Id, markAsPaidNote.value)

    if (result.Result === 1) {
      toast.success(result.Message || 'Đánh dấu đã chuyển tiền thành công')
      showMarkAsPaidModal.value = false
      expenseToMarkAsPaid.value = null
      markAsPaidNote.value = ''
      loadData()
    } else {
      toast.error(result.Message || 'Có lỗi xảy ra khi đánh dấu')
    }
  } catch (error) {
    console.error('Error marking expense as paid:', error)
    toast.error('Có lỗi xảy ra khi đánh dấu chi phí đã chuyển tiền')
  } finally {
    isSubmitting.value = false
  }
}


const handleUnapprove = async () => {
  try {
    isSubmitting.value = true

    const result = await expenseService.unapprove(
      expenseToUnapprove.value.Id,
      unapproveReason.value.trim() || 'Bỏ duyệt'
    )

    if (result.Result === 1) {
      toast.success(result.Message || 'Bỏ duyệt chi phí thành công')
      showUnapproveModal.value = false
      expenseToUnapprove.value = null
      unapproveReason.value = ''
      loadData()
    } else {
      toast.error(result.Message || 'Có lỗi xảy ra khi bỏ duyệt')
    }
  } catch (error) {
    console.error('Error unapproving expense:', error)
    toast.error('Có lỗi xảy ra khi bỏ duyệt chi phí')
  } finally {
    isSubmitting.value = false
  }
}

const handleDelete = async () => {
  try {
    isDeleting.value = true
    const result = await expenseService.delete(expenseToDelete.value.Id)

    if (result.Result === 1) {
      toast.success(result.Message || 'Xóa thành công')
      closeDeleteModal()
      loadData()
    } else {
      toast.error(result.Message || 'Có lỗi xảy ra khi xóa')
    }
  } catch (error) {
    console.error('Error deleting expense:', error)
    toast.error('Có lỗi xảy ra khi xóa chi phí')
  } finally {
    isDeleting.value = false
  }
}

//#region Expense Categories
// Flatten hierarchical data to flat array
const flattenCategories = (categories, level = 0) => {
  const result = []
  categories.forEach(category => {
    // Thêm category hiện tại với level
    result.push({
      ...category,
      Level: level
    })

    // Nếu có children, flatten chúng với level + 1
    if (category.Children && category.Children.length > 0) {
      const childrenFlattened = flattenCategories(category.Children, level + 1)
      result.push(...childrenFlattened)
    }
  })
  return result
}

async function getExpenseCategories() {
  expenseCategories.splice(0, expenseCategories.length);
  try {
    const hierarchyResult = await expenseCategoryService.getHierarchy();
    if (hierarchyResult && hierarchyResult.length > 0) {
      // Flatten toàn bộ cây phân cấp thành mảng phẳng
      const flattenedCategories = flattenCategories(hierarchyResult);
      flattenedCategories.forEach(category => {
        expenseCategories.push(category);
      });
    }
  } catch (error) {
    console.error('Error loading expense categories:', error);
  }
}
//#endregion

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

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

.btn-sm {
  padding: 0.25rem 0.5rem;
  font-size: 0.875rem;
}

.text-primary {
  color: #0d6efd !important;
}
</style>
