<template>
  <div>
    <div class="row row-sm">
      <div class="col-sm-12 col-md-12 col-lg-12 col-xl-12 grid-margin">
        <!-- Search Form -->
        <form @submit.prevent="searchRefresh" class="mb-3">
          <div class="row">
            <div class="col-lg-6 col-md-8 mb-3">
              <label>Tìm kiếm</label>
              <input type="text" v-model="searchModel.Search.PredicateObject.Keyword" class="form-control"
                placeholder="Tên, SĐT, email, username..." />
            </div>
            <div class="col-lg-6 col-md-4 mb-3 d-flex align-items-end">
              <button type="submit" class="btn btn-dark me-2" :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" class="btn btn-outline-secondary" @click="resetSearch" :disabled="loading">
                <i class="fe fe-refresh-cw"></i>
                <span>Đặt lại</span>
              </button>
            </div>
          </div>
        </form>

        <!-- Summary Cards -->
        <div class="row mb-3" v-if="!loading && items.length > 0">
          <div class="col-md-3">
            <div class="card summary-card bg-primary-gradient text-white">
              <div class="card-body py-3">
                <div class="d-flex align-items-center justify-content-between">
                  <div>
                    <h6 class="mb-1 text-white-50">Tổng khách hàng</h6>
                    <h3 class="mb-0 fw-bold">{{ searchModel.Pagination.Total }}</h3>
                  </div>
                  <div class="summary-icon">
                    <i class="fe fe-users"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="col-md-3">
            <div class="card summary-card bg-info-gradient text-white">
              <div class="card-body py-3">
                <div class="d-flex align-items-center justify-content-between">
                  <div>
                    <h6 class="mb-1 text-white-50">Tổng tiền COD</h6>
                    <h3 class="mb-0 fw-bold">{{ formatCurrencyShort(totalCodAmount) }}</h3>
                  </div>
                  <div class="summary-icon">
                    <i class="fe fe-package"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="col-md-3">
            <div class="card summary-card bg-warning-gradient text-white">
              <div class="card-body py-3">
                <div class="d-flex align-items-center justify-content-between">
                  <div>
                    <h6 class="mb-1 text-white-50">Tổng phí dịch vụ</h6>
                    <h3 class="mb-0 fw-bold">{{ formatCurrencyShort(totalFees) }}</h3>
                  </div>
                  <div class="summary-icon">
                    <i class="fe fe-percent"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="col-md-3">
            <div class="card summary-card bg-success-gradient text-white">
              <div class="card-body py-3">
                <div class="d-flex align-items-center justify-content-between">
                  <div>
                    <h6 class="mb-1 text-white-50">Tiền trả khách hàng</h6>
                    <h3 class="mb-0 fw-bold">{{ formatCurrencyShort(totalEstimatedNet) }}</h3>
                  </div>
                  <div class="summary-icon">
                    <i class="fe fe-dollar-sign"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Results Card -->
        <div class="card card-table shadow-none">
          <div class="card-body card-table-body">
            <div class="table-responsive border-top mg-b-10">
              <table class="table table-vcenter table-hover mb-0" style="min-height:300px">
                <thead>
                  <tr>
                    <th class="wd-lg-20p min-width-1"><span>Thông tin khách hàng</span></th>
                    <th class="wd-lg-8p min-width-1 text-center"><span>Số đơn</span></th>
                    <th class="wd-lg-12p min-width-1 text-end"><span>Tiền COD</span></th>
                    <th class="wd-lg-12p min-width-1 text-end"><span>Phí dịch vụ</span></th>
                    <th class="wd-lg-12p min-width-1 text-end"><span>Tiền trả KH</span></th>
                    <th class="wd-lg-8p min-width-1 text-center"><span>Ưu tiên</span></th>
                    <th class="wd-lg-12p min-width-1 text-center"><span>Thời gian</span></th>
                    <th class="wd-lg-8p"></th>
                  </tr>
                </thead>
                <tbody v-if="loading">
                  <tr>
                    <td colspan="8" class="tx-semibold text-center text-default py-5">
                      <span class="spinner-border spinner-border-sm me-2"></span>
                      <span>Đang tải dữ liệu...</span>
                    </td>
                  </tr>
                </tbody>
                <tbody v-if="!loading && items.length <= 0">
                  <tr>
                    <td colspan="8" class="tx-semibold text-center text-muted py-5">
                      <i class="fe fe-inbox fs-3 d-block mb-2"></i>
                      Không tìm thấy khách hàng nào cần đối soát!
                    </td>
                  </tr>
                </tbody>
                <tbody v-if="!loading && items.length > 0" class="tx-13">
                  <tr v-for="item in items" :key="item.CustomerId" class="customer-row">
                    <!-- Thông tin khách hàng -->
                    <td class="text-wrap align-top">
                      <div class="customer-info">
                        <div class="fw-semibold mb-1">
                          <span class="customer-name">{{ item.CustomerName }}</span>
                          <span class="badge bg-light text-dark ms-2" v-if="item.CustomerCode">{{ item.CustomerCode
                          }}</span>
                        </div>
                        <div class="text-muted tx-12">
                          <i class="fe fe-phone me-1"></i>{{ item.CustomerPhone }}
                        </div>
                        <div class="text-muted tx-12" v-if="item.CustomerEmail">
                          <i class="fe fe-mail me-1"></i>{{ item.CustomerEmail }}
                        </div>
                        <!-- Thông tin ngân hàng -->
                        <div v-if="item.BankAccountNumber" class="mt-2 bank-info">
                          <i class="fe fe-credit-card me-1 text-info"></i>
                          <span class="tx-12 text-info">{{ item.BankName }} - {{ item.BankAccountNumber }}</span>
                          <div class="tx-11 text-muted">{{ item.BankAccountHolderName }}</div>
                        </div>
                      </div>
                    </td>

                    <!-- Số đơn -->
                    <td class="text-center align-middle">
                      <div class="order-count">
                        <span class="badge badge-lg bg-primary-transparent text-primary">
                          {{ item.PendingOrderCount }} đơn
                        </span>
                        <div class="tx-11 text-muted mt-1"
                          v-if="item.CodOrderCount > 0 || item.BankTransferOrderCount > 0">
                          <span v-if="item.CodOrderCount > 0" class="me-1">COD: {{ item.CodOrderCount }}</span>
                          <span v-if="item.BankTransferOrderCount > 0">CK: {{ item.BankTransferOrderCount }}</span>
                        </div>
                      </div>
                    </td>

                    <!-- Tiền COD -->
                    <td class="text-end align-middle">
                      <div class="amount-cell">
                        <span class="fw-semibold text-primary">{{ formatCurrency(item.TotalCodAmount) }}</span>
                      </div>
                    </td>

                    <!-- Phí dịch vụ -->
                    <td class="text-end align-middle">
                      <div class="fee-breakdown">
                        <span class="fw-semibold text-warning">{{ formatCurrency(getTotalFee(item)) }}</span>
                        <div class="tx-11 text-muted" v-if="item.TotalCodFee > 0 || item.TotalTransferFee > 0">
                          <div v-if="item.TotalCodFee > 0">Cước COD: {{ formatCurrency(item.TotalCodFee) }}</div>
                          <div v-if="item.TotalTransferFee > 0">Cước CK: {{ formatCurrency(item.TotalTransferFee) }}
                          </div>
                        </div>
                      </div>
                    </td>

                    <!-- Tiền trả KH -->
                    <td class="text-end align-middle">
                      <div class="amount-cell">
                        <span class="fw-bold fs-6"
                          :class="item.EstimatedNetAmount >= 0 ? 'text-success' : 'text-danger'">
                          {{ item.EstimatedNetAmountFormatted || formatCurrency(item.EstimatedNetAmount) }}
                        </span>
                      </div>
                    </td>

                    <!-- Mức ưu tiên -->
                    <td class="text-center align-middle">
                      <span :class="getPriorityBadgeClass(item.PriorityLevel)">
                        {{ item.PriorityLevel }}
                      </span>
                    </td>

                    <!-- Thời gian -->
                    <td class="text-center align-middle">
                      <div class="time-info">
                        <div class="tx-12">
                          <span class="text-muted">Cũ nhất:</span>
                          <span class="fw-medium">{{ formatDate(item.OldestOrderDate) }}</span>
                        </div>
                        <div class="tx-12">
                          <span class="text-muted">Mới nhất:</span>
                          <span class="fw-medium">{{ formatDate(item.LatestOrderDate) }}</span>
                        </div>
                        <div class="tx-11 mt-1">
                          <span :class="getDaysClass(item.DaysFromOldest)">
                            <i class="fe fe-clock me-1"></i>{{ item.DaysFromOldest }} ngày
                          </span>
                        </div>
                      </div>
                    </td>

                    <!-- Thao tác -->
                    <td class="align-middle text-end">
                      <button type="button" class="btn btn-sm btn-primary-gradient btn-action"
                        @click="viewReconciliationDetail(item)" :disabled="loading">
                        <i class="fe fe-eye me-1"></i>
                        Chi tiết
                      </button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            <pager ref="ctrlPager" v-show="!loading && items.length > 0" @PageSizeChanged="PageSizeChanged"
              @PageIndexChanged="PageIndexChanged" :Total="searchModel.Pagination.Total" :TotalCurrent="items.length">
            </pager>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useToast } from 'vue-toastification'
