<template>
  <div class="container-fluid">
    <!-- Header -->
    <div class="row">
      <div class="col-12">
        <div class="page-title-box d-sm-flex align-items-center justify-content-between">
          <h4 class="mb-sm-0">Danh sách phiếu đối soát cước</h4>
          <div class="page-title-right">
            <ol class="breadcrumb m-0">
              <li class="breadcrumb-item">
                <router-link to="/">Trang chủ</router-link>
              </li>
              <li class="breadcrumb-item">Đối soát cước</li>
              <li class="breadcrumb-item active">Danh sách phiếu đối soát</li>
            </ol>
          </div>
        </div>
      </div>
    </div>

    <!-- Filters -->
    <div class="row mb-3">
      <div class="col-12">
        <div class="card">
          <div class="card-body">
            <div class="row g-3">
              <!-- Tìm kiếm -->
              <div class="col-md-3">
                <label class="form-label">Tìm kiếm</label>
                <input type="text" class="form-control" placeholder="Mã đối soát hoặc tên khách hàng..."
                  v-model="searchModel.Search.PredicateObject.Keyword" @input="debouncedSearch" />
              </div>

              <!-- Trạng thái -->
              <div class="col-md-2">
                <label class="form-label">Trạng thái</label>
                <v-select v-model="searchModel.Search.PredicateObject.Status" :options="statusOptions"
                  :reduce="option => option.value" label="label" placeholder="Chọn trạng thái" :clearable="true"
                  @update:model-value="handleSearch" />
              </div>

              <!-- Từ ngày -->
              <div class="col-md-2">
                <label class="form-label">Từ ngày</label>
                <VueDatePicker v-model="searchModel.Search.PredicateObject.CreatedStart" :format="'dd/MM/yyyy'"
                  :enable-time-picker="false" placeholder="Chọn từ ngày" @update:model-value="handleSearch" />
              </div>

              <!-- Đến ngày -->
              <div class="col-md-2">
                <label class="form-label">Đến ngày</label>
                <VueDatePicker v-model="searchModel.Search.PredicateObject.CreatedEnd" :format="'dd/MM/yyyy'"
                  :enable-time-picker="false" placeholder="Chọn đến ngày" @update:model-value="handleSearch" />
              </div>

              <!-- Buttons -->
              <div class="col-md-3 d-flex align-items-end">
                <button type="button" class="btn btn-primary me-2" @click="handleSearch" :disabled="loading">
                  <i class="bx bx-search me-1"></i>
                  Tìm kiếm
                </button>
                <button type="button" class="btn btn-outline-secondary me-2" @click="handleReset" :disabled="loading">
                  <i class="bx bx-refresh me-1"></i>
                  Làm mới
                </button>
                <button type="button" class="btn btn-success" @click="handleExport" :disabled="loading">
                  <i class="bx bx-download me-1"></i>
                  Xuất Excel
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Results -->
    <div class="row">
      <div class="col-12">
        <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>
              <p class="mt-2 mb-0">Đang tải dữ liệu...</p>
            </div>

            <!-- Empty state -->
            <empty v-else-if="!loading && reconciliations.length === 0" icon="bx bx-file-blank"
              message="Không có phiếu đối soát cước nào" />

            <!-- Table -->
            <div v-else>
              <div class="table-responsive">
                <table class="table table-hover align-middle">
                  <thead class="table-light">
                    <tr>
                      <th @click="handleSort('code')" class="sortable">
                        Mã đối soát
                        <i class="bx bx-sort ms-1"></i>
                      </th>
                      <th>Khách hàng</th>
                      <th @click="handleSort('createdDate')" class="sortable text-center">
                        Ngày tạo
                        <i class="bx bx-sort ms-1"></i>
                      </th>
                      <th class="text-end">Tổng cước</th>
                      <th class="text-end">Phí dự kiến</th>
                      <th class="text-end">Thực chuyển</th>
                      <th class="text-center">Trạng thái</th>
                      <th class="text-center">Thao tác</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="reconciliation in reconciliations" :key="reconciliation.Id">
                      <!-- Mã đối soát -->
                      <td>
                        <div class="fw-semibold">{{ reconciliation.Code }}</div>
                        <div class="text-muted small">{{ reconciliation.OrderCount }} đơn hàng</div>
                      </td>

                      <!-- Khách hàng -->
                      <td>
                        <div class="fw-semibold">{{ reconciliation.CustomerName }}</div>
                        <div class="text-muted small">{{ reconciliation.CustomerPhone }}</div>
                      </td>

                      <!-- Ngày tạo -->
                      <td class="text-center">
                        <div>{{ formatDate(reconciliation.CreatedDate) }}</div>
                        <div class="text-muted small">{{ reconciliation.CreatedByName }}</div>
                      </td>

                      <!-- Tổng cước -->
                      <td class="text-end">
                        <span class="fw-semibold">{{ formatCurrency(reconciliation.TotalShippingFeeAmount) }}</span>
                      </td>

                      <!-- Phí dự kiến -->
                      <td class="text-end">
                        <span class="text-warning">{{ formatCurrency(reconciliation.TotalFeeAmount) }}</span>
                      </td>

                      <!-- Thực chuyển -->
                      <td class="text-end">
                        <span class="fw-semibold text-success">{{ formatCurrency(reconciliation.NetAmount) }}</span>
                      </td>

                      <!-- Trạng thái -->
                      <td class="text-center">
                        <span :class="getStatusBadgeClass(reconciliation.Status)">
                          {{ getStatusLabel(reconciliation.Status) }}
                        </span>
                      </td>

                      <!-- Thao tác -->
                      <td class="text-center">
                        <div class="btn-group" role="group">
                          <router-link
                            :to="{ name: 'shipping-fee-reconciliation-detail', params: { id: reconciliation.Id } }"
                            class="btn btn-sm btn-outline-primary">
                            <i class="bx bx-show me-1"></i>
                            Chi tiết
                          </router-link>
                        </div>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>

              <!-- Pagination -->
              <div class="row mt-3">
                <div class="col-sm-12 col-md-5">
                  <div class="dataTables_info">
                    Hiển thị {{ ((searchModel.Pagination.PageIndex - 1) * searchModel.Pagination.PageSize) + 1 }} đến
                    {{ Math.min(searchModel.Pagination.PageIndex * searchModel.Pagination.PageSize,
                      searchModel.Pagination.Total) }}
                    trong tổng số {{ searchModel.Pagination.Total }} bản ghi
                  </div>
                </div>
                <div class="col-sm-12 col-md-7">
                  <div class="dataTables_paginate">
                    <pagination v-model="searchModel.Pagination.PageIndex" :records="searchModel.Pagination.Total"
                      :per-page="searchModel.Pagination.PageSize" @paginate="handlePageChange" />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useToast } from 'vue-toastification';
