<template>
  <div>
    <div class="breadcrumb-header justify-content-between">
      <div class="my-auto">
        <h4 class="page-title">Quản lý ngân hàng</h4>
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="javascript:void(0);">Trang chủ</a></li>
          <li class="breadcrumb-item active" aria-current="page">Quản lý ngân hàng</li>
        </ol>
      </div>
    </div>

    <div class="row row-sm">
      <!-- Search Form -->
      <div class="col-sm-12 col-md-12 col-lg-12 col-xl-12 grid-margin">
        <div class="card card-search shadow-none">
          <form class="card-body" @submit.prevent="search">
            <div class="row">
              <div class="col-lg-6 col-md-8 mb-3">
                <label>Từ khóa</label>
                <input type="text" v-model="searchModel.Search.PredicateObject.Keyword" class="form-control"
                  placeholder="Tên ngân hàng, tên thương hiệu...">
              </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>

      <!-- Data Table -->
      <div class="col-sm-12 col-md-12 col-lg-12 col-xl-12 grid-margin">
        <div class="card">
          <div class="card-header pb-0">
            <div class="d-flex justify-content-between">
              <h4 class="card-title mg-b-0">Danh sách ngân hàng</h4>
              <div>
                <button class="btn btn-success btn-sm me-2" @click="openCreateModal" v-if="canCreate">
                  <i class="fa fa-plus"></i> Thêm mới
                </button>
                <button class="btn btn-info btn-sm" @click="initializeBankData" v-if="canCreate">
                  <i class="fa fa-database"></i> Khởi tạo dữ liệu mẫu
                </button>
              </div>
            </div>
          </div>
          <div class="card-body">
            <div class="table-responsive">
              <table class="table table-striped table-hover">
                <thead>
                  <tr>
                    <th>ID</th>
                    <th>Mã</th>
                    <th>Tên đầy đủ</th>
                    <th>Tên thương hiệu</th>
                    <th>Thứ tự</th>
                    <th>Thao tác</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-if="loading">
                    <td colspan="5" class="text-center">
                      <div class="spinner-border" role="status">
                        <span class="visually-hidden">Loading...</span>
                      </div>
                    </td>
                  </tr>
                  <tr v-else-if="banks.length === 0">
                    <td colspan="5" class="text-center">Không có dữ liệu</td>
                  </tr>
                  <tr v-else v-for="bank in banks" :key="bank.Id">
                    <td>{{ bank.Id }}</td>
                    <td>{{ bank.BankCode }}</td>
                    <td>{{ bank.FullName }}</td>
                    <td>{{ bank.BrandName }}</td>
                    <td>{{ bank.DisplayOrder || '-' }}</td>
                    <td>
                      <div class="btn-group btn-group-sm">
                        <button class="btn btn-outline-info" @click="viewDetail(bank)" title="Xem chi tiết">
                          <i class="fa fa-eye"></i>
                        </button>
                        <button class="btn btn-outline-primary" @click="editBank(bank)" v-if="canEdit"
                          title="Chỉnh sửa">
                          <i class="fa fa-edit"></i>
                        </button>
                        <button class="btn btn-outline-danger" @click="deleteBank(bank)" v-if="canDelete" title="Xóa">
                          <i class="fa fa-trash"></i>
                        </button>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

            <pager ref="ctrlPager" v-show="!loading && banks.length > 0" @PageSizeChanged="PageSizeChanged"
              @PageIndexChanged="PageIndexChanged" :Total="searchModel.Pagination.Total" :TotalCurrent="banks.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 ngân hàng</h5>
          <h5 class="modal-title" v-if="selectedId > 0">Cập nhật ngân hàng</h5>
          <button @click="closeModal" type="button" class="close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
      </template>
      <template #body>
        <CreateOrUpdateBank @cancel="closeModal" :id="selectedId"></CreateOrUpdateBank>
      </template>
    </LadaDialog>

    <!-- Detail Modal -->
    <LadaDialog :visible="modalControl.Detail">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title">Chi tiết ngân hàng</h5>
          <button @click="closeDetailModal" type="button" class="close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
      </template>
      <template #body>
        <BankDetail @cancel="closeDetailModal" :bank="selectedBank"></BankDetail>
      </template>
    </LadaDialog>
  </div>
