<template>
  <div>
    <!-- 1. Breadcrumb Header -->
    <div class="breadcrumb-header justify-content-between">
      <div class="my-auto">
        <h4 class="page-title">Lịch sử import sao kê</h4>
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="javascript:void(0);">Trang chủ</a></li>
          <li class="breadcrumb-item"><a href="javascript:void(0);">Tài chính</a></li>
          <li class="breadcrumb-item">
            <router-link :to="{ name: 'bank-accounts' }">Quản lý tài khoản ngân hàng</router-link>
          </li>
          <li class="breadcrumb-item active" aria-current="page">Lịch sử import</li>
        </ol>
      </div>
    </div>

    <!-- 2. Main Content Container -->
    <div class="row row-sm">
      <div class="col-sm-12 col-md-12 col-lg-12 col-xl-12 grid-margin">

        <!-- 3. Search Form Card -->
        <div class="card card-search shadow-none">
          <form class="card-body" @submit.prevent="search">
            <div class="row">
              <div class="col-lg-3 col-md-4 mb-3">
                <label>Từ khóa</label>
                <input type="text" v-model="searchModel.Search.PredicateObject.Keyword" class="form-control"
                  placeholder="Tên file, tên tài khoản..." />
              </div>
              <div class="col-lg-3 col-md-4 mb-3">
                <label>Tài khoản ngân hàng</label>
                <v-select v-model="searchModel.Search.PredicateObject.BankAccountId" :options="bankAccountOptions"
                  :reduce="option => option.Id" label="AccountName" placeholder="Chọn tài khoản..." :clearable="true">
                  <template #option="{ AccountName, AccountNumber, BankName }">
                    <div>
                      <div class="fw-bold">{{ AccountName }}</div>
                      <small class="text-muted">{{ AccountNumber }} - {{ BankName }}</small>
                    </div>
                  </template>
                  <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-4 mb-3">
                <label>Ngân hàng</label>
                <v-select v-model="searchModel.Search.PredicateObject.BankCode" :options="bankOptions"
                  :reduce="option => option.Id" label="Name" placeholder="Chọn ngân hàng..." :clearable="true">
                  <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-4 mb-3">
                <label>Trạng thái import</label>
                <v-select v-model="searchModel.Search.PredicateObject.ImportStatus" :options="importStatusOptions"
                  :reduce="option => option.Id" label="Name" placeholder="Chọn trạng thái..." :clearable="true">
                  <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-4 mb-3">
                <label>Ngày import</label>
                <VueDatePicker ref="importDatePicker" v-model="importDate" :enable-time-picker="false" range
                  multi-calendars auto-apply :format="format" @update:model-value="handleImportDate">
                  <template #left-sidebar>
                    <DateRangeSidebar @change-date="onChangeImportDate"></DateRangeSidebar>
                  </template>
                </VueDatePicker>
              </div>
            </div>

            <!-- Search Button -->
            <div class="row">
              <div class="col-lg mb-3">
                <button type="submit" class="btn btn-dark" :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" @click="resetSearch" class="btn btn-secondary ms-2">
                  <i class="fe fe-refresh-cw"></i>
                  <span>Làm mới</span>
                </button>
              </div>
            </div>
          </form>
        </div>

        <!-- 4. Data Table Card -->
        <div class="card card-table shadow-none">
          <div class="card-body card-table-body">
            <!-- Action Buttons -->
            <div class="d-flex flex-row justify-content-between mg-b-10">
              <router-link :to="{ name: 'bank-account-import-statement' }"
                class="btn btn-outline-primary mx-2 button-icon mb-1">
                <i class="fe fe-plus me-2"></i>Import mới
              </router-link>
            </div>

            <!-- Table -->
            <div class="table-responsive border-top mg-b-10">
              <table class="table table-vcenter mb-0" style="min-height:300px">
                <thead>
                  <tr>
                    <th class="wd-lg-12p min-width-2"><span>Thời gian import</span></th>
                    <th class="wd-lg-12p min-width-2"><span>File</span></th>
                    <th class="wd-lg-12p min-width-2"><span>Tài khoản</span></th>
                    <th class="wd-lg-8p"><span>Kết quả</span></th>
                    <th class="wd-lg-8p"><span>Thống kê</span></th>
                    <th class="wd-lg-8p"><span>Tỷ lệ thành công</span></th>
                    <th class="wd-lg-8p"><span>Người import</span></th>
                    <th class="wd-lg-8p"></th>
                  </tr>
                </thead>

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

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

                <!-- Data Rows -->
                <tbody v-if="!loading && searchResult.Items && searchResult.Items.length > 0">
                  <tr v-for="item in searchResult.Items" :key="item.Id">
                    <td class="text-wrap align-top">
                      <div>{{ formatDateTime(item.CreatedTime) }}</div>
                      <small class="text-muted">
                        Thời gian xử lý: {{ item.ProcessDuration }}
                      </small>
                    </td>
                    <td class="text-wrap align-top">
                      <div class="fw-bold">{{ item.OriginalFileName }}</div>
                      <small class="text-muted">{{ item.FileSize }}</small>
                    </td>
                    <td class="text-wrap align-top">
                      <div class="fw-bold">{{ item.BankAccountName }}</div>
                      <small class="text-muted">{{ item.BankAccountNumber }}</small>
                      <small class="text-muted d-block">{{ item.BankName }}</small>
                    </td>
                    <td class="align-top">
                      <span :class="`badge bg-${getImportStatusColor(item.ImportStatus)} mb-1`">
                        {{ item.ImportStatus }}
                      </span>
                      <div v-if="item.ErrorMessage" class="text-danger small">
                        {{ item.ErrorMessage }}
                      </div>
                    </td>
                    <td class="align-top">
                      <div class="small">
                        <div class="text-primary">Tổng: {{ item.TotalRows }}</div>
                        <div class="text-success">Thành công: {{ item.ProcessedRows }}</div>
                        <div class="text-danger">Lỗi: {{ item.ErrorRows }}</div>
                        <div class="text-warning">Bỏ qua: {{ item.SkippedRows }}</div>
                        <div class="text-info">Trùng: {{ item.DuplicateRows }}</div>
                      </div>
                    </td>
                    <td class="align-top">
                      <div class="d-flex align-items-center">
                        <div class="progress flex-grow-1 me-2" style="height: 8px;">
                          <div class="progress-bar"
                            :class="`bg-${item.SuccessRate >= 90 ? 'success' : item.SuccessRate >= 70 ? 'warning' : 'danger'}`"
                            :style="`width: ${item.SuccessRate}%`"></div>
                        </div>
                        <span class="small fw-bold">{{ item.SuccessRate }}%</span>
                      </div>
                    </td>
                    <td class="align-top">
                      <div>{{ item.ImportedByUserName }}</div>
                    </td>
                    <td class="align-top pt-2">
                      <!-- Action Dropdown -->
                      <button type="button" data-bs-toggle="dropdown"
                        class="mb-1 mt-1 mr-1 btn btn-light dropdown-toggle btn-sm" aria-expanded="false">
                        <i class="fas fa-cog"></i> Quản lý
                      </button>
                      <div class="dropdown-menu dropdown-menu-arrow">
                        <router-link :to="{ name: 'bank-account-transactions', query: { importId: item.Id } }"
                          class="dropdown-item" href="javascript:void(0);">
                          <i class="fe fe-list"></i>
                          <span class="mg-l-6">Xem giao dịch</span>
                        </router-link>
                        <a @click="viewDetails(item)" class="dropdown-item" href="javascript:void(0);">
                          <i class="fe fe-eye"></i>
                          <span class="mg-l-6">Xem chi tiết</span>
                        </a>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

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

        <!-- 5. Modals -->
        <LadaDialog :visible="modalControl.ViewDetails">
          <template #header>
            <div class="modal-header">
              <h5 class="modal-title">Chi tiết import</h5>
              <button @click="closeModal" type="button" class="close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
          </template>
          <template #body>
            <div class="modal-body" v-if="selectedImport">
              <div class="row">
                <div class="col-lg-6">
                  <h6>Thông tin file:</h6>
                  <table class="table table-borderless table-sm">
                    <tbody>
                      <tr>
                        <td class="fw-bold" width="40%">Tên file:</td>
                        <td>{{ selectedImport.OriginalFileName }}</td>
                      </tr>
                      <tr>
                        <td class="fw-bold">Kích thước:</td>
                        <td>{{ selectedImport.FileSize }}</td>
                      </tr>
                      <tr>
                        <td class="fw-bold">Ngân hàng:</td>
                        <td>{{ selectedImport.BankName }}</td>
                      </tr>
                      <tr>
                        <td class="fw-bold">Tài khoản:</td>
                        <td>{{ selectedImport.BankAccountName }}</td>
                      </tr>
                    </tbody>
                  </table>
                </div>
                <div class="col-lg-6">
                  <h6>Thông tin xử lý:</h6>
                  <table class="table table-borderless table-sm">
                    <tbody>
                      <tr>
                        <td class="fw-bold" width="40%">Thời gian bắt đầu:</td>
                        <td>{{ formatDateTime(selectedImport.ProcessStartTime) }}</td>
                      </tr>
                      <tr>
                        <td class="fw-bold">Thời gian kết thúc:</td>
                        <td>{{ formatDateTime(selectedImport.ProcessEndTime) }}</td>
                      </tr>
                      <tr>
                        <td class="fw-bold">Thời gian xử lý:</td>
                        <td>{{ selectedImport.ProcessDuration }}</td>
                      </tr>
                      <tr>
                        <td class="fw-bold">Ghi đè dữ liệu:</td>
                        <td>
                          <span :class="`badge ${selectedImport.OverwriteExisting ? 'bg-warning' : 'bg-secondary'}`">
                            {{ selectedImport.OverwriteExisting ? 'Có' : 'Không' }}
                          </span>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>

              <div class="row">
                <div class="col-lg-12">
                  <h6>Khoảng thời gian dữ liệu:</h6>
                  <p>
                    Từ {{ formatDate(selectedImport.DataFromDate) }}
                    đến {{ formatDate(selectedImport.DataToDate) }}
                  </p>
                </div>
              </div>
            </div>
          </template>
          <template #footer>
            <div class="modal-footer">
              <button @click="closeModal" type="button" class="btn btn-secondary">
                Đóng
              </button>
              <router-link v-if="selectedImport"
                :to="{ name: 'bank-account-transactions', query: { importId: selectedImport.Id } }"
                class="btn btn-primary" @click="closeModal">
                <i class="fe fe-list me-1"></i>
                Xem giao dịch
              </router-link>
            </div>
          </template>
        </LadaDialog>
      </div>
    </div>
  </div>
