<template>
  <div>
    <!-- Header -->
    <div class="breadcrumb-header justify-content-between">
      <div class="my-auto">
        <h4 class="page-title">Quản lý tài khoản 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"><a href="javascript:void(0);">Tài chính</a></li>
          <li class="breadcrumb-item active" aria-current="page">Quản lý tài khoản ngân hàng</li>
        </ol>
      </div>
      <div class="d-flex gap-2">
        <router-link
          :to="{ name: 'bank-account-import-statement' }"
          class="btn btn-info btn-sm"
        >
          <i class="fas fa-file-import me-1"></i>
          Import sao kê
        </router-link>
        <router-link
          :to="{ name: 'bank-account-create' }"
          class="btn btn-primary btn-sm"
        >
          <i class="fas fa-plus me-1"></i>
          Tạo tài khoản
        </router-link>
      </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-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ên tài khoản, số tài khoản, tên ngân hàng..."
            >
          </div>
          <div class="col-lg-3 col-md-4 mb-3">
            <label>Ngân hàng</label>
            <v-select
              v-model="searchModel.Search.PredicateObject.BankCode"
              :options="bankOptions"
              :reduce="option => option.Id"
              label="Name"
              placeholder="Chọn ngân hàng..."
              :clearable="true"
            />
          </div>
          <div class="col-lg-3 col-md-4 mb-3">
            <label>Trạng thái</label>
            <v-select
              v-model="searchModel.Search.PredicateObject.Status"
              :options="statusOptions"
              :reduce="option => option.Id"
              label="Name"
              placeholder="Chọn trạng thái..."
              :clearable="true"
            />
          </div>
          <div class="col-lg-3 col-md-4 mb-3">
            <label>&nbsp;</label>
            <div class="d-flex gap-2">
              <button type="submit" class="btn btn-primary btn-sm">
                <i class="fas fa-search me-1"></i>
                Tìm kiếm
              </button>
              <button type="button" @click="resetSearch" class="btn btn-secondary btn-sm">
                <i class="fas fa-redo me-1"></i>
                Làm mới
              </button>
            </div>
          </div>
        </div>
      </form>
    </div>
  </div>

  <!-- Results -->
  <div class="col-sm-12 col-md-12 col-lg-12 col-xl-12 grid-margin">
    <div class="card">
      <div class="card-body">
        <!-- Loading -->
        <div v-if="loading" class="text-center py-4">
          <div class="spinner-border text-primary" role="status">
            <span class="visually-hidden">Đang tải...</span>
          </div>
        </div>

        <!-- Data Table -->
        <div v-else-if="searchResult.Items && searchResult.Items.length > 0">
          <div class="table-responsive">
            <table class="table table-striped">
              <thead>
                <tr>
                  <th>Tên tài khoản</th>
                  <th>Số tài khoản</th>
                  <th>Ngân hàng</th>
                  <th>Số dư hiện tại</th>
                  <th>Trạng thái</th>
                  <th>Người quản lý</th>
                  <th>Giao dịch gần nhất</th>
                  <th class="text-center">Thao tác</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="item in searchResult.Items" :key="item.Id">
                  <td>
                    <div class="fw-bold">{{ item.AccountName }}</div>
                    <small class="text-muted">{{ item.BranchName }}</small>
                  </td>
                  <td>
                    <code>{{ item.AccountNumber }}</code>
                  </td>
                  <td>
                    <div>{{ item.BankName }}</div>
                    <small class="text-muted">{{ item.BankCode }}</small>
                  </td>
                  <td>
                    <div class="fw-bold text-success">
                      {{ formatCurrency(item.CurrentBalance) }}đ
                    </div>
                    <small class="text-muted">
                      {{ item.LastBalanceUpdate ? formatDate(item.LastBalanceUpdate) : 'Chưa cập nhật' }}
                    </small>
                  </td>
                  <td>
                    <span :class="`badge bg-${getStatusColor(item.Status)}`">
                      {{ item.Status }}
                    </span>
                  </td>
                  <td>
                    <div>{{ item.ManagerFullName }}</div>
                    <small class="text-muted">@{{ item.ManagerUserName }}</small>
                  </td>
                  <td>
                    <div v-if="item.LastTransactionDate">
                      {{ formatDate(item.LastTransactionDate) }}
                    </div>
                    <div class="text-muted">
                      {{ item.TransactionCount }} giao dịch
                    </div>
                  </td>
                  <td class="text-center">
                    <div class="btn-group btn-group-sm">
                      <router-link 
                        :to="{ name: 'bank-account-detail', params: { id: item.Id } }"
                        class="btn btn-outline-primary"
                        title="Xem chi tiết"
                      >
                        <i class="fas fa-eye"></i>
                      </router-link>
                      <router-link 
                        :to="{ name: 'bank-account-edit', params: { id: item.Id } }"
                        class="btn btn-outline-warning"
                        title="Chỉnh sửa"
                      >
                        <i class="fas fa-edit"></i>
                      </router-link>
                      <button 
                        @click="confirmDelete(item)"
                        class="btn btn-outline-danger"
                        title="Xóa"
                      >
                        <i class="fas fa-trash"></i>
                      </button>
                    </div>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          <!-- Pagination -->
          <pager 
            v-if="searchResult.NumberOfPages > 1"
            :numberOfPages="searchResult.NumberOfPages"
            :currentPage="searchModel.Pagination.PageIndex"
            @pageChanged="onPageChanged"
          />
        </div>

        <!-- Empty State -->
        <empty v-else message="Không tìm thấy tài khoản ngân hàng nào" />
      </div>
    </div>

    <!-- Delete Confirmation Dialog -->
    <LadaDialog :visible="showDeleteDialog">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title">Xác nhận xóa</h5>
          <button @click="showDeleteDialog = false" type="button" class="close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
      </template>
      <template #body>
        <div class="modal-body">
          <p>Bạn có chắc chắn muốn xóa tài khoản ngân hàng <strong>{{ selectedAccount?.AccountName }}</strong>?</p>
          <p class="text-danger">
            <i class="fas fa-exclamation-triangle me-1"></i>
            Hành động này không thể hoàn tác!
          </p>
        </div>
      </template>
      <template #footer>
        <div class="modal-footer">
          <button @click="showDeleteDialog = false" type="button" class="btn btn-secondary">
            Hủy
          </button>
          <button @click="deleteAccount" type="button" class="btn btn-danger">
            <i class="fas fa-trash me-1"></i>
            Xóa
          </button>
        </div>
      </template>
    </LadaDialog>
    </div>
  </div>
