<template>
  <div>
    <!-- 1. Breadcrumb Header -->
    <div class="breadcrumb-header justify-content-between">
      <div class="my-auto">
        <h4 class="page-title">Giao dịch 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">
            <router-link :to="{ name: 'bank-accounts' }">Quản lý tài khoản ngân hàng</router-link>
          </li>
          <li class="breadcrumb-item active" aria-current="page">Giao dịch</li>
        </ol>
      </div>
      <router-link :to="{ name: 'bank-accounts' }" class="btn btn-secondary btn-sm">
        <i class="fas fa-arrow-left me-1"></i>
        Quay lại
      </router-link>
    </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. 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="Mô tả, mã giao dịch, tên đối tác...">
              </div>
              <div class="col-lg-3 col-md-4 mb-3">
                <label>Tài khoản ngân hàng</label>
                <v-select v-model="searchModel.Search.PredicateObject.BankAccountId" :options="bankAccountOptions"
                  :reduce="option => option.Id" label="AccountName" placeholder="Chọn tài khoản..." :clearable="true">
                  <template #option="{ AccountName, AccountNumber, BankName }">
                    <div>
                      <div class="fw-bold">{{ AccountName }}</div>
                      <small class="text-muted">{{ AccountNumber }} - {{ BankName }}</small>
                    </div>
                  </template>
                </v-select>
              </div>
              <!-- Date Range Picker -->
              <div class="col-lg-3 col-md-4 mb-3">
                <label>Ngày giao dịch</label>
                <VueDatePicker ref="transactionDatePicker" v-model="dateRange" :enable-time-picker="false" range
                  multi-calendars auto-apply :format="format" @update:model-value="handleDateRange">
                  <template #left-sidebar>
                    <DateRangeSidebar @change-date="onChangeDate"></DateRangeSidebar>
                  </template>
                </VueDatePicker>
              </div>
              <div class="col-lg-3 col-md-4 mb-3">
                <label>Loại giao dịch</label>
                <v-select v-model="searchModel.Search.PredicateObject.TransactionDirection"
                  :options="transactionDirectionOptions" :reduce="option => option.value" label="label"
                  placeholder="Chọn loại..." :clearable="true" />
              </div>
              <div class="col-lg-3 col-md-4 mb-3">
                <label>Trạng thái xử lý</label>
                <v-select v-model="searchModel.Search.PredicateObject.ProcessStatus" :options="processStatusOptions"
                  :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>Số tiền từ</label>
                <VueNumberFormat v-model:value="searchModel.Search.PredicateObject.AmountFrom" class="form-control"
                  :options="{ precision: 0, prefix: '', suffix: '', isInteger: true }" placeholder="0" />
              </div>
              <div class="col-lg-3 col-md-4 mb-3">
                <label>Số tiền đến</label>
                <VueNumberFormat v-model:value="searchModel.Search.PredicateObject.AmountTo" class="form-control"
                  :options="{ precision: 0, prefix: '', suffix: '', isInteger: true }" placeholder="0" />
              </div>
            </div>

            <!-- Search Button -->
            <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>
                <button type="button" @click="resetSearch" class="btn btn-secondary ms-2">
                  <i class="fe fe-refresh-cw"></i>
                  <span>Làm mới</span>
                </button>
                <button type="button" @click="exportData" class="btn btn-success ms-2" :disabled="exporting">
                  <span v-if="exporting" class="spinner-border spinner-border-sm"></span>
                  <i v-else class="fe fe-download"></i>
                  <span>{{ exporting ? 'Đang xuất...' : 'Xuất Excel' }}</span>
                </button>
              </div>
            </div>
          </form>
        </div>

        <!-- 4. Data Table Card -->
        <div class="card card-table shadow-none">
          <div class="card-body card-table-body">
            <!-- 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-12p min-width-2"><span>Ngày giao dịch</span></th>
                    <th class="wd-lg-8p"><span>Mã giao dịch</span></th>
                    <th class="wd-lg-15p"><span>Mô tả</span></th>
                    <th class="wd-lg-12p"><span>Đối tác</span></th>
                    <th class="wd-lg-8p text-end"><span>Số tiền</span></th>
                    <th class="wd-lg-8p text-end"><span>Số dư</span></th>
                    <th class="wd-lg-8p"><span>Trạng thái</span></th>
                    <th class="wd-lg-12p"><span>Tài khoản</span></th>
                  </tr>
                </thead>

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

                <!-- Empty State -->
                <tbody v-if="!loading && items.length <= 0">
                  <tr>
                    <td colspan="8" 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 && items.length > 0">
                  <tr v-for="item in items" :key="item.Id">
                    <td>
                      <div>{{ formatDate(item.TransactionDate) }}</div>
                      <small class="text-muted" v-if="item.DetailedTime">
                        {{ formatTime(item.DetailedTime) }}
                      </small>
                    </td>
                    <td>
                      <code>{{ item.TransactionCode }}</code>
                      <div v-if="item.ReferenceNumber" class="text-muted small">
                        Ref: {{ item.ReferenceNumber }}
                      </div>
                    </td>
                    <td class="text-wrap align-top">
                      <div class="text-truncate" style="max-width: 200px;" :title="item.Description">
                        {{ item.Description }}
                      </div>
                      <small v-if="item.TransactionType"
                        :class="`text-${getTransactionTypeColor(item.TransactionType)}`">
                        {{ item.TransactionType }}
                      </small>
                    </td>
                    <td class="text-wrap align-top">
                      <div v-if="item.CounterpartyName">{{ item.CounterpartyName }}</div>
                      <small v-if="item.CounterpartyAccount" class="text-muted">
                        {{ item.CounterpartyAccount }}
                      </small>
                      <small v-if="item.CounterpartyBank" class="text-muted d-block">
                        {{ item.CounterpartyBank }}
                      </small>
                    </td>
                    <td class="text-end align-top">
                      <div v-if="item.CreditAmount" class="text-success fw-bold">
                        +{{ item.CreditAmount }}
                      </div>
                      <div v-if="item.DebitAmount" class="text-danger fw-bold">
                        -{{ item.DebitAmount }}
                      </div>
                    </td>
                    <td class="text-end align-top">
                      <span class="fw-bold">{{ item.Balance }}</span>
                    </td>
                    <td class="align-top">
                      <span :class="`badge bg-${getTransactionStatusColor(item.ProcessStatus)}`">
                        {{ item.ProcessStatus }}
                      </span>
                    </td>
                    <td class="text-wrap align-top">
                      <div class="small">{{ item.BankAccountName }}</div>
                      <small class="text-muted">{{ item.BankAccountNumber }}</small>
                      <small class="text-muted d-block">{{ item.BankName }}</small>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

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

      </div>
    </div>
  </div>