</template>

<script setup>
//#region Imports
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useToast } from "vue-toastification";
import bankAccountService from '@/services/bankAccountService';
import {
  BankList,
  ImportStatusList,
  BankAccountUtils
} from '@/infrastructure/constants/bankAccountConstants';
import DatepickerInstance from "@vuepic/vue-datepicker";
import { DateRangeSidebar } from '@/components/index';
//#endregion

//#region Composables
const route = useRoute();
const router = useRouter();
const toast = useToast();
//#endregion

//#region Reactive data
const loading = ref(false);
const bankAccountOptions = ref([]);
const selectedImport = ref(null);
const ctrlPager = ref(null);

// Date picker
const importDate = ref();
const importDatePicker = ref(DatepickerInstance);

const searchModel = reactive({
  Pagination: {
    PageIndex: 1,
    PageSize: 25,
    Total: 0
  },
  Sort: {
    Predicate: 'CreatedTime',
    Reverse: true
  },
  Search: {
    PredicateObject: {
      Keyword: '',
      BankAccountId: null,
      BankCode: null,
      ImportStatus: null,
      ImportDateFrom: null,
      ImportDateTo: null,
      ImportedByUserId: null
    }
  }
});

const searchResult = reactive({
  Items: [],
  TotalRecord: 0,
  NumberOfPages: 0
});
//#endregion

