<template>
  <div>
    <!-- Header -->
    <div class="breadcrumb-header justify-content-between">
      <div class="my-auto">
        <h4 class="page-title">Import sao kê ngân hàng</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">Import sao kê</li>
        </ol>
      </div>
      <router-link :to="{ name: 'bank-accounts' }" class="btn btn-secondary btn-sm">
        <i class="fas fa-arrow-left me-1"></i>
        Quay lại
      </router-link>
    </div>

    <div class="row row-sm">
      <!-- Import Form -->
      <div class="col-sm-12 col-md-12 col-lg-12 col-xl-12 grid-margin">
        <div class="card">
          <div class="card-header">
            <h5 class="mb-0">Thông tin import</h5>
          </div>
          <div class="card-body">
            <form @submit.prevent="onSubmit">
              <div class="row">
                <!-- Tài khoản ngân hàng -->
                <div class="col-lg-6 mb-3">
                  <label class="form-label required">Tài khoản ngân hàng</label>
                  <v-select v-model="formModel.BankAccountId" :options="bankAccountOptions"
                    :reduce="option => option.Id" label="AccountName" placeholder="Chọn tài khoản ngân hàng..."
                    :class="{ 'is-invalid': errors.BankAccountId }">
                    <template #option="{ AccountName, AccountNumber, BankName }">
                      <div>
                        <div class="fw-bold">{{ AccountName }}</div>
                        <small class="text-muted">{{ AccountNumber }} - {{ BankName }}</small>
                      </div>
                    </template>
                  </v-select>
                  <div v-if="errors.BankAccountId" class="invalid-feedback">
                    {{ errors.BankAccountId }}
                  </div>
                </div>



                <!-- File Excel -->
                <div class="col-lg-6 mb-3">
                  <label class="form-label required">File Excel sao kê</label>
                  <input type="file" ref="fileInput" @change="onFileSelected" class="form-control"
                    :class="{ 'is-invalid': errors.ExcelFile }" accept=".xlsx,.xls" required>
                  <div v-if="errors.ExcelFile" class="invalid-feedback">
                    {{ errors.ExcelFile }}
                  </div>
                  <div class="form-text">
                    Chỉ chấp nhận file Excel (.xlsx, .xls). Kích thước tối đa: 10MB
                  </div>
                </div>



                <!-- Options -->
                <div class="col-lg-12 mb-3">
                  <div class="row">
                    <div class="col-lg-4">
                      <div class="form-check">
                        <input class="form-check-input" type="checkbox" v-model="formModel.OverwriteExisting"
                          id="overwriteExisting">
                        <label class="form-check-label" for="overwriteExisting">
                          Ghi đè dữ liệu đã tồn tại
                        </label>
                      </div>
                    </div>
                    <div class="col-lg-4">
                      <div class="form-check">
                        <input class="form-check-input" type="checkbox" v-model="formModel.AutoCategorize"
                          id="autoCategorize">
                        <label class="form-check-label" for="autoCategorize">
                          Tự động phân loại giao dịch
                        </label>
                      </div>
                    </div>
                    <div class="col-lg-4">
                      <div class="form-check">
                        <input class="form-check-input" type="checkbox" v-model="formModel.UpdateAccountBalance"
                          id="updateAccountBalance">
                        <label class="form-check-label" for="updateAccountBalance">
                          Cập nhật số dư tài khoản
                        </label>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- Submit Button -->
              <div class="d-flex justify-content-end gap-2">
                <router-link :to="{ name: 'bank-accounts' }" class="btn btn-secondary">
                  Hủy
                </router-link>
                <button type="submit" class="btn btn-primary" :disabled="importing">
                  <span v-if="importing" class="spinner-border spinner-border-sm me-1"></span>
                  <i v-else class="fas fa-file-import me-1"></i>
                  {{ importing ? 'Đang import...' : 'Import' }}
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>

    <!-- Import Result -->
    <div v-if="importResult" class="col-sm-12 col-md-12 col-lg-12 col-xl-12 grid-margin">
      <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
          <h5 class="mb-0">Kết quả import</h5>
          <span :class="`badge bg-${importResult.Result === 1 ? 'success' : 'danger'} fs-6`">
            {{ importResult.Result === 1 ? 'Thành công' : 'Thất bại' }}
          </span>
        </div>
        <div class="card-body">
          <!-- Summary -->
          <div class="row mb-4">
            <div class="col-lg-3 col-md-6 mb-3">
              <div class="text-center">
                <div class="text-primary">
                  <i class="fas fa-file-alt fa-2x mb-2"></i>
                  <h6>Tổng số dòng</h6>
                  <h4>{{ importResult.TotalRows }}</h4>
                </div>
              </div>
            </div>
            <div class="col-lg-3 col-md-6 mb-3">
              <div class="text-center">
                <div class="text-success">
                  <i class="fas fa-check-circle fa-2x mb-2"></i>
                  <h6>Đã xử lý</h6>
                  <h4>{{ importResult.ProcessedRows }}</h4>
                </div>
              </div>
            </div>
            <div class="col-lg-3 col-md-6 mb-3">
              <div class="text-center">
                <div class="text-danger">
                  <i class="fas fa-times-circle fa-2x mb-2"></i>
                  <h6>Lỗi</h6>
                  <h4>{{ importResult.ErrorRows }}</h4>
                </div>
              </div>
            </div>
            <div class="col-lg-3 col-md-6 mb-3">
              <div class="text-center">
                <div class="text-warning">
                  <i class="fas fa-exclamation-circle fa-2x mb-2"></i>
                  <h6>Bỏ qua</h6>
                  <h4>{{ importResult.SkippedRows }}</h4>
                </div>
              </div>
            </div>
          </div>

          <!-- Additional Info -->
          <div class="row mb-3">
            <div class="col-lg-6">
              <strong>Thời gian xử lý:</strong> {{ importResult.ProcessingTimeMs }}ms
            </div>
            <div class="col-lg-6" v-if="importResult.FinalBalance">
              <strong>Số dư cuối:</strong> {{ formatCurrency(importResult.FinalBalance) }}đ
            </div>
          </div>

          <!-- Error Messages -->
          <div v-if="importResult.ErrorMessages && importResult.ErrorMessages.length > 0" class="mb-3">
            <h6 class="text-danger">Lỗi:</h6>
            <ul class="list-unstyled">
              <li v-for="error in importResult.ErrorMessages" :key="error" class="text-danger">
                <i class="fas fa-times-circle me-1"></i>
                {{ error }}
              </li>
            </ul>
          </div>

          <!-- Warning Messages -->
          <div v-if="importResult.WarningMessages && importResult.WarningMessages.length > 0" class="mb-3">
            <h6 class="text-warning">Cảnh báo:</h6>
            <ul class="list-unstyled">
              <li v-for="warning in importResult.WarningMessages" :key="warning" class="text-warning">
                <i class="fas fa-exclamation-triangle me-1"></i>
                {{ warning }}
              </li>
            </ul>
          </div>

          <!-- Actions -->
          <div class="d-flex gap-2">
            <router-link :to="{ name: 'bank-account-transactions', query: { importId: importResult.ImportId } }"
              class="btn btn-primary btn-sm">
              <i class="fas fa-list me-1"></i>
              Xem giao dịch đã import
            </router-link>
            <router-link :to="{ name: 'bank-account-import-history' }" class="btn btn-secondary btn-sm">
              <i class="fas fa-history me-1"></i>
              Xem lịch sử import
            </router-link>
          </div>
        </div>
      </div>
    </div>

    <!-- File Format Guide -->
    <div class="col-sm-12 col-md-12 col-lg-12 col-xl-12 grid-margin">
      <div class="card">
        <div class="card-header">
          <h5 class="mb-0">Hướng dẫn định dạng file</h5>
        </div>
        <div class="card-body">
          <div class="row">
            <div class="col-lg-6">
              <h6>Định dạng VPBank:</h6>
              <table class="table table-sm table-bordered">
                <thead>
                  <tr>
                    <th>Cột</th>
                    <th>Tên trường</th>
                    <th>Định dạng</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td>A</td>
                    <td>Số hóa đơn</td>
                    <td>Text</td>
                  </tr>
                  <tr>
                    <td>B</td>
                    <td>Ngày ghi nợ</td>
                    <td>dd/MM/yyyy</td>
                  </tr>
                  <tr>
                    <td>C</td>
                    <td>Số tiền ghi có</td>
                    <td>1.000.000</td>
                  </tr>
                  <tr>
                    <td>D</td>
                    <td>Số tiền ghi nợ</td>
                    <td>1.000.000</td>
                  </tr>
                  <tr>
                    <td>E</td>
                    <td>Nội dung</td>
                    <td>Text</td>
                  </tr>
                  <tr>
                    <td>F</td>
                    <td>Số dư tham chiếu</td>
                    <td>1.000.000</td>
                  </tr>
                  <tr>
                    <td>G</td>
                    <td>Thời gian giao dịch</td>
                    <td>dd/MM/yyyy HH:mm</td>
                  </tr>
                </tbody>
              </table>
            </div>
            <div class="col-lg-6">
              <h6>Định dạng Techcombank:</h6>
              <table class="table table-sm table-bordered">
                <thead>
                  <tr>
                    <th>Cột</th>
                    <th>Tên trường</th>
                    <th>Định dạng</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td>A</td>
                    <td>Ngày GD</td>
                    <td>dd/MM/yyyy</td>
                  </tr>
                  <tr>
                    <td>B</td>
                    <td>Mã GD</td>
                    <td>Text</td>
                  </tr>
                  <tr>
                    <td>C</td>
                    <td>Số tiền</td>
                    <td>-1,000,000</td>
                  </tr>
                  <tr>
                    <td>D</td>
                    <td>Số dư</td>
                    <td>1,000,000</td>
                  </tr>
                  <tr>
                    <td>E</td>
                    <td>Nội dung</td>
                    <td>Text</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useToast } from "vue-toastification";
