<template>
  <div>
    <!-- Breadcrumb -->
    <div class="breadcrumb-header justify-content-between">
      <div class="my-auto">
        <h4 class="page-title">Hóa đơn VAT điện tử</h4>
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="javascript:void(0);">Trang chủ</a></li>
          <li class="breadcrumb-item active" aria-current="page">Hóa đơn VAT</li>
        </ol>
      </div>
    </div>

    <!-- Sync Status Bar -->
    <div class="row row-sm mb-3">
      <div class="col-lg-12">
        <div class="card shadow-none mb-0">
          <div class="card-body py-3">
            <div class="d-flex flex-wrap align-items-center justify-content-between">
              <div class="d-flex align-items-center">
                <i class="fas fa-sync-alt me-2 text-primary"></i>
                <span v-if="syncInfo.HasSyncHistory">
                  <span
                    :class="['badge me-2', syncStatusBadgeClass]"
                  >{{ syncStatusText }}</span>
                  <span class="text-muted">{{ syncInfo.Message }}</span>
                  <span v-if="syncInfo.Status === 'Success'" class="text-muted ms-2">
                    (Thêm: {{ syncInfo.InsertedCount }}, Cập nhật: {{ syncInfo.UpdatedCount }})
                  </span>
                  <span v-if="syncInfo.Status === 'Failed' && syncInfo.ErrorMessage" class="text-danger ms-2">
                    — {{ syncInfo.ErrorMessage }}
                  </span>
                </span>
                <span v-else class="text-muted">Chưa có lịch sử đồng bộ nào</span>
              </div>
              <div class="d-flex gap-2 mt-1 mt-md-0">
                <button
                  type="button"
                  class="btn btn-outline-primary btn-sm"
                  @click="openSyncModal(1)"
                >
                  <i class="fas fa-cloud-upload-alt me-1"></i>Đồng bộ bán ra
                </button>
                <button
                  type="button"
                  class="btn btn-outline-success btn-sm"
                  @click="openSyncModal(2)"
                >
                  <i class="fas fa-cloud-download-alt me-1"></i>Đồng bộ mua vào
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Search Form -->
    <div class="row row-sm">
      <div class="col-sm-12 col-md-12 col-lg-12 col-xl-12 grid-margin">
        <div class="card card-search shadow-none mb-3">
          <form class="card-body" @submit.prevent="search">
            <div class="row">
              <div class="col-lg-4 col-md-6 mb-3">
                <label>Từ khóa</label>
                <input
                  type="text"
                  v-model="searchKeyword"
                  class="form-control"
                  placeholder="Số HĐ, tên/MST người bán, tên/MST người mua..."
                  @keyup.enter="search"
                >
              </div>
              <div class="col-lg-4 col-md-6 mb-3">
                <label>Thời gian</label>
                <VueDatePicker
                  ref="dateRangePicker"
                  v-model="dateRange"
                  :enable-time-picker="false"
                  range
                  multi-calendars
                  auto-apply
                  :format="formatDateRange"
                  @update:model-value="handleDate"
                  placeholder="Từ ngày - Đến ngày"
                >
                  <template #left-sidebar>
                    <DateRangeSidebar @change-date="onChangeDate"></DateRangeSidebar>
                  </template>
                </VueDatePicker>
              </div>
              <div class="col-lg-4 col-md-6 mb-3">
                <label>Tình trạng</label>
                <select class="form-select" v-model="selectedStatus">
                  <option :value="null">Tất cả</option>
                  <option :value="1">Hóa đơn mới</option>
                  <option :value="2">Hóa đơn thay thế</option>
                  <option :value="3">Hóa đơn điều chỉnh</option>
                  <option :value="4">HĐ đã bị thay thế</option>
                  <option :value="5">HĐ đã bị điều chỉnh</option>
                  <option :value="6">HĐ đã bị hủy</option>
                </select>
              </div>
            </div>
            <div class="row">
              <div class="col-lg-4 col-md-6 mb-3">
                <label>Chiều hóa đơn</label>
                <select class="form-select" v-model="selectedDirection">
                  <option :value="null">Tất cả</option>
                  <option :value="1">Bán ra</option>
                  <option :value="2">Mua vào</option>
                </select>
              </div>
              <div class="col-lg-4 col-md-6 mb-3">
                <label>KQ kiểm tra</label>
                <select class="form-select" v-model="selectedCheckResult">
                  <option :value="null">Tất cả</option>
                  <!-- Hóa đơn bán ra (0-8) -->
                  <template v-if="selectedDirection !== 2">
                    <option :value="0">CQ Thuế đã nhận</option>
                    <option :value="1">Đang kiểm tra ĐK cấp mã</option>
                    <option :value="2">CQT từ chối HĐ</option>
                    <option :value="3">HĐ đủ ĐK cấp mã</option>
                    <option :value="4">HĐ không đủ ĐK cấp mã</option>
                  </template>
                  <!-- Chung cho cả bán ra và mua vào -->
                  <option :value="5">Đã cấp mã HĐ</option>
                  <option :value="6">CQ Thuế đã nhận không mã</option>
                  <template v-if="selectedDirection !== 2">
                    <option :value="7">Đã kiểm tra định kỳ</option>
                  </template>
                  <option :value="8">CQ Thuế đã nhận HĐ từ MTT</option>
                </select>
              </div>
            </div>
            <div class="row">
              <div class="col-lg-4 col-md-6 mb-3">
                <label>MST người bán</label>
                <input
                  type="text"
                  v-model="sellerTaxCode"
                  class="form-control"
                  placeholder="Mã số thuế người bán..."
                >
              </div>
              <div class="col-lg-4 col-md-6 mb-3">
                <label>MST người mua</label>
                <input
                  type="text"
                  v-model="buyerTaxCode"
                  class="form-control"
                  placeholder="Mã số thuế người mua..."
                >
              </div>
              <div class="col-lg-4 col-md-6 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 class="ms-1">Tìm kiếm</span>
                </button>
                <button type="button" class="btn btn-secondary" @click="resetSearch">
                  <i class="fas fa-redo me-1"></i>Làm mới
                </button>
              </div>
            </div>
          </form>
        </div>

        <!-- Data Table -->
        <div class="card card-table shadow-none">
          <div class="card-body card-table-body p-0">
            <div class="table-responsive border-top mg-b-10">
              <table class="table table-vcenter mb-0" style="min-height:300px">
                <thead>
                  <tr>
                    <th class="min-width-1"><span>STT</span></th>
                    <th class="min-width-1"><span>Chiều HĐ</span></th>
                    <th class="min-width-2"><span>KQ kiểm tra</span></th>
                    <th class="min-width-1"><span>Mẫu số</span></th>
                    <th class="min-width-1"><span>Ký hiệu HĐ</span></th>
                    <th class="min-width-1"><span>Số HĐ</span></th>
                    <th class="min-width-2"><span>Ngày lập</span></th>
                    <th class="min-width-3"><span>Người bán</span></th>
                    <th class="min-width-3"><span>Người mua</span></th>
                    <th class="min-width-3 text-end"><span>Số tiền</span></th>
                    <th class="min-width-2"><span>Tình trạng</span></th>
                    <th class="min-width-2"><span>Ghi chú</span></th>
                  </tr>
                </thead>

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

                <!-- Empty -->
                <tbody v-if="!loading && items.length <= 0">
                  <tr>
                    <td colspan="12" class="tx-semibold text-center text-danger">
                      Không tìm thấy bản ghi nào!
                    </td>
                  </tr>
                </tbody>

                <!-- Data -->
                <tbody v-if="!loading && items.length > 0">
                  <tr v-for="(item, index) in items" :key="item.Id">
                    <td class="text-wrap align-top">{{ getRowNumber(index) }}</td>
                    <td class="text-wrap align-top">
                      <span :class="['badge', item.InvoiceDirection === 1 ? 'bg-primary' : 'bg-success']">{{ item.InvoiceDirectionName || (item.InvoiceDirection === 1 ? 'Bán ra' : 'Mua vào') }}</span>
                    </td>
                    <td class="text-wrap align-top">
                      <span v-if="item.InvoiceCheckResultName">{{ item.InvoiceCheckResultName }}</span>
                      <span v-else class="text-muted">-</span>
                    </td>
                    <td class="text-wrap align-top">{{ item.TemplateCode }}</td>
                    <td class="text-wrap align-top">{{ item.InvoiceSymbol }}</td>
                    <td class="text-wrap align-top">
                      <strong>{{ item.InvoiceNumber }}</strong>
                    </td>
                    <td class="text-wrap align-top">{{ formatDate(item.IssueDate) }}</td>
                    <td class="text-wrap align-top">
                      <div><strong>{{ item.SellerName }}</strong></div>
                      <div class="text-muted" style="font-size: 0.8rem;"><code>{{ item.SellerTaxCode }}</code></div>
                    </td>
                    <td class="text-wrap align-top">
                      <div><strong>{{ item.BuyerName }}</strong></div>
                      <div class="text-muted" style="font-size: 0.8rem;"><code>{{ item.BuyerTaxCode }}</code></div>
                    </td>
                    <td class="text-wrap align-top text-end">
                      <div><strong>{{ formatNumber(item.TotalAmount) }}</strong> <small class="text-muted">{{ item.Currency }}</small></div>
                      <div class="text-muted" style="font-size: 0.8rem;">Hàng: {{ formatNumber(item.AmountBeforeTax) }} | Thuế: {{ formatNumber(item.TaxAmount) }}</div>
                    </td>
                    <td class="text-wrap align-top">
                      <span :class="['badge', getInvoiceStatusBadge(item.Status)]">
                        {{ item.StatusName || getInvoiceStatusText(item.Status) }}
                      </span>
                    </td>
                    <td class="text-wrap align-top">{{ item.Note }}</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>

    <!-- Sync Modal -->
    <LadaDialog :visible="modalControl.SyncModal">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title">
            <i class="fas fa-cloud-download-alt me-2"></i>Đồng bộ hóa đơn
          </h5>
          <button @click="closeSyncModal" type="button" class="close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
      </template>
      <template #body>
        <div class="row">
          <div class="col-lg-12 mb-3">
            <label class="form-label">Chiều hóa đơn</label>
            <input type="text" class="form-control" :value="syncDirection === 1 ? 'Bán ra' : 'Mua vào'" readonly />
          </div>
          <div class="col-lg-12 mb-3">
            <label class="form-label">Khoảng thời gian <span class="text-danger">*</span></label>
            <VueDatePicker
              ref="syncDateRangePicker"
              v-model="syncDateRange"
              :enable-time-picker="false"
              range
              multi-calendars
              auto-apply
              :format="formatDateRange"
              placeholder="Từ ngày - Đến ngày"
            >
              <template #left-sidebar>
                <DateRangeSidebar @change-date="onChangeSyncDate"></DateRangeSidebar>
              </template>
            </VueDatePicker>
          </div>
          <div class="col-lg-12">
            <div class="d-flex flex-row-reverse">
              <button @click="closeSyncModal" type="button" class="btn btn-secondary mg-l-15">
                Hủy
              </button>
              <button @click="doSyncManual" type="button" class="btn btn-primary" :disabled="syncing">
                <span v-show="syncing" class="spinner-border spinner-border-sm me-2"></span>
                <i v-show="!syncing" class="fas fa-sync-alt me-2"></i>
                Đồng bộ
              </button>
            </div>
          </div>
        </div>
      </template>
    </LadaDialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue';