import reconciliationService from '@/services/reconciliationService'
import LeftSidebar from "@/components/daterange/left-sidebar.vue"
import DatepickerInstance from "@vuepic/vue-datepicker"

const router = useRouter()
const toast = useToast()

// Define emits
const emit = defineEmits(['update-count'])

// Reactive data
const loading = ref(false)
const items = reactive([])
const dateRange = ref(null)
const dateRangePicker = ref(DatepickerInstance)

// Khởi tạo với 30 ngày gần đây (mặc định của API)
const initDateRange = () => {
  const today = new Date()
  const thirtyDaysAgo = new Date()
  thirtyDaysAgo.setDate(today.getDate() - 30)
  return [thirtyDaysAgo, today]
}

const searchModel = reactive({
  Pagination: {
    Total: 0,
    PageIndex: 1,
    PageSize: 25
  },
  Sort: {
    Predicate: 'LatestOrderDate',
    Reverse: true
  },
  Search: {
    PredicateObject: {
      Keyword: '',
      FromDate: null,
      ToDate: null,
      Priority: null
    }
  }
})

const priorityOptions = reactive([
  { Id: null, Name: "Tất cả" },
  { Id: "Thấp", Name: "Thấp (<15 ngày)" },
  { Id: "Trung bình", Name: "Trung bình (15-30 ngày)" },
  { Id: "Cao", Name: "Cao (>30 ngày)" }
])