import bankAccountService from '@/services/bankAccountService';
import { BankAccountUtils } from '@/infrastructure/constants/bankAccountConstants';

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

// Reactive data
const importing = ref(false);
const bankAccountOptions = ref([]);
const selectedFile = ref(null);
const fileInput = ref(null);
const importResult = ref(null);

const formModel = reactive({
  BankAccountId: null,
  ExcelFile: null,
  OverwriteExisting: false,
  AutoCategorize: true,
  UpdateAccountBalance: true
});

const errors = reactive({});



// Methods
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) {
      const account = accounts.find(a => a.Id == accountId);
      if (account) {
        formModel.BankAccountId = account.Id;
      }
    }
  } 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 onFileSelected = (event) => {
  const file = event.target.files[0];
  if (file) {
    // Validate file size (10MB)
    if (file.size > 10 * 1024 * 1024) {
      errors.ExcelFile = 'Kích thước file không được vượt quá 10MB';
      fileInput.value.value = '';
      return;
    }

    // Validate file type
    const allowedTypes = [
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'application/vnd.ms-excel'
    ];
    if (!allowedTypes.includes(file.type)) {
      errors.ExcelFile = 'Chỉ chấp nhận file Excel (.xlsx, .xls)';
      fileInput.value.value = '';
      return;
    }

    selectedFile.value = file;
    delete errors.ExcelFile;
  }
};