import moment from 'moment';
import vatInvoiceService from '@/services/vatInvoiceService';
import { useToast } from 'vue-toastification';
import DatepickerInstance from "@vuepic/vue-datepicker";
import { LadaDialog, DateRangeSidebar } from '@/components/index';

const toast = useToast();

//#region DATA
const loading = ref(false);
const syncing = ref(false);
const searchKeyword = ref('');
const sellerTaxCode = ref('');
const buyerTaxCode = ref('');
const selectedStatus = ref(null);
const selectedDirection = ref(null);
const selectedCheckResult = ref(null);
const dateRange = ref(null);
const dateRangePicker = ref(DatepickerInstance);
const items = reactive([]);
const ctrlPager = ref();

const searchModel = reactive({
  Pagination: {
    Total: 0,
    PageIndex: 1,
    PageSize: 15,
  },
  Sort: {
    Predicate: 'SyncTime',
    Reverse: true,
  },
  Search: {
    PredicateObject: {
      Keyword: '',
      FromDate: null,
      ToDate: null,
      SellerTaxCode: null,
      BuyerTaxCode: null,
      Status: null,
      InvoiceDirection: null,
      InvoiceCheckResult: null,
    },
  },
});

// Sync info
const syncInfo = reactive({
  HasSyncHistory: false,
  LastSyncTime: null,
  SyncDateRange: null,
  Status: null,
  InsertedCount: 0,
  UpdatedCount: 0,
  TotalCount: 0,
  DurationSeconds: 0,
  SyncType: null,
  ErrorMessage: null,
  Message: '',
});