</template>

<script setup>
//#region Imports
import { ref, reactive, onMounted } from 'vue';
import bankService from '@/services/bankService';
// Removed unused imports
import { useToast } from "vue-toastification";

const toast = useToast();
//#endregion

//#region Components
import { LadaDialog } from '@/components/index';
import CreateOrUpdateBank from './components/CreateOrUpdateBank.vue';
import BankDetail from './components/BankDetail.vue';
//#endregion

//#region Reactive Data
// Search Model
const searchModel = reactive({
  Pagination: {
    Total: 0,
    PageIndex: 1,
    PageSize: 10
  },
  Sort: {
    Predicate: '',
    Reverse: true
  },
  Search: {
    PredicateObject: {
      Keyword: ''
    }
  }
});

// Data
const banks = reactive([]);
const loading = ref(false);

// Constants (removed unused constants)

// Permissions (should be loaded from user permissions)
const canCreate = ref(true);
const canEdit = ref(true);
const canDelete = ref(true);

// Pager reference
const ctrlPager = ref();
//#endregion

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

const selectedId = ref(0);
const selectedBank = ref(null);

function closeModal() {
  modalControl.CreateOrUpdate = false;
  selectedId.value = 0;
  selectedBank.value = null;
  loadData();
}

function closeDetailModal() {
  modalControl.Detail = false;
  selectedBank.value = null;
}
//#endregion
//#region API Methods
async function loadData() {
  loading.value = true;
  banks.splice(0, banks.length);
  try {
    const searchResult = await bankService.search(searchModel);
    if (searchResult.Items != null && searchResult.Items.length > 0) {
      searchResult.Items.forEach(bank => {
        banks.push(bank);
      });
    }
    searchModel.Pagination.Total = searchResult.TotalRecord;
  } catch (error) {
    console.error('Error loading banks:', error);
    toast.error('Có lỗi xảy ra khi tải danh sách ngân hàng');
  } finally {
    loading.value = false;
  }
}
//#endregion

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

//#region Pagination Methods
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 openCreateModal() {
  fnCreateOrUpdate(0);
}

function viewDetail(bank) {
  selectedBank.value = bank;
  modalControl.Detail = true;
}

function editBank(bank) {
  selectedBank.value = { ...bank };
  fnCreateOrUpdate(bank.Id);
}
//#endregion

//#region CRUD Methods
async function deleteBank(bank) {
  if (!confirm(`Bạn có chắc chắn muốn xóa ngân hàng "${bank.FullName}"?`)) {
    return;
  }

  try {
    const result = await bankService.delete(bank.Id);
    if (result.Result === 1) {
      toast.success('Xóa ngân hàng thành công');
      loadData();
    } else {
      toast.error(result.Message || 'Có lỗi xảy ra khi xóa ngân hàng');
    }
  } catch (error) {
    console.error('Error deleting bank:', error);
    toast.error('Có lỗi xảy ra khi xóa ngân hàng');
  }
}

async function initializeBankData() {
  if (!confirm('Bạn có chắc chắn muốn khởi tạo dữ liệu mẫu ngân hàng?')) {
    return;
  }

  try {
    const result = await bankService.initializeBankData();
    if (result.Result === 1) {
      toast.success('Khởi tạo dữ liệu ngân hàng thành công');
      loadData();
    } else {
      toast.error(result.Message || 'Có lỗi xảy ra khi khởi tạo dữ liệu');
    }
  } catch (error) {
    console.error('Error initializing bank data:', error);
    toast.error('Có lỗi xảy ra khi khởi tạo dữ liệu');
  }
}

//#endregion

//#region Utility Methods
// Removed unused utility methods
//#endregion

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

<style scoped>
.card-search {
  border: 1px solid #e9ecef;
  margin-bottom: 1rem;
}

.table th {
  background-color: #f8f9fa;
  font-weight: 600;
}

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

.pagination-sm .page-link {
  padding: 0.25rem 0.5rem;
  font-size: 0.875rem;
}

.badge {
  font-size: 0.75rem;
}
</style>
