<template>
  <div>
    <!-- Breadcrumb -->
    <div class="breadcrumb-header justify-content-between">
      <div class="my-auto">
        <h4 class="page-title">Báo cáo công nợ chuyển khoản ngân hàng theo Sale</h4>
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="/">Trang chủ</a></li>
          <li class="breadcrumb-item"><a href="javascript:void(0);">Báo cáo</a></li>
          <li class="breadcrumb-item active" aria-current="page">Công nợ chuyển khoản</li>
        </ol>
      </div>
    </div>

    <!-- Search Form -->
    <div class="row row-sm">
      <div class="col-lg-12">
        <div class="card shadow-none">
          <div class="card-header">
            <h5 class="card-title mb-0">
              <i class="fas fa-search me-2"></i>
              Tìm kiếm
            </h5>
          </div>
          <div class="card-body">
            <form @submit.prevent="search">
              <div class="row">
                
                
                <div class="col-lg-3 col-md-6 mb-3" v-if="isFounder">
                  <label class="form-label">Sale</label>
                  <v-select 
                    label="FullName" 
                    :options="salesList"
                    v-model="selectedSale"
                    :reduce="(option) => option.Id"
                    placeholder="Tất cả sale"
                  >
                    <template v-slot:no-options="{ search, searching }">
                      <template v-if="searching">
                        Không có kết quả cho <em>{{ search }}</em>.
                      </template>
                      <span v-else style="opacity: 0.8">Không có bản ghi nào</span>
                    </template>
                  </v-select>
                </div>

                <div class="col-lg-3 col-md-6 mb-3">
                  <label class="form-label">Khách hàng</label>
                  <v-select 
                    v-model="selectedCustomer" 
                    :reduce="(option) => option.Id"
                    label="FullName + ' - ' + PhoneNumber" 
                    :filterable="false" 
                    :options="customersList"
                    @search="searchCustomers" 
                    placeholder="Chọn / tìm khách hàng theo tên / sđt"
                  >
                    <template #no-options="{ search, searching, loading }">
                      Gõ từ khóa để tìm khách hàng....
                    </template>
                    <template #option="{ FullName, PhoneNumber, UserName }">
                      <div class="mt-0 pb-1">
                        <h5 class="mb-1 tx-14">{{ FullName }}</h5>
                        <p class="mb-0 tx-13">
                          <span>
                            <i class="fas fa-phone tx-11"></i>
                            {{ PhoneNumber }}
                          </span>
                          <span class="mg-l-10">
                            <i class="fas fa-user tx-11"></i>
                            {{ UserName }}
                          </span>
                        </p>
                      </div>
                    </template>
                    <template #selected-option="{ FullName, PhoneNumber }">
                      <div style="display: flex; align-items: baseline">
                        <strong>{{ FullName }}</strong>
                        <span class="mg-r-5 mg-l-10">|</span>
                        <small style="margin-left: 0.5rem">{{ PhoneNumber }}</small>
                      </div>
                    </template>
                  </v-select>
                </div>

                <div class="col-lg-3 col-md-6 mb-3">
                  <label class="form-label">Trạng thái đơn hàng</label>
                  <v-select 
                    multiple
                    :options="statusOptions"
                    label="Name"
                    :reduce="(option) => option.Id"
                    v-model="selectedStatuses"
                    placeholder="Chọn trạng thái"
                  >
                    <template v-slot:no-options>
                      <span style="opacity: 0.8">Không có bản ghi nào</span>
                    </template>
                  </v-select>
                </div>

                <div class="col-lg-3 col-md-6 mb-3">
                  <label class="form-label">Trạng thái vật lý</label>
                  <v-select 
                    multiple
                    :options="physicalStatusOptions"
                    label="Name"
                    :reduce="(option) => option.Id"
                    v-model="selectedPhysicalStatuses"
                    placeholder="Chọn trạng thái vật lý"
                  >
                    <template v-slot:no-options>
                      <span style="opacity: 0.8">Không có bản ghi nào</span>
                    </template>
                  </v-select>
                </div>
              </div>
              <div class="row">
                <div class="col-12">
                  <button type="submit" class="btn btn-primary me-2" :disabled="loading">
                    <i v-show="!loading" class="fas fa-search me-2"></i>
                    <span v-show="loading" class="spinner-border spinner-border-sm me-2"></span>
                    Tìm kiếm
                  </button>
                  <button type="button" class="btn btn-secondary" @click="resetSearch">
                    <i class="fas fa-redo me-2"></i>Làm mới
                  </button>
                </div>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>

    <!-- Summary Cards -->
    <div class="row row-sm" v-if="reportData.length > 0 && !loading">
      <div class="col-sm-12 col-md-12 col-lg-12 col-xl-12 grid-margin">
        <div class="card shadow-none mb-3">
          <div class="card-header">
            <h5 class="card-title mb-0">
              <i class="fas fa-chart-pie me-2"></i>
              Tổng quan
            </h5>
          </div>
          <div class="card-body">
            <div class="row">
              <!-- Tổng số đơn -->
              <div class="col-lg-3 col-md-6 mb-3">
                <div class="card bg-primary text-white">
                  <div class="card-body">
                    <h4 class="mb-1">{{ formatNumber(summaryStats.totalOrders) }}</h4>
                    <p class="mb-0 small">Đơn hàng</p>
                    <div class="mt-2">
                      <strong>Tổng số đơn</strong>
                    </div>
                  </div>
                </div>
              </div>

              <!-- Tổng cước -->
              <div class="col-lg-3 col-md-6 mb-3">
                <div class="card bg-info text-white">
                  <div class="card-body">
                    <h4 class="mb-1">{{ formatCurrency(summaryStats.totalFee) }}</h4>
                    <p class="mb-0 small">Tổng phí: {{ formatCurrency(summaryStats.totalTransferFee) }}</p>
                    <div class="mt-2">
                      <strong>Tổng tiền cước</strong>
                    </div>
                  </div>
                </div>
              </div>

              <!-- Chưa thu -->
              <div class="col-lg-2 col-md-6 mb-3">
                <div class="card bg-warning text-white">
                  <div class="card-body">
                    <h4 class="mb-1">{{ formatCurrency(summaryStats.notCollected) }}</h4>
                    <p class="mb-0 small">{{ formatNumber(summaryStats.notCollectedCount) }} đơn</p>
                    <div class="mt-2">
                      <strong>Chưa thu</strong>
                    </div>
                  </div>
                </div>
              </div>

              <!-- Đã tạo phiếu -->
              <div class="col-lg-2 col-md-6 mb-3">
                <div class="card bg-secondary text-white">
                  <div class="card-body">
                    <h4 class="mb-1">{{ formatCurrency(summaryStats.createdBill) }}</h4>
                    <p class="mb-0 small">{{ formatNumber(summaryStats.createdBillCount) }} đơn</p>
                    <div class="mt-2">
                      <strong>Đã tạo phiếu</strong>
                    </div>
                  </div>
                </div>
              </div>

              <!-- Đã thu -->
              <div class="col-lg-2 col-md-6 mb-3">
                <div class="card bg-success text-white">
                  <div class="card-body">
                    <h4 class="mb-1">{{ formatCurrency(summaryStats.collected) }}</h4>
                    <p class="mb-0 small">{{ formatNumber(summaryStats.collectedCount) }} đơn</p>
                    <div class="mt-2">
                      <strong>Đã thu</strong>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Data Table -->
    <div class="row row-sm">
      <div class="col-lg-12">
        <div class="card shadow-none">
          <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="card-title mb-0">
              <i class="fas fa-table me-2"></i>
              Chi tiết theo Sale
            </h5>
            <div>
              <span class="badge bg-secondary">Tổng: {{ formatNumber(searchModel.Pagination.Total) }} sale</span>
            </div>
          </div>
          <div class="card-body">
            <!-- Empty state when no search performed -->
            <div v-if="!loading && reportData.length === 0 && searchModel.Pagination.Total === 0" class="text-center py-5">
              <div class="mb-3">
                <i class="fas fa-chart-line fa-3x text-muted"></i>
              </div>
              <h5 class="text-muted">Nhấn "Tìm kiếm" để xem báo cáo</h5>
              <p class="text-muted">Có thể chọn thời gian, sale hoặc khách hàng để lọc dữ liệu</p>
            </div>

            <!-- Data table -->
            <div v-else class="table-responsive">
              <table class="table table-bordered table-striped">
                <thead class="table-primary">
                  <tr>
                    <th class="wd-15p">Sale</th>
                    <th class="text-center">Tổng đơn</th>
                    <th class="text-center">Tổng cước</th>
                    <th class="text-center">Phí CK</th>
                    <th class="text-center">Chưa thu</th>
                    <th class="text-center">Đã tạo phiếu</th>
                    <th class="text-center">Đã thu</th>
                    <th class="text-center">Tỷ lệ thu</th>
                  </tr>
                </thead>
                <tbody v-if="loading">
                  <tr>
                    <td colspan="8" class="tx-semibold text-center text-default">
                      <span class="spinner-border spinner-border-sm"></span>
                      <span class="ms-2">Đang tải dữ liệu...</span>
                    </td>
                  </tr>
                </tbody>
                <tbody v-if="!loading && reportData.length <= 0 && searchModel.Pagination.Total > 0">
                  <tr>
                    <td colspan="8" class="tx-semibold text-center text-danger">
                      Không tìm thấy dữ liệu!
                    </td>
                  </tr>
                </tbody>
                <tbody v-if="!loading && reportData.length > 0">
                  <tr v-for="item in reportData" :key="item.SaleId">
                    <td>
                      <div class="fw-bold">{{ item.SaleName }}</div>
                      <div class="small text-muted">ID: {{ item.SaleId }}</div>
                      <div class="small text-info">{{ item.SalePhoneNumber }}</div>
                    </td>
                    <td class="text-center">
                      <div class="fw-bold text-primary">{{ formatNumber(item.TotalOrders) }}</div>
                    </td>
                    <td class="text-center">
                      <div class="fw-bold text-success">{{ formatCurrency(item.SumTotalFee) }}</div>
                    </td>
                    <td class="text-center">
                      <div class="fw-bold text-info">{{ formatCurrency(item.TotalTransferFee) }}</div>
                    </td>
                    <td class="text-center">
                      <div class="fw-bold text-warning">{{ formatCurrency(item.NotCollectAmount) }}</div>
                      <div class="small text-muted">{{ formatNumber(item.NotCollectedCount) }} đơn</div>
                    </td>
                    <td class="text-center">
                      <div class="fw-bold text-secondary">{{ formatCurrency(item.CreatedBillAmount) }}</div>
                      <div class="small text-muted">{{ formatNumber(item.CountCreatedBill) }} đơn</div>
                    </td>
                    <td class="text-center">
                      <div class="fw-bold text-success">{{ formatCurrency(item.TotalCollected) }}</div>
                      <div class="small text-muted">{{ formatNumber(item.CountCollected) }} đơn</div>
                    </td>
                    <td class="text-center">
                      <div class="progress" style="height: 25px;">
                        <div 
                          class="progress-bar" 
                          :class="getProgressBarClass(calculateCollectionRate(item))"
                          role="progressbar"
                          :style="`width: ${calculateCollectionRate(item)}%`"
                          :aria-valuenow="calculateCollectionRate(item)" 
                          aria-valuemin="0"
                          aria-valuemax="100"
                        >
                          {{ formatPercent(calculateCollectionRate(item)) }}%
                        </div>
                      </div>
                    </td>
                  </tr>
                </tbody>
                <tfoot v-if="!loading && reportData.length > 0">
                  <tr>
                    <td><strong>Tổng</strong></td>
                    <td class="text-center"><strong class="text-primary">{{ formatNumber(summaryStats.totalOrders) }}</strong></td>
                    <td class="text-center"><strong class="text-success">{{ formatCurrency(summaryStats.totalFee) }}</strong></td>
                    <td class="text-center"><strong class="text-info">{{ formatCurrency(summaryStats.totalTransferFee) }}</strong></td>
                    <td class="text-center"><strong class="text-warning">{{ formatCurrency(summaryStats.notCollected) }}</strong></td>
                    <td class="text-center"><strong class="text-secondary">{{ formatCurrency(summaryStats.createdBill) }}</strong></td>
                    <td class="text-center"><strong class="text-success">{{ formatCurrency(summaryStats.collected) }}</strong></td>
                    <td class="text-center"><strong>{{ formatPercent(overallCollectionRate) }}%</strong></td>
                  </tr>
                </tfoot>
              </table>
            </div>

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

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue';
import reportService from "@/services/reportService";
import customerService from "@/services/customerService";
import userService from "@/services/userService";
import { useToast } from "vue-toastification";
import { useUserStore } from "@/stores";
import moment from "moment";
import _ from 'lodash';