</div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useToast } from "vue-toastification";
import bankAccountService from '@/services/bankAccountService';
import { BankList, BankAccountStatusList, BankAccountUtils } from '@/infrastructure/constants/bankAccountConstants';

// Composables
const toast = useToast();

// Reactive data
const loading = ref(false);
const showDeleteDialog = ref(false);
const selectedAccount = ref(null);

const searchModel = reactive({
  Pagination: {
    PageIndex: 1,
    PageSize: 20,
    From: 0,
    Total: 0,
    TotalPages: 0,
    Start: 0
  },
  Search: {
    PredicateObject: {
      Keyword: '',
      BankCode: null,
      Status: null,
      ManagerUserId: null,
      CreatedFrom: null,
      CreatedTo: null
    }
  },
  Sort: {
    Predicate: 'CreatedTime',
    Reverse: true
  },
  IsExport: false
});

const searchResult = reactive({
  Items: [],
  TotalRecord: 0,
  NumberOfPages: 0,
  From: 0,
  To: 0,
  LastPage: 0
});

// Options for select components
const bankOptions = BankList;
const statusOptions = BankAccountStatusList;

// Methods
const search = async () => {
  loading.value = true;
  try {
    const result = await bankAccountService.search(searchModel);
    Object.assign(searchResult, result);
  } catch (error) {
    toast.error('Có lỗi xảy ra khi tìm kiếm tài khoản ngân hàng');
  } finally {
    loading.value = false;
  }
};

const resetSearch = () => {
  searchModel.Search.PredicateObject = {
    Keyword: '',
    BankCode: null,
    Status: null,
    ManagerUserId: null,
    CreatedFrom: null,
    CreatedTo: null
  };
  searchModel.Pagination.PageIndex = 1;
  search();
};

const onPageChanged = (page) => {
  searchModel.Pagination.PageIndex = page;
  search();
};

const confirmDelete = (account) => {
  selectedAccount.value = account;
  showDeleteDialog.value = true;
};

const deleteAccount = async () => {
  if (!selectedAccount.value) return;
  
  try {
    const result = await bankAccountService.delete(selectedAccount.value.Id);
    if (result.Result === 1) {
      toast.success(result.Message || 'Xóa tài khoản ngân hàng thành công');
      showDeleteDialog.value = false;
      search(); // Refresh data
    } else {
      toast.error(result.Message || 'Có lỗi xảy ra khi xóa tài khoản ngân hàng');
    }
  } catch (error) {
    toast.error('Có lỗi xảy ra khi xóa tài khoản ngân hàng');
  }
};

// Utility functions
const formatCurrency = BankAccountUtils.formatCurrency;
const getStatusColor = BankAccountUtils.getStatusColor;

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

// Lifecycle
onMounted(() => {
  search();
});
</script>

<style scoped>
.card-search {
  border: 1px solid #e9ecef;
  background-color: #f8f9fa;
}

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

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

code {
  background-color: #f8f9fa;
  color: #495057;
  padding: 0.125rem 0.25rem;
  border-radius: 0.25rem;
}
</style>