const sortOptions = reactive([
  { Id: 'LatestOrderDate', Name: "Đơn mới nhất (giảm dần)" },
  { Id: 'OldestOrderDate', Name: "Đơn cũ nhất" },
  { Id: 'DaysFromOldest', Name: "Số ngày chờ (giảm dần)" },
  { Id: 'EstimatedNetAmount', Name: "Tiền trả KH (giảm dần)" },
  { Id: 'TotalCodAmount', Name: "Tiền COD (giảm dần)" },
  { Id: 'PendingOrderCount', Name: "Số đơn (giảm dần)" },
  { Id: 'CustomerName', Name: "Tên khách hàng (A-Z)" }
])

const selectedSort = ref('LatestOrderDate')
const ctrlPager = ref()

// Computed - Summary values
const totalCodAmount = computed(() => {
  return items.reduce((sum, item) => sum + (item.TotalCodAmount || 0), 0)
})

const totalFees = computed(() => {
  return items.reduce((sum, item) => {
    const codFee = item.TotalCodFee || 0
    const transferFee = item.TotalTransferFee || 0
    return sum + codFee + transferFee
  }, 0)
})

const totalEstimatedNet = computed(() => {
  return items.reduce((sum, item) => sum + (item.EstimatedNetAmount || 0), 0)
})