const toast = useToast();
const userStore = useUserStore();

//#region DATA
const loading = ref(false);

// Check if user is Founder
const isFounder = computed(() => {
  // TODO: Replace with actual role check from userStore
  return userStore.user?.roles?.includes('Founder') || false;
});

// Data
const reportData = reactive([]);
const salesList = reactive([]);
const customersList = reactive([]);
const selectedSale = ref(null);
const selectedCustomer = ref(null);
const statusOptions = reactive([]);
const physicalStatusOptions = reactive([]);
const selectedStatuses = ref([]);
const selectedPhysicalStatuses = ref([]);

// Search model
const searchModel = reactive({
  Pagination: {
    Total: 0,
    PageIndex: 1,
    PageSize: 25
  },
  Sort: {
    Predicate: 'SaleName',
    Reverse: false
  },
  Search: {
    PredicateObject: {
      CustomerId: null,
      SaleId: null
    }
  }
});

const ctrlPager = ref();
//#endregion

//#region COMPUTED
const summaryStats = computed(() => {
  if (reportData.length === 0) {
    return {
      totalOrders: 0,
      totalFee: 0,
      totalTransferFee: 0,
      notCollected: 0,
      notCollectedCount: 0,
      createdBill: 0,
      createdBillCount: 0,
      collected: 0,
      collectedCount: 0
    };
  }

  return reportData.reduce((acc, item) => {
    acc.totalOrders += item.TotalOrders || 0;
    acc.totalFee += item.SumTotalFee || 0;
    acc.totalTransferFee += item.TotalTransferFee || 0;
    acc.notCollected += item.NotCollectAmount || 0;
    acc.notCollectedCount += item.NotCollectedCount || 0;
    acc.createdBill += item.CreatedBillAmount || 0;
    acc.createdBillCount += item.CountCreatedBill || 0;
    acc.collected += item.TotalCollected || 0;
    acc.collectedCount += item.CountCollected || 0;
    return acc;
  }, {
    totalOrders: 0,
    totalFee: 0,
    totalTransferFee: 0,
    notCollected: 0,
    notCollectedCount: 0,
    createdBill: 0,
    createdBillCount: 0,
    collected: 0,
    collectedCount: 0
  });
});
//#endregion