const validateForm = () => {
  Object.keys(errors).forEach(key => delete errors[key]);

  if (!formModel.BankAccountId) {
    errors.BankAccountId = 'Vui lòng chọn tài khoản ngân hàng';
  }



  if (!selectedFile.value) {
    errors.ExcelFile = 'Vui lòng chọn file Excel';
  }

  return Object.keys(errors).length === 0;
};

const onSubmit = async () => {
  if (!validateForm()) {
    toast.error('Vui lòng kiểm tra lại thông tin nhập');
    return;
  }

  importing.value = true;
  importResult.value = null;

  try {
    const formData = new FormData();
    formData.append('BankAccountId', formModel.BankAccountId);
    formData.append('ExcelFile', selectedFile.value);

    formData.append('OverwriteExisting', formModel.OverwriteExisting);
    formData.append('AutoCategorize', formModel.AutoCategorize);
    formData.append('UpdateAccountBalance', formModel.UpdateAccountBalance);

    const result = await bankAccountService.importStatement(formData);
    importResult.value = result;

    if (result.Result === 1) {
      toast.success(result.Message || 'Import sao kê thành công');
    } else {
      toast.error(result.Message || 'Có lỗi xảy ra khi import sao kê');
    }
  } catch (error) {
    toast.error('Có lỗi xảy ra khi import sao kê');
  } finally {
    importing.value = false;
  }
};

// Utility functions
const formatCurrency = BankAccountUtils.formatCurrency;

// Lifecycle
onMounted(() => {
  loadBankAccounts();
});
</script>

<style scoped>
.required::after {
  content: " *";
  color: #dc3545;
}

.table-sm th,
.table-sm td {
  padding: 0.25rem;
  font-size: 0.875rem;
}
</style>
