<template>
  <div class="user-bank-accounts">
    <!-- Header với nút thêm tài khoản -->
    <div class="d-flex justify-content-between align-items-center mb-3">
      <h6 class="mb-0">Tài khoản ngân hàng</h6>
      <button 
        @click="openCreateModal" 
        type="button" 
        class="btn btn-outline-primary btn-sm"
        :disabled="loading"
      >
        <i class="fe fe-plus me-1"></i>
        Thêm tài khoản
      </button>
    </div>

    <!-- Loading State -->
    <div v-if="loading" class="text-center py-3">
      <span class="spinner-border spinner-border-sm me-2"></span>
      Đang tải...
    </div>

    <!-- Empty State -->
    <div v-else-if="bankAccounts.length === 0" class="text-center py-4 text-muted">
      <i class="fe fe-credit-card fs-1 mb-2"></i>
      <p class="mb-0">Chưa có tài khoản ngân hàng nào</p>
    </div>

    <!-- Bank Accounts List -->
    <div v-else class="bank-accounts-list">
      <div 
        v-for="account in bankAccounts" 
        :key="account.Id"
        class="card mb-2"
        :class="{ 'border-primary': account.IsDefault }"
      >
        <div class="card-body p-3">
          <div class="row align-items-center">
            <div class="col">
              <div class="d-flex align-items-center mb-1">
                <h6 class="mb-0 me-2">{{ account.BankName }}</h6>
                <span v-if="account.IsDefault" class="badge bg-primary">Mặc định</span>
              </div>
              <div class="text-muted small mb-1">
                <strong>STK:</strong> {{ account.AccountNumber }}
              </div>
              <div class="text-muted small mb-1">
                <strong>Chủ TK:</strong> {{ account.AccountHolderName }}
              </div>
              <div v-if="account.Note" class="text-muted small">
                <strong>Ghi chú:</strong> {{ account.Note }}
              </div>
            </div>
            <div class="col-auto">
              <div class="dropdown">
                <button 
                  type="button" 
                  class="btn btn-light btn-sm dropdown-toggle"
                  data-bs-toggle="dropdown"
                  aria-expanded="false"
                >
                  <i class="fe fe-more-vertical"></i>
                </button>
                <ul class="dropdown-menu">
                  <li>
                    <a 
                      @click="openEditModal(account)" 
                      class="dropdown-item" 
                      href="javascript:void(0);"
                    >
                      <i class="fe fe-edit-2 me-2"></i>
                      Chỉnh sửa
                    </a>
                  </li>
                  <li>
                    <a 
                      @click="setAsDefault(account.Id)" 
                      class="dropdown-item"
                      href="javascript:void(0);"
                      v-if="!account.IsDefault"
                    >
                      <i class="fe fe-star me-2"></i>
                      Đặt làm mặc định
                    </a>
                  </li>
                  <li><hr class="dropdown-divider"></li>
                  <li>
                    <a 
                      @click="deleteAccount(account.Id)" 
                      class="dropdown-item text-danger"
                      href="javascript:void(0);"
                    >
                      <i class="fe fe-trash-2 me-2"></i>
                      Xóa
                    </a>
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Modal Create/Update -->
    <LadaDialog :visible="modalControl.createOrUpdate">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title">
            {{ selectedAccount.Id ? 'Cập nhật tài khoản ngân hàng' : 'Thêm tài khoản ngân hàng' }}
          </h5>
          <button @click="closeModal" type="button" class="close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
      </template>
      <template #body>
        <BankAccountForm 
          :account="selectedAccount"
          :user-id="userId"
          @save="saveAccount"
          @cancel="closeModal"
        />
      </template>
    </LadaDialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import userBankAccountService from '@/services/userBankAccountService'
import bankService from '@/services/bankService'
import { LadaDialog } from '@/components/index'
import BankAccountForm from './BankAccountForm.vue'
import { useToast } from "vue-toastification"

const toast = useToast()

// Props
const props = defineProps({
  userId: {
    type: Number,
    required: true
  }
})

// Reactive data
const bankAccounts = reactive([])
const bankInfoMap = reactive({}) // Map BankId to Bank info
const loading = ref(false)
const formLoading = ref(false)

// Modal control
const modalControl = reactive({
  createOrUpdate: false
})

const selectedAccount = reactive({
  Id: 0,
  AccountNumber: '',
  AccountHolderName: '',
  BankCode: '',
  BankName: '',
  IsDefault: false,
  Note: ''
})