//#region LIFECYCLE
onMounted(async () => {
  await loadPrepareModel();
  // Load initial data
  await loadSalesAndCustomers();
  // Auto-search on mount after prepare model
  await search();
});
//#endregion

//#region FUNCTIONS
const overallCollectionRate = computed(() => {
  const total = (summaryStats.value.notCollected || 0) + (summaryStats.value.createdBill || 0) + (summaryStats.value.collected || 0);
  if (total === 0) return 0;
  return (summaryStats.value.collected / total) * 100;
});

function formatNumber(value) {
  if (value == null || value == undefined) return '0';
  return new Intl.NumberFormat('vi-VN').format(value);
}

function formatCurrency(value) {
  if (value == null || value == undefined) return '0 ₫';
  return new Intl.NumberFormat('vi-VN', {
    style: 'currency',
    currency: 'VND'
  }).format(value);
}

function formatPercent(value) {
  if (value == null || value == undefined) return '0.00';
  return parseFloat(value).toFixed(2);
}

function calculateCollectionRate(item) {
  const total = (item.NotCollectAmount || 0) + (item.CreatedBillAmount || 0) + (item.TotalCollected || 0);
  if (total === 0) return 0;
  return ((item.TotalCollected || 0) / total) * 100;
}

function getProgressBarClass(rate) {
  if (rate >= 80) return 'bg-success';
  if (rate >= 50) return 'bg-info';
  if (rate >= 30) return 'bg-warning';
  return 'bg-danger';
}