</template>

<script setup>
//#region Imports
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useToast } from "vue-toastification"
//#endregion

//#region Components
import DatepickerInstance from "@vuepic/vue-datepicker"
import { DateRangeSidebar } from '@/components/index'
//#endregion

//#region Services
import bankAccountService from '@/services/bankAccountService'
import {
  TransactionProcessStatusList,
  BankTransactionTypeList,
  BankAccountUtils
} from '@/infrastructure/constants/bankAccountConstants'
//#endregion

//#region Composables
const route = useRoute()
const router = useRouter()
const toast = useToast()
//#endregion

//#region Reactive Data
const loading = ref(false)
const exporting = ref(false)
const bankAccountOptions = ref([])
const ctrlPager = ref()

// Date Range Picker
const dateRange = ref()
const transactionDatePicker = ref(DatepickerInstance)

const searchModel = reactive({
  Pagination: {
    PageIndex: 1,
    PageSize: 25,
    Total: 0
  },
  Search: {
    PredicateObject: {
      Keyword: '',
      BankAccountId: null,
      TransactionCode: '',
      TransactionDateFrom: null,
      TransactionDateTo: null,
      AmountFrom: null,
      AmountTo: null,
      TransactionDirection: null,
      ProcessStatus: null,
      TransactionType: null,
      ImportId: null
    }
  },
  Sort: {
    Predicate: 'TransactionDate',
    Reverse: true
  },
  IsExport: false
})

const items = reactive([])

// Options
const processStatusOptions = TransactionProcessStatusList
const transactionDirectionOptions = [
  { value: 'Credit', label: 'Thu (Tiền vào)' },
  { value: 'Debit', label: 'Chi (Tiền ra)' }
]
//#endregion

//#region Computed
const totalCredit = computed(() => {
  return items.reduce((sum, item) => {
    const amount = parseFloat(item.CreditAmount?.replace(/[,\s]/g, '') || 0)
    return sum + amount
  }, 0)
})

const totalDebit = computed(() => {
  return items.reduce((sum, item) => {
    const amount = parseFloat(item.DebitAmount?.replace(/[,\s]/g, '') || 0)
    return sum + amount
  }, 0)
})
//#endregion

//#region Methods
const loadBankAccounts = async () => {
  try {
    const accounts = await bankAccountService.getActiveAccounts()
    bankAccountOptions.value = accounts

    // Auto-select account if provided in query
    const accountId = route.query.accountId
    if (accountId) {
      searchModel.Search.PredicateObject.BankAccountId = parseInt(accountId)
    }

    // Auto-filter by import ID if provided
    const importId = route.query.importId
    if (importId) {
      searchModel.Search.PredicateObject.ImportId = importId
    }
  } catch (error) {
    console.error('Error loading bank accounts:', error)
    toast.error('Có lỗi xảy ra khi tải danh sách tài khoản ngân hàng')
  }
}

const search = async () => {
  searchModel.Pagination.PageIndex = 1
  if (ctrlPager.value) {
    ctrlPager.value.Refresh()
  }
  loadData()
}