// Sync modal
const modalControl = reactive({
  SyncModal: false,
});
const syncDateRange = ref(null);
const syncDateRangePicker = ref(DatepickerInstance);
const syncDirection = ref(1);
//#endregion

//#region COMPUTED
const syncStatusBadgeClass = computed(() => {
  switch (syncInfo.Status) {
    case 'Success': return 'bg-success';
    case 'Failed': return 'bg-danger';
    case 'InProgress': return 'bg-warning';
    default: return 'bg-secondary';
  }
});

const syncStatusText = computed(() => {
  switch (syncInfo.Status) {
    case 'Success': return '✅ Thành công';
    case 'Failed': return '❌ Thất bại';
    case 'InProgress': return '⏳ Đang xử lý';
    default: return syncInfo.Status || '';
  }
});

// Auto-reset InvoiceCheckResult khi đổi chiều hóa đơn
watch(selectedDirection, () => {
  selectedCheckResult.value = null;
});
//#endregion

//#region LIFECYCLE
onMounted(async () => {
  // Set default date range: current month
  const startOfMonth = moment().startOf('month').toDate();
  const endOfMonth = moment().endOf('month').toDate();
  dateRange.value = [startOfMonth, endOfMonth];


  await loadSyncInfo();
  await search();
});
//#endregion

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