// Watch sort change
watch(selectedSort, (newValue) => {
  searchModel.Sort.Predicate = newValue
  if (newValue === 'CustomerName') {
    searchModel.Sort.Reverse = false
  } else {
    searchModel.Sort.Reverse = true
  }
})

// Methods
const formatCurrency = (amount) => {
  if (amount === null || amount === undefined) return '0 ₫'
  return new Intl.NumberFormat('vi-VN', {
    style: 'currency',
    currency: 'VND'
  }).format(amount)
}

const formatCurrencyShort = (amount) => {
  if (amount === null || amount === undefined) return '0 ₫'
  const absAmount = Math.abs(amount)
  const sign = amount < 0 ? '-' : ''
  if (absAmount >= 1000000000) {
    return sign + (absAmount / 1000000000).toFixed(1) + ' tỷ'
  }
  if (absAmount >= 1000000) {
    return sign + (absAmount / 1000000).toFixed(1) + ' tr'
  }
  if (absAmount >= 1000) {
    return sign + (absAmount / 1000).toFixed(0) + 'k'
  }
  return formatCurrency(amount)
}

const getTotalFee = (item) => {
  return (item.TotalCodFee || 0) + (item.TotalTransferFee || 0)
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleDateString('vi-VN', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric'
  })
}