// Methods
const loadBankAccounts = async () => {
  if (!props.userId) return
  
  try {
    loading.value = true
    const searchModel = {
      Pagination: {
        PageIndex: 1,
        PageSize: 100
      },
      Sort: {
        Predicate: '',
        Reverse: true
    },
      Search: {
        PredicateObject: {
          UserId: props.userId
        }
      }
    }
    
    const result = await userBankAccountService.search(searchModel)
    
    // Clear existing data
    bankAccounts.splice(0, bankAccounts.length)
    
    if (result.Items && result.Items.length > 0) {
      result.Items.forEach(account => {
        bankAccounts.push(account)
      })
      // Load bank info for all accounts
      //await loadBankInfoForAccounts(result.Data)
    }
  } catch (error) {
    console.error('Error loading bank accounts:', error)
    toast.error('Không thể tải danh sách tài khoản ngân hàng: ' + error.message)
  } finally {
    loading.value = false
  }
}


const getBankName = (bankId) => {
  if (!bankId || !bankInfoMap[bankId]) {
    return `Ngân hàng ID: ${bankId}`
  }
  return bankInfoMap[bankId].BrandName || bankInfoMap[bankId].FullName || `Ngân hàng ID: ${bankId}`
}

const openCreateModal = () => {
  // Reset form
  Object.assign(selectedAccount, {
    Id: 0,
    AccountNumber: '',
    AccountHolderName: '',
    BankId: 0,
    IsDefault: bankAccounts.length === 0, // Tự động đặt làm mặc định nếu là tài khoản đầu tiên
    Note: ''
  })
  
  modalControl.createOrUpdate = true
}

const openEditModal = (account) => {
  Object.assign(selectedAccount, account)
  modalControl.createOrUpdate = true
}

const closeModal = () => {
  modalControl.createOrUpdate = false
}

const saveAccount = async (accountData) => {
  try {
    formLoading.value = true
    
    // accountData already contains UserId from the form
    const result = await userBankAccountService.createOrUpdate(accountData)
    
    if (result.Result === 1) {
      toast.success(result.Message || 'Lưu tài khoản ngân hàng thành công')
      closeModal()
      await loadBankAccounts()
    } else {
      toast.error(result.Message || 'Có lỗi xảy ra khi lưu tài khoản ngân hàng')
    }
  } catch (error) {
    console.error('Error saving bank account:', error)
    toast.error('Lỗi: ' + error.message)
  } finally {
    formLoading.value = false
  }
}

const setAsDefault = async (accountId) => {
  try {
    const account = bankAccounts.find(acc => acc.Id === accountId)
    if (!account) return
    
    const result = await userBankAccountService.createOrUpdate({
      ...account,
      IsDefault: true
    })
    
    if (result.Result === 1) {
      toast.success('Đã đặt làm tài khoản mặc định')
      await loadBankAccounts()
    } else {
      toast.error('Không thể đặt làm tài khoản mặc định')
    }
  } catch (error) {
    console.error('Error setting default account:', error)
    toast.error('Lỗi: ' + error.message)
  }
}

const deleteAccount = async (accountId) => {
  const confirm = window.confirm('Bạn có chắc chắn muốn xóa tài khoản ngân hàng này?')
  if (!confirm) return
  
  try {
    const result = await userBankAccountService.delete(accountId)
    
    if (result.Result === 1) {
      toast.success('Xóa tài khoản ngân hàng thành công')
      await loadBankAccounts()
    } else {
      toast.error(result.Message || 'Không thể xóa tài khoản ngân hàng')
    }
  } catch (error) {
    console.error('Error deleting bank account:', error)
    toast.error('Lỗi: ' + error.message)
  }
}

// Watch userId changes
watch(() => props.userId, (newUserId) => {
  if (newUserId) {
    loadBankAccounts()
  }
})

// Load data on mount
onMounted(() => {
  if (props.userId) {
    loadBankAccounts()
  }
})
</script>

<style scoped>
.user-bank-accounts {
  border: 1px solid #e9ecef;
  border-radius: 0.375rem;
  padding: 1rem;
  background-color: #f8f9fa;
}

.bank-accounts-list .card {
  border: 1px solid #dee2e6;
  transition: all 0.15s ease-in-out;
}

.bank-accounts-list .card:hover {
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.bank-accounts-list .card.border-primary {
  border-color: #0d6efd !important;
  background-color: rgba(13, 110, 253, 0.05);
}
</style>