//#region Modals
const modalControl = reactive({
  ViewDetails: false
});
//#endregion

//#region Options
const bankOptions = BankList;
const importStatusOptions = ImportStatusList;
//#endregion

//#region Actions
const loadBankAccounts = async () => {
  try {
    const accounts = await bankAccountService.getActiveAccounts();
    bankAccountOptions.value = accounts;

    // Auto-select account if provided in query
    const accountId = route.query.accountId;
    if (accountId) {
      searchModel.Search.PredicateObject.BankAccountId = parseInt(accountId);
    }
  } catch (error) {
    toast.error('Có lỗi xảy ra khi tải danh sách tài khoản ngân hàng');
  }
};

const viewDetails = (importItem) => {
  selectedImport.value = importItem;
  modalControl.ViewDetails = true;
};

const closeModal = () => {
  modalControl.ViewDetails = false;
};
//#endregion

//#region SEARCH
const search = async () => {
  loading.value = true;
  try {
    // Convert dates to ISO format
    const searchParams = { ...searchModel };
    if (searchParams.Search.PredicateObject.ImportDateFrom) {
      searchParams.Search.PredicateObject.ImportDateFrom =
        new Date(searchParams.Search.PredicateObject.ImportDateFrom).toISOString();
    }
    if (searchParams.Search.PredicateObject.ImportDateTo) {
      searchParams.Search.PredicateObject.ImportDateTo =
        new Date(searchParams.Search.PredicateObject.ImportDateTo).toISOString();
    }

    const result = await bankAccountService.searchImportHistory(searchParams);
    Object.assign(searchResult, result);
  } catch (error) {
    toast.error('Có lỗi xảy ra khi tìm kiếm lịch sử import');
  } finally {
    loading.value = false;
  }
};

