<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</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</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 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>Khoảng thời gian</th>
                      <th class="text-center">Số đơn</th>
                      <th class="text-end">Tổng COD</th>
                      <th class="text-end">Tổng phí</th>
                      <th class="text-end">Tiền thực chuyển</th>
                      <th class="text-center">Trạng thái</th>
                      <th @click="handleSort('createdTime')" class="sortable text-center">
                        Ngày tạo
                        <i class="bx bx-sort ms-1"></i>
                      </th>
                      <th>Người tạo</th>
                      <th class="text-center">Thao tác</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="item in reconciliations" :key="item.Id">
                      <!-- Mã đối soát -->
                      <td>
                        <router-link :to="{ name: 'reconciliation-detail', params: { id: item.Id } }"
                          class="fw-semibold text-decoration-none">
                          {{ item.Code }}
                        </router-link>
                      </td>

                      <!-- Khách hàng -->
                      <td>
                        <div>
                          <div class="fw-semibold">{{ item.CustomerName }}</div>
                          <div class="text-muted small">
                            <i class="bx bx-phone me-1"></i>{{ item.CustomerPhone }}
                          </div>
                        </div>
                      </td>

                      <!-- Khoảng thời gian -->
                      <td>
                        <div class="text-muted small">
                          {{ formatDate(item.FromDate) }} - {{ formatDate(item.ToDate) }}
                        </div>
                      </td>

                      <!-- Số đơn -->
                      <td class="text-center">
                        <span class="badge bg-info">{{ item.OrderCount }}</span>
                      </td>

                      <!-- Tổng COD -->
                      <td class="text-end">
                        <span class="fw-semibold">{{ formatCurrency(item.TotalCodAmount) }}</span>
                      </td>

                      <!-- Tổng phí -->
                      <td class="text-end">
                        <span class="text-warning">{{ formatCurrency(item.TotalFeeAmount) }}</span>
                      </td>

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

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

                      <!-- Ngày tạo -->
                      <td class="text-center">
                        <span class="text-muted">{{ formatDateTime(item.CreatedTime) }}</span>
                      </td>

                      <!-- Người tạo -->
                      <td>
                        <span class="text-muted">{{ item.CreatedByUsername }}</span>
                      </td>

                      <!-- Thao tác -->
                      <td class="text-center">
                        <div class="dropdown">
                          <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button"
                            :id="'dropdown-' + item.Id" data-bs-toggle="dropdown">
                            <i class="bx bx-dots-horizontal-rounded"></i>
                          </button>
                          <ul class="dropdown-menu" :aria-labelledby="'dropdown-' + item.Id">
                            <li>
                              <router-link :to="{ name: 'reconciliation-detail', params: { id: item.Id } }"
                                class="dropdown-item">
                                <i class="bx bx-show me-2"></i>
                                Xem chi tiết
                              </router-link>
                            </li>
                            <li v-if="item.CanConfirmWithPermission">
                              <button class="dropdown-item" @click="confirmReconciliation(item)">
                                <i class="bx bx-check me-2"></i>
                                Xác nhận
                              </button>
                            </li>
                            <li v-if="item.CanTransferWithPermission">
                              <button class="dropdown-item" @click="showTransferModal(item)">
                                <i class="bx bx-transfer me-2"></i>
                                Cập nhật đã chuyển tiền
                              </button>
                            </li>
                            <li v-if="item.CanCancel">
                              <hr class="dropdown-divider" />
                              <button class="dropdown-item text-danger" @click="cancelReconciliation(item)">
                                <i class="bx bx-x me-2"></i>
                                Hủy đối soát
                              </button>
                            </li>
                          </ul>
                        </div>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>

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

    <!-- Transfer Dialog -->
    <LadaDialog :visible="modalControl.Transfer">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title">
            <i class="bx bx-transfer me-2"></i>
            Cập nhật đã chuyển tiền
          </h5>
          <button @click="closeTransferModal" type="button" class="close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
      </template>
      <template #body>
        <TransferReconciliationForm :reconciliation="selectedReconciliation" @cancel="closeTransferModal"
          @success="onTransferSuccess" />
      </template>
    </LadaDialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useToast } from 'vue-toastification';
import reconciliationService from '@/services/reconciliationService';
import { TransferReconciliationForm } from './components';
import {
  formatCurrency,
  formatDate,
  formatDateTime,
  debounce,
  getDefaultDateRange,
  dateToISOString
} from '@/infrastructure/utilities/reconciliationHelpers';
import {
  ReconciliationStatusOptions,
  getReconciliationStatusClass,
  canConfirmReconciliation,
  canMarkAsTransferred,
  canCancelReconciliation
} from '@/infrastructure/utilities/reconciliationConstants';

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

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

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

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