function formatDate(value) {
  if (!value) return '';
  return moment(value).format('DD/MM/YYYY');
}

function formatDateRange(dates) {
  if (!dates || !Array.isArray(dates) || dates.length !== 2) return '';
  const start = moment(dates[0]).format('DD/MM/YYYY');
  const end = moment(dates[1]).format('DD/MM/YYYY');
  return `${start} - ${end}`;
}

function formatSingleDate(date) {
  if (!date) return '';
  return moment(date).format('DD/MM/YYYY');
}
//#endregion

//#region DATE RANGE
function handleDate(modelData) {
  if (modelData != null && Array.isArray(modelData) && modelData.length === 2) {
    // handled by v-model
  } else {
    dateRange.value = null;
  }
}

async function onChangeDate(newDates) {
  dateRange.value = newDates;
  dateRangePicker.value.closeMenu();
  handleDate(newDates);
}
//#endregion

//#region HELPERS
function getRowNumber(index) {
  return (searchModel.Pagination.PageIndex - 1) * searchModel.Pagination.PageSize + index + 1;
}

function getInvoiceStatusText(status) {
  switch (status) {
    case 1: return 'Hóa đơn mới';
    case 2: return 'HĐ thay thế';
    case 3: return 'HĐ điều chỉnh';
    case 4: return 'HĐ đã bị thay thế';
    case 5: return 'HĐ đã bị điều chỉnh';
    case 6: return 'HĐ đã bị hủy';
    default: return `#${status}`;
  }
}

function getInvoiceStatusBadge(status) {
  switch (status) {
    case 1: return 'bg-info';
    case 2: return 'bg-warning';
    case 3: return 'bg-primary';
    case 4: return 'bg-secondary';
    case 5: return 'bg-secondary';
    case 6: return 'bg-danger';
    default: return 'bg-secondary';
  }
}
//#endregion