// removed date filter

async function loadSalesAndCustomers() {
  try {
    // Load sales list if Founder
    if (isFounder.value) {
      const salesResult = await userService.listStaff({
        Pagination: { PageIndex: 1, PageSize: 1000 },
        Search: { PredicateObject: {} }
      });
      if (salesResult && salesResult.Items) {
        salesList.splice(0, salesList.length);
        salesResult.Items.forEach(sale => {
          salesList.push(sale);
        });
      }
    }
  } catch (error) {
    console.error('Error loading sales:', error);
  }
}

// Customer search with debounce (like in customer.vue)
async function searchCustomers(keyword, loading) {
  if (keyword.length) {
    loading(true);
    await loadSuggestCustomers(loading, keyword);
  }
}

const loadSuggestCustomers = _.debounce(async (loading, keyword) => {
  customersList.splice(0, customersList.length);
  try {
    const customerResult = await customerService.suggest(keyword);
    if (customerResult != null && customerResult.length > 0) {
      customerResult.forEach(customer => {
        customersList.push(customer);
      });
    }
  } catch (error) {
    console.error('Error searching customers:', error);
  } finally {
    loading(false);
  }
}, 300);

async function search() {
  loading.value = true;
  reportData.splice(0, reportData.length);
  
  try {
    // Update search params (date removed)
    searchModel.Search.PredicateObject.CustomerId = selectedCustomer.value;
    searchModel.Search.PredicateObject.SaleId = isFounder.value ? selectedSale.value : null;

    // Build payload matching SmartTableParam per API guide
    const payload = {
      Pagination: {
        Start: (searchModel.Pagination.PageIndex - 1) * searchModel.Pagination.PageSize,
        Number: searchModel.Pagination.PageSize,
      },
      Search: {
        PredicateObject: {
          // No date filters
          CustomerId: searchModel.Search.PredicateObject.CustomerId || null,
          SaleId: isFounder.value ? searchModel.Search.PredicateObject.SaleId : null,
          Statuses: Array.isArray(selectedStatuses.value) && selectedStatuses.value.length > 0 ? selectedStatuses.value : undefined,
          PhysicalStatuses: Array.isArray(selectedPhysicalStatuses.value) && selectedPhysicalStatuses.value.length > 0 ? selectedPhysicalStatuses.value : undefined,
        },
      },
      Sort: {
        Predicate: searchModel.Sort.Predicate,
        Reverse: searchModel.Sort.Reverse,
      },
    };

    const result = await reportService.getBankTransferSummaryBySale(payload);
    
    if (result && Array.isArray(result)) {
      result.forEach(item => {
        reportData.push(item);
      });
      searchModel.Pagination.Total = result.length;
      
      if (result.length === 0) {
        toast.info('Không tìm thấy dữ liệu phù hợp với điều kiện tìm kiếm');
      }
    } else {
      toast.error('Lỗi: Không thể tải dữ liệu');
    }
  } catch (error) {
    console.error('Error searching bank transfer summary:', error);
    toast.error('Có lỗi xảy ra khi tải dữ liệu');
  } finally {
    loading.value = false;
  }
}