const resetSearch = () => {
  searchModel.Search.PredicateObject = {
    Keyword: '',
    BankAccountId: null,
    BankCode: null,
    ImportStatus: null,
    ImportDateFrom: null,
    ImportDateTo: null,
    ImportedByUserId: null
  };
  importDate.value = null;
  searchModel.Pagination.PageIndex = 1;
  ctrlPager.value.Refresh();
  loadData();
};

const loadData = () => {
  search();
};

// Pagination
const PageSizeChanged = (pagesize) => {
  searchModel.Pagination.PageSize = pagesize;
  searchModel.Pagination.PageIndex = 1;
  loadData();
};

const PageIndexChanged = (pageIndex) => {
  searchModel.Pagination.PageIndex = pageIndex;
  loadData();
};
//#endregion

//#region Utility functions
const getImportStatusColor = (status) => {
  const statusItem = ImportStatusList.find(s => s.Name === status);
  return statusItem ? statusItem.Color : 'secondary';
};

const formatDateTime = (dateString) => {
  if (!dateString) return 'Chưa có thông tin';
  return new Date(dateString).toLocaleString('vi-VN');
};

const formatDate = (dateString) => {
  if (!dateString) return 'Chưa có thông tin';
  return new Date(dateString).toLocaleDateString('vi-VN');
};

// Date range functions
const format = (dates) => {
  if (!dates || !dates[0] || !dates[1]) return '';
  let start = dates[0];
  let 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 handleImportDate = (modelData) => {
  if (modelData != null && modelData.length === 2) {
    searchModel.Search.PredicateObject.ImportDateFrom = modelData[0];
    searchModel.Search.PredicateObject.ImportDateTo = modelData[1];
  } else {
    searchModel.Search.PredicateObject.ImportDateFrom = null;
    searchModel.Search.PredicateObject.ImportDateTo = null;
  }
};

const onChangeImportDate = (newDates) => {
  importDate.value = newDates;
  importDatePicker.value.closeMenu();
  handleImportDate(newDates);
};
//#endregion

//#region Lifecycle
onMounted(() => {
  loadBankAccounts().then(() => {
    loadData();
  });
});
//#endregion
</script>

<style scoped>
.card-search {
  border: 1px solid #e9ecef;
  background-color: #f8f9fa;
}

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

.table-borderless td {
  border: none;
  padding: 0.25rem 0;
}

.btn-group-sm .btn {
  padding: 0.25rem 0.5rem;
}

.progress {
  background-color: #e9ecef;
}
</style>