const formatDateRange = (dates) => {
  if (!dates || !dates[0] || !dates[1]) return ''
  const start = dates[0]
  const 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 formatDateForApi = (date) => {
  if (!date) return null
  const d = new Date(date)
  return d.toISOString()
}

const getPriorityBadgeClass = (priority) => {
  const classMap = {
    'Cao': 'badge badge-lg bg-danger',
    'Trung bình': 'badge badge-lg bg-warning text-dark',
    'Thấp': 'badge badge-lg bg-success'
  }
  return classMap[priority] || 'badge badge-lg bg-secondary'
}

const getDaysClass = (days) => {
  if (days >= 30) return 'text-danger fw-semibold'
  if (days >= 15) return 'text-warning fw-semibold'
  return 'text-muted'
}

const viewReconciliationDetail = (customer) => {
  // Open in new tab instead of navigating in current tab
  const route = router.resolve({
    name: 'customer-reconciliation-detail',
    params: { customerId: customer.CustomerId }
  })
  window.open(route.href, '_blank')
}

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

const handleDateRange = (modelData) => {
  if (modelData != null && modelData[0] && modelData[1]) {
    // Set FromDate là đầu ngày
    const fromDate = new Date(modelData[0])
    fromDate.setHours(0, 0, 0, 0)
    searchModel.Search.PredicateObject.FromDate = formatDateForApi(fromDate)

    // Set ToDate là cuối ngày
    const toDate = new Date(modelData[1])
    toDate.setHours(23, 59, 59, 999)
    searchModel.Search.PredicateObject.ToDate = formatDateForApi(toDate)
  } else {
    searchModel.Search.PredicateObject.FromDate = null
    searchModel.Search.PredicateObject.ToDate = null
  }
}

const resetSearch = () => {
  searchModel.Search.PredicateObject.Keyword = ''
  searchModel.Search.PredicateObject.FromDate = null
  searchModel.Search.PredicateObject.ToDate = null
  searchModel.Search.PredicateObject.Priority = null
  dateRange.value = initDateRange()
  handleDateRange(dateRange.value)
  selectedSort.value = 'LatestOrderDate'
  searchModel.Sort.Predicate = 'LatestOrderDate'
  searchModel.Sort.Reverse = true
  searchRefresh()
}

async function searchRefresh() {
  searchModel.Pagination.PageIndex = 1
  ctrlPager.value?.Refresh()
  search()
}

async function search() {
  loading.value = true
  items.splice(0, items.length)

  try {
    const searchResult = await reconciliationService.getCustomersOverview(searchModel)
    if (searchResult.Items != null && searchResult.Items.length > 0) {
      // Filter by priority if selected (client-side filter)
      let filteredItems = searchResult.Items
      if (searchModel.Search.PredicateObject.Priority) {
        filteredItems = searchResult.Items.filter(
          item => item.PriorityLevel === searchModel.Search.PredicateObject.Priority
        )
      }
      filteredItems.forEach(customer => {
        items.push(customer)
      })
    }
    searchModel.Pagination.Total = searchResult.TotalRecord

    // Emit count to parent component
    emit('update-count', searchModel.Pagination.Total)
  } catch (error) {
    console.error('Error loading customers:', error)
    toast.error('Có lỗi xảy ra khi tải danh sách khách hàng cần đối soát')
  } finally {
    loading.value = false
  }
}

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

function PageIndexChanged(pageIndex) {
  searchModel.Pagination.PageIndex = pageIndex
  search()
}

onMounted(() => {
  // Khởi tạo với 30 ngày gần đây
  dateRange.value = initDateRange()
  handleDateRange(dateRange.value)
  search()
})
</script>

<style scoped>
/* Card Styles */
.summary-card {
  border: none;
  border-radius: 12px;
  overflow: hidden;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.summary-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.summary-icon {
  font-size: 2rem;
  opacity: 0.8;
}

.bg-primary-gradient {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.bg-info-gradient {
  background: linear-gradient(135deg, #17a2b8 0%, #138496 100%);
}

.bg-warning-gradient {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.bg-success-gradient {
  background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
}

/* Table Styles */
.table th {
  border-top: none;
  font-weight: 600;
  color: #495057;
  background-color: #f8f9fa;
  padding: 0.75rem;
  font-size: 0.85rem;
}

.table-hover tbody tr:hover {
  background-color: rgba(102, 126, 234, 0.05);
}

.customer-row {
  transition: background-color 0.15s ease;
}

.customer-info {
  line-height: 1.5;
}

.customer-name {
  color: #2d3748;
  font-size: 0.9rem;
}

.bank-info {
  padding: 0.4rem 0.5rem;
  background: linear-gradient(135deg, #e3f2fd 0%, #f3e5f5 100%);
  border-radius: 6px;
  border-left: 3px solid #2196f3;
}

.order-count {
  line-height: 1.4;
}

.amount-cell {
  padding: 0.25rem 0;
}

.fee-breakdown {
  line-height: 1.4;
}

.time-info {
  line-height: 1.6;
}

/* Badge Styles */
.badge {
  font-weight: 500;
  padding: 0.4rem 0.6rem;
  border-radius: 6px;
}

.badge-lg {
  font-size: 0.75rem;
}

.bg-primary-transparent {
  background-color: rgba(102, 126, 234, 0.15);
}

/* Button Styles */
.btn-action {
  white-space: nowrap;
  min-width: 70px;
  border-radius: 6px;
  font-weight: 500;
  font-size: 0.8rem;
  padding: 0.35rem 0.6rem;
  transition: all 0.2s ease;
}

.btn-primary-gradient {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
}

.btn-primary-gradient:hover {
  background: linear-gradient(135deg, #5a6fd6 0%, #6a4190 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.btn-primary-gradient:disabled {
  opacity: 0.7;
  transform: none;
  box-shadow: none;
}

/* Spinner */
.spinner-border {
  width: 1rem;
  height: 1rem;
}

/* Responsive */
@media (max-width: 768px) {
  .summary-card .card-body {
    padding: 0.75rem;
  }

  .summary-icon {
    font-size: 1.5rem;
  }

  .btn-action {
    min-width: auto;
    padding: 0.3rem 0.5rem;
  }
}
</style>