function resetSearch() {
  // Reset date to empty
  date.value = null;
  handleDate(null);

  // Reset filters
  selectedSale.value = null;
  selectedCustomer.value = null;

  // Clear data
  reportData.splice(0, reportData.length);
  searchModel.Pagination.Total = 0;

  // Reset pagination
  searchModel.Pagination.PageIndex = 1;
  if (ctrlPager.value) {
    ctrlPager.value.Refresh();
  }
}

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

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

// Watch for filter changes to auto-search
watch([selectedCustomer, selectedSale], () => {
  searchModel.Pagination.PageIndex = 1;
  if (ctrlPager.value) {
    ctrlPager.value.Refresh();
  }
  search();
});
// Auto search when statuses change
watch([selectedStatuses, selectedPhysicalStatuses], () => {
  searchModel.Pagination.PageIndex = 1;
  if (ctrlPager.value) {
    ctrlPager.value.Refresh();
  }
  search();
});
//#endregion

//#region PREPARE MODEL
const prepareModel = ref({});

async function loadPrepareModel() {
  try {
    const model = await reportService.prepareBankTransferSummaryBySaleModel();
    prepareModel.value = model || {};

    // Load status options if provided by backend
    const statuses = model?.StatusOptions || [];
    const physicalStatuses = model?.PhysicalStatusOptions || [];
    if (Array.isArray(statuses)) {
      statusOptions.splice(0, statusOptions.length);
      statuses.forEach(s => statusOptions.push(s));
    }
    if (Array.isArray(physicalStatuses)) {
      physicalStatusOptions.splice(0, physicalStatusOptions.length);
      physicalStatuses.forEach(s => physicalStatusOptions.push(s));
    }
  } catch (e) {
    console.error('Error loading prepare model:', e);
  }
}
//#endregion
</script>

<style scoped>
.progress {
  background-color: rgba(0, 0, 0, 0.1);
}

.table th {
  font-weight: 600;
  font-size: 0.875rem;
}

.table td {
  vertical-align: middle;
}

.fw-bold {
  font-weight: 600;
}

.card-body h4 {
  font-size: 1.5rem;
  font-weight: 700;
}

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