import reconciliationService from '@/services/reconciliationService';
import { ReconciliationType, ReconciliationStatusOptions, getReconciliationStatusLabel, getReconciliationStatusClass } from '@/infrastructure/utilities/reconciliationConstants';
import { formatCurrency, formatDate, debounce } from '@/infrastructure/utilities/reconciliationHelpers';

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

// Reactive data
const loading = ref(false);
const reconciliations = ref([]);

const searchModel = reactive({
  Pagination: {
    Total: 0,
    PageIndex: 1,
    PageSize: 20
  },
  Sort: {
    Predicate: 'CreatedDate',
    Reverse: true
  },
  Search: {
    PredicateObject: {
      Keyword: '',
      Status: null,
      CreatedStart: null,
      CreatedEnd: null
    }
  }
});

// Options
const statusOptions = computed(() => ReconciliationStatusOptions);

// Methods
const handleSearch = async () => {
  searchModel.Pagination.PageIndex = 1;
  await loadReconciliations();
};

const handleReset = () => {
  searchModel.Search.PredicateObject.Keyword = '';
  searchModel.Search.PredicateObject.Status = null;
  searchModel.Search.PredicateObject.CreatedStart = null;
  searchModel.Search.PredicateObject.CreatedEnd = null;
  searchModel.Pagination.PageIndex = 1;
  loadReconciliations();
};

const handleSort = (field) => {
  if (searchModel.Sort.Predicate === field) {
    searchModel.Sort.Reverse = !searchModel.Sort.Reverse;
  } else {
    searchModel.Sort.Predicate = field;
    searchModel.Sort.Reverse = false;
  }
  loadReconciliations();
};

const handlePageChange = (page) => {
  searchModel.Pagination.PageIndex = page;
  loadReconciliations();
};

const handleExport = async () => {
  try {
    loading.value = true;
    const result = await reconciliationService.export(searchModel, ReconciliationType.ShippingFee);
    if (result) {
      toast.success('Xuất Excel thành công');
    }
  } catch (error) {
    console.error('Error exporting:', error);
    toast.error('Có lỗi xảy ra khi xuất Excel');
  } finally {
    loading.value = false;
  }
};

const loadReconciliations = async () => {
  try {
    loading.value = true;
    const result = await reconciliationService.search(searchModel, ReconciliationType.ShippingFee);
    reconciliations.value = result.items || [];
    searchModel.Pagination.Total = result.totalRecord || 0;
  } catch (error) {
    console.error('Error loading reconciliations:', error);
    toast.error('Có lỗi xảy ra khi tải danh sách đối soát');
  } finally {
    loading.value = false;
  }
};

const getStatusLabel = (status) => {
  return getReconciliationStatusLabel(status);
};

const getStatusBadgeClass = (status) => {
  return getReconciliationStatusClass(status);
};

// Debounced search
const debouncedSearch = debounce(handleSearch, 500);

onMounted(() => {
  loadReconciliations();
});
</script>

<style scoped>
.sortable {
  cursor: pointer;
  user-select: none;
}

.sortable:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

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

.badge {
  font-size: 0.75rem;
}

.btn-sm {
  padding: 0.25rem 0.5rem;
  font-size: 0.875rem;
}

.spinner-border {
  width: 2rem;
  height: 2rem;
}

.dataTables_info {
  padding-top: 0.75rem;
  color: #6c757d;
  font-size: 0.875rem;
}

.dataTables_paginate {
  text-align: right;
}
</style>