const loadData = async () => {
  loading.value = true
  try {
    // Clear old data
    items.splice(0, items.length)

    // Convert dates to ISO format
    const searchParams = { ...searchModel }
    if (searchParams.Search.PredicateObject.TransactionDateFrom) {
      searchParams.Search.PredicateObject.TransactionDateFrom =
        new Date(searchParams.Search.PredicateObject.TransactionDateFrom).toISOString()
    }
    if (searchParams.Search.PredicateObject.TransactionDateTo) {
      searchParams.Search.PredicateObject.TransactionDateTo =
        new Date(searchParams.Search.PredicateObject.TransactionDateTo).toISOString()
    }

    const result = await bankAccountService.searchTransactions(searchParams)

    // Add new data
    if (result.Items && result.Items.length > 0) {
      result.Items.forEach(item => {
        items.push(item)
      })
    }

    // Update pagination info
    searchModel.Pagination.Total = result.TotalRecord
  } catch (error) {
    console.error('Error loading transactions:', error)
    toast.error('Có lỗi xảy ra khi tìm kiếm giao dịch')
  } finally {
    loading.value = false
  }
}

const resetSearch = () => {
  searchModel.Search.PredicateObject = {
    Keyword: '',
    BankAccountId: null,
    TransactionCode: '',
    TransactionDateFrom: null,
    TransactionDateTo: null,
    AmountFrom: null,
    AmountTo: null,
    TransactionDirection: null,
    ProcessStatus: null,
    TransactionType: null,
    ImportId: null
  }
  // Reset date range picker
  dateRange.value = null
  search()
}

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

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

const exportData = async () => {
  exporting.value = true
  try {
    const exportParams = { ...searchModel, IsExport: true }
    // Convert dates to ISO format
    if (exportParams.Search.PredicateObject.TransactionDateFrom) {
      exportParams.Search.PredicateObject.TransactionDateFrom =
        new Date(exportParams.Search.PredicateObject.TransactionDateFrom).toISOString()
    }
    if (exportParams.Search.PredicateObject.TransactionDateTo) {
      exportParams.Search.PredicateObject.TransactionDateTo =
        new Date(exportParams.Search.PredicateObject.TransactionDateTo).toISOString()
    }

    const result = await bankAccountService.searchTransactions(exportParams)
    if (result.ExportUrl) {
      window.open(result.ExportUrl, '_blank')
      toast.success('Xuất dữ liệu thành công')
    } else {
      toast.error('Không thể xuất dữ liệu')
    }
  } catch (error) {
    console.error('Error exporting data:', error)
    toast.error('Có lỗi xảy ra khi xuất dữ liệu')
  } finally {
    exporting.value = false
  }
}
//#endregion

//#region Utility Functions
const formatCurrency = BankAccountUtils.formatCurrency
const getTransactionStatusColor = BankAccountUtils.getTransactionStatusColor
const getTransactionTypeColor = BankAccountUtils.getTransactionTypeColor

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

const formatTime = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleTimeString('vi-VN')
}

// Date Range Functions
const format = (dates) => {
  if (!dates || !dates[0] || !dates[1]) return ''
  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}`
}

const onChangeDate = async (newDates) => {
  dateRange.value = newDates
  transactionDatePicker.value.closeMenu()
  handleDateRange(newDates)
}

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

//#region Lifecycle
onMounted(() => {
  loadBankAccounts().then(() => {
    loadData()
  })
})
//#endregion
</script>

<style scoped>
/* Search Form Styling */
.card-search {
  border: 1px solid var(--lada-border-color, #e9ecef);
  background-color: var(--lada-bg-light, #f8f9fa);
}

/* Table Styling */
.table th {
  background-color: var(--lada-bg-light, #f8f9fa);
  border-top: none;
  font-weight: 600;
}

.table-vcenter td {
  vertical-align: top;
}

/* Code Styling */
code {
  background-color: var(--lada-bg-light, #f8f9fa);
  color: var(--lada-text-muted, #495057);
  padding: 0.125rem 0.25rem;
  border-radius: var(--lada-border-radius, 0.25rem);
  font-size: 0.875rem;
}

/* Text Utilities */
.text-truncate {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* Status Badges */
.badge {
  font-size: 0.75rem;
  font-weight: 500;
}

/* Responsive Design */
@media (max-width: 767.98px) {
  .table-responsive {
    font-size: 0.875rem;
  }

  .btn {
    font-size: 0.875rem;
    padding: 0.375rem 0.75rem;
  }
}

/* Loading States */
.spinner-border-sm {
  width: 1rem;
  height: 1rem;
}

/* Form Controls */
.form-control:focus {
  border-color: var(--lada-primary, #007bff);
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

/* Button States */
.btn:disabled {
  opacity: 0.65;
  cursor: not-allowed;
}
</style>