//#region SEARCH
async function search() {
  searchModel.Pagination.PageIndex = 1;
  if (ctrlPager.value) {
    ctrlPager.value.Refresh();
  }
  await loadData();
}

async function loadData() {
  loading.value = true;
  try {
    // Update search model
    searchModel.Search.PredicateObject.Keyword = searchKeyword.value || null;
    searchModel.Search.PredicateObject.SellerTaxCode = sellerTaxCode.value || null;
    searchModel.Search.PredicateObject.BuyerTaxCode = buyerTaxCode.value || null;
    searchModel.Search.PredicateObject.Status = selectedStatus.value;
    searchModel.Search.PredicateObject.InvoiceDirection = selectedDirection.value;
    searchModel.Search.PredicateObject.InvoiceCheckResult = selectedCheckResult.value;

    if (dateRange.value && Array.isArray(dateRange.value) && dateRange.value.length === 2) {
      searchModel.Search.PredicateObject.FromDate = dateRange.value[0];
      searchModel.Search.PredicateObject.ToDate = dateRange.value[1];
    } else {
      searchModel.Search.PredicateObject.FromDate = null;
      searchModel.Search.PredicateObject.ToDate = null;
    }

    const result = await vatInvoiceService.search(searchModel);
    items.splice(0, items.length);
    if (result && result.Items && result.Items.length > 0) {
      result.Items.forEach(item => {
        items.push(item);
      });
    }
    searchModel.Pagination.Total = result?.TotalRecord || 0;
  } catch (error) {
    console.error('Error loading VAT invoices:', error);
    toast.error('Có lỗi xảy ra khi tải dữ liệu hóa đơn');
  } finally {
    loading.value = false;
  }
}

function resetSearch() {
  searchKeyword.value = '';
  sellerTaxCode.value = '';
  buyerTaxCode.value = '';
  selectedStatus.value = null;
  selectedDirection.value = null;
  selectedCheckResult.value = null;
  const startOfMonth = moment().startOf('month').toDate();
  const endOfMonth = moment().endOf('month').toDate();
  dateRange.value = [startOfMonth, endOfMonth];
  search();
}
//#endregion

//#region PAGINATION
function pageSizeChanged(pagesize) {
  searchModel.Pagination.PageSize = pagesize;
  searchModel.Pagination.PageIndex = 1;
  loadData();
}

function pageIndexChanged(pageIndex) {
  searchModel.Pagination.PageIndex = pageIndex;
  loadData();
}
//#endregion

//#region SYNC
async function loadSyncInfo() {
  try {
    const result = await vatInvoiceService.getLastSyncInfo();
    if (result) {
      Object.assign(syncInfo, result);
    }
  } catch (error) {
    console.error('Error loading sync info:', error);
  }
}

function openSyncModal(direction = 1) {
  syncDirection.value = direction;
  const yesterday = moment().subtract(1, 'days').startOf('day').toDate();
  const today = moment().endOf('day').toDate();
  syncDateRange.value = [yesterday, today];
  modalControl.SyncModal = true;
}

function onChangeSyncDate(newDates) {
  syncDateRange.value = newDates;
  syncDateRangePicker.value.closeMenu();
}

function closeSyncModal() {
  modalControl.SyncModal = false;
}

async function doSyncManual() {
  if (!syncDateRange.value || !Array.isArray(syncDateRange.value) || syncDateRange.value.length !== 2) {
    toast.error('Vui lòng chọn khoảng thời gian');
    return;
  }

  syncing.value = true;
  try {
    const result = await vatInvoiceService.syncManual({
      FromDate: syncDateRange.value[0],
      ToDate: syncDateRange.value[1],
      InvoiceDirection: syncDirection.value,
    });

    if (result && result.Result === 1) {
      toast.success(result.Message || 'Đồng bộ thành công');
      closeSyncModal();
      await loadSyncInfo();
      await search();
    } else {
      toast.error(result?.Message || 'Đồng bộ thất bại');
    }
  } catch (error) {
    console.error('Error syncing VAT invoices:', error);
    toast.error('Có lỗi xảy ra khi đồng bộ');
  } finally {
    syncing.value = false;
  }
}
//#endregion
</script>