// Computed properties
const statusOptions = computed(() => ReconciliationStatusOptions);

// Methods
const loadReconciliations = async () => {
  try {
    loading.value = true;

    // Prepare search model
    const searchParams = { ...searchModel };
    searchParams.Pagination.Start = (searchParams.Pagination.PageIndex - 1) * searchParams.Pagination.PageSize;

    // Convert dates to ISO strings
    if (searchParams.Search.PredicateObject.CreatedStart) {
      var dateToISOStringStart = dateToISOString(searchParams.Search.PredicateObject.CreatedStart);

      searchParams.Search.PredicateObject.CreatedStart = dateToISOStringStart != "" ? dateToISOStringStart : null;

    }
    if (searchParams.Search.PredicateObject.CreatedEnd) {
      var dateToISOStringEnd = dateToISOString(searchParams.Search.PredicateObject.CreatedEnd);
      searchParams.Search.PredicateObject.CreatedEnd = dateToISOStringEnd != "" ? dateToISOStringEnd : null;
    }

    const result = await reconciliationService.search(searchParams);

    reconciliations.value = result.Items || [];
    searchModel.Pagination.Total = result.TotalRecord;
  } 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');
    reconciliations.value = [];
  } finally {
    loading.value = false;
  }
};

const handleSearch = () => {
  searchModel.Pagination.PageIndex = 1;
  ctrlPager.value.Refresh();
  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;
  }
  handleSearch();
};

const PageSizeChanged = (pageSize) => {
  searchModel.Pagination.PageSize = pageSize;
  searchModel.Pagination.PageIndex = 1;
  loadReconciliations();
};

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

const handleExport = async () => {
  try {
    loading.value = true;

    const exportParams = { ...searchModel };
    exportParams.IsExport = true;

    // Convert dates to ISO strings
    if (exportParams.Search.PredicateObject.CreatedStart) {
      exportParams.Search.PredicateObject.CreatedStart = dateToISOString(exportParams.Search.PredicateObject.CreatedStart);
    }
    if (exportParams.Search.PredicateObject.CreatedEnd) {
      exportParams.Search.PredicateObject.CreatedEnd = dateToISOString(exportParams.Search.PredicateObject.CreatedEnd);
    }

    const blob = await reconciliationService.export(exportParams);

    // Create download link
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `DanhSachDoiSoat_${new Date().toISOString().slice(0, 10)}.xlsx`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    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 confirmReconciliation = async (item) => {
  if (!confirm(`Bạn có chắc chắn muốn xác nhận đối soát ${item.Code}?`)) {
    return;
  }

  try {
    const result = await reconciliationService.confirm(item.Id);
    if (result && result.Result === 1) {
      toast.success('Xác nhận đối soát thành công');
      loadReconciliations();
    } else {
      toast.error(result?.Message || 'Có lỗi xảy ra khi xác nhận đối soát');
    }
  } catch (error) {
    console.error('Error confirming reconciliation:', error);
    toast.error('Có lỗi xảy ra khi xác nhận đối soát');
  }
};

const showTransferModal = (item) => {
  selectedReconciliation.value = item;
  modalControl.Transfer = true;
};

const closeTransferModal = () => {
  selectedReconciliation.value = null;
  modalControl.Transfer = false;
};

const onTransferSuccess = async () => {
  // Reload reconciliations to get updated status
  await loadReconciliations();
};

const cancelReconciliation = async (item) => {
  const reason = prompt('Nhập lý do hủy đối soát:');
  if (!reason) return;

  try {
    const result = await reconciliationService.cancel(item.Id, reason);
    if (result && result.Result === 1) {
      toast.success('Hủy đối soát thành công');
      loadReconciliations();
    } else {
      toast.error(result?.Message || 'Có lỗi xảy ra khi hủy đối soát');
    }
  } catch (error) {
    console.error('Error cancelling reconciliation:', error);
    toast.error('Có lỗi xảy ra khi hủy đối soát');
  }
};

// Debounced search for keyword input
const debouncedSearch = debounce(() => {
  handleSearch();
}, 500);

// Lifecycle
onMounted(() => {
  // Set default date range
  const defaultRange = getDefaultDateRange();
  searchModel.Search.PredicateObject.CreatedStart = new Date(defaultRange.fromDate);
  searchModel.Search.PredicateObject.CreatedEnd = new Date(defaultRange.toDate);

  // Load initial data
  loadReconciliations();
});
</script>

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

.sortable {
  cursor: pointer;
  user-select: none;
}

.sortable:hover {
  background-color: #f8f9fa;
}

.badge {
  font-size: 0.75rem;
}

.dropdown-toggle::after {
  display: none;
}

.spinner-border {
  width: 2rem;
  height: 2rem;
}
</style>
