<template>
  <div>
    <!-- Breadcrumb Header -->
    <div class="breadcrumb-header justify-content-between">
      <div class="my-auto">
        <h4 class="page-title">Tạo đối soát mới</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);">Đối soát</a></li>
          <li class="breadcrumb-item"><a href="javascript:void(0);">Khách hàng cần đối soát</a></li>
          <li class="breadcrumb-item active" aria-current="page">Tạo đối soát mới</li>
        </ol>
      </div>
    </div>
    <div class="row row-sm">
      <!-- Customer Information Section -->
      <div class="col-sm-12 col-md-6 col-lg-6 col-xl-6 grid-margin">
        <div class="card shadow-none">
          <div class="card-header">
            <h5 class="card-title mb-0">
              <i class="fe fe-user me-2"></i>
              Thông tin khách hàng
            </h5>
          </div>
          <div class="card-body">
            <div v-if="customerLoading" class="text-center py-4">
              <span class="spinner-border spinner-border-sm"></span>
              <span class="ms-2">Đang tải thông tin khách hàng...</span>
            </div>
            <div v-else-if="customerInfo" class="row">
              <div class="col-md-4">
                <div class="mb-3">
                  <label class="form-label fw-semibold">Tên khách hàng</label>
                  <div class="form-control-plaintext">{{ customerInfo.FullName || 'Chưa có' }}</div>
                </div>
                <div class="mb-3">
                  <label class="form-label fw-semibold">Số điện thoại</label>
                  <div class="form-control-plaintext">{{ customerInfo.PhoneNumber || 'Chưa có' }}</div>
                </div>
              </div>
              <div class="col-md-4">
                <div class="mb-3">
                  <label class="form-label fw-semibold">Email</label>
                  <div class="form-control-plaintext">{{ customerInfo.Email || 'Chưa có' }}</div>
                </div>
                <div class="mb-3">
                  <label class="form-label fw-semibold">Địa chỉ</label>
                  <div class="form-control-plaintext">{{ customerInfo.Address || 'Chưa có' }}</div>
                </div>
              </div>
              <div class="col-md-4">
                <div class="mb-3">
                  <label class="form-label fw-semibold">Sale quản lý</label>
                  <div class="form-control-plaintext">{{ customerInfo.Manager?.FullName || 'Chưa có' }}</div>
                </div>
                <div class="mb-3">
                  <label class="form-label fw-semibold">Trạng thái</label>
                  <div class="form-control-plaintext">
                    <span :class="customerInfo.Status === 1 ? 'tag tag-green' : 'tag tag-red'">
                      {{ customerInfo.StatusStr || 'Chưa có' }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
            <div v-else class="text-center py-4 text-muted">
              Không tìm thấy thông tin khách hàng
            </div>
          </div>
        </div>
      </div>

      <!-- Bank Account Selection Section -->
      <div class="col-sm-12 col-md-6 col-lg-6 col-xl-6 grid-margin">
        <div class="card shadow-none">
          <div class="card-header">
            <h5 class="card-title mb-0">
              <i class="fe fe-credit-card me-2"></i>
              Chọn tài khoản ngân hàng
            </h5>
          </div>
          <div class="card-body">
            <div v-if="bankAccountsLoading" class="text-center py-4">
              <span class="spinner-border spinner-border-sm"></span>
              <span class="ms-2">Đang tải danh sách tài khoản ngân hàng...</span>
            </div>
            <div v-else-if="bankAccounts.length > 0">
              <div class="mb-3">
                <div class="d-flex justify-content-between align-items-center mb-2">
                  <label class="form-label fw-semibold mb-0">Chọn tài khoản ngân hàng</label>
                  <button type="button" class="btn btn-sm btn-outline-primary" @click="openCreateBankAccountModal">
                    <i class="fe fe-plus me-1"></i>
                    Tạo mới
                  </button>
                </div>
                <v-select :options="bankAccounts" :reduce="(account) => account" label="AccountNumber"
                  v-model="selectedBankAccount" @update:model-value="onBankAccountChange"
                  placeholder="Chọn tài khoản ngân hàng...">
                  <template #option="{ AccountNumber, AccountHolderName, BankName, IsDefault }">
                    <div class="d-flex justify-content-between align-items-center">
                      <div>
                        <div class="fw-semibold">{{ AccountNumber }}</div>
                        <div class="text-muted small">{{ AccountHolderName }} - {{ BankName }}</div>
                      </div>
                      <span v-if="IsDefault" class="tag tag-green">Mặc định</span>
                    </div>
                  </template>
                  <template #selected-option="{ AccountNumber, AccountHolderName, BankName, IsDefault }">
                    <div class="d-flex justify-content-between align-items-center">
                      <div>
                        <span class="fw-semibold">{{ AccountNumber }}</span>
                        <span class="text-muted ms-2">- {{ AccountHolderName }}</span>
                      </div>
                      <span v-if="IsDefault" class="tag tag-green ms-2">Mặc định</span>
                    </div>
                  </template>
                </v-select>
              </div>

              <!-- Hiển thị thông tin tài khoản đã chọn -->
              <div v-if="selectedBankAccount" class="row mt-3">
                <div class="col-md-4">
                  <div class="mb-3">
                    <label class="form-label fw-semibold">Số tài khoản</label>
                    <div class="form-control-plaintext">{{ selectedBankAccount.AccountNumber }}</div>
                  </div>
                  <div class="mb-3">
                    <label class="form-label fw-semibold">Tên chủ tài khoản</label>
                    <div class="form-control-plaintext">{{ selectedBankAccount.AccountHolderName }}</div>
                  </div>
                </div>
                <div class="col-md-4">
                  <div class="mb-3">
                    <label class="form-label fw-semibold">Ngân hàng</label>
                    <div class="form-control-plaintext">{{ selectedBankAccount.BankName }}</div>
                  </div>
                  <div class="mb-3">
                    <label class="form-label fw-semibold">Chi nhánh</label>
                    <div class="form-control-plaintext">{{ selectedBankAccount.BranchName || 'Chưa có' }}</div>
                  </div>
                </div>
                <div class="col-md-4">
                  <div class="mb-3">
                    <label class="form-label fw-semibold">Mã ngân hàng</label>
                    <div class="form-control-plaintext">{{ selectedBankAccount.BankCode || 'Chưa có' }}</div>
                  </div>
                  <div class="mb-3">
                    <label class="form-label fw-semibold">Địa chỉ chi nhánh</label>
                    <div class="form-control-plaintext">{{ selectedBankAccount.BranchAddress || 'Chưa có' }}</div>
                  </div>
                </div>
              </div>
            </div>
            <div v-else class="text-center py-4">
              <div class="text-muted mb-3">
                <i class="fe fe-credit-card me-2"></i>
                Khách hàng chưa có tài khoản ngân hàng nào
              </div>
              <button type="button" class="btn btn-primary" @click="openCreateBankAccountModal">
                <i class="fe fe-plus me-2"></i>
                Tạo tài khoản ngân hàng mới
              </button>
            </div>
          </div>
        </div>
      </div>

      <div class="col-12">
        <form @submit.prevent="handleSubmit">

          <!-- Upload và Thông tin phiếu - 2 cột -->
          <div class="row" v-if="selectedOrdersSummary.netAmount < 0">
            <!-- Upload phiếu chuyển khoản -->
            <div class="col-sm-12 col-md-6 col-lg-6 col-xl-6 grid-margin">
              <div class="card shadow-none">
                <div class="card-header">
                  <h5 class="card-title mb-0">
                    <i class="fe fe-upload me-2"></i>
                    Upload phiếu chuyển khoản
                  </h5>
                </div>
                <div class="card-body">
                  <div class="upload-area text-center p-4 border border-dashed rounded" 
                       :class="{ 'border-danger': uploadError }"
                       @click="triggerFileInput"
                       @dragover.prevent="onDragOver"
                       @dragleave.prevent="onDragLeave"
                       @drop.prevent="onDrop">
                    <div v-if="!uploadedFile">
                      <i class="fe fe-image" style="font-size: 48px; color: #6c757d;"></i>
                      <p class="mt-3 mb-0">Kéo và thả hoặc click để chọn ảnh</p>
                      <p class="text-muted small">Hỗ trợ: JPG, PNG (Tối đa 5MB)</p>
                    </div>
                    <div v-else>
                      <img :src="uploadedFilePreview" alt="Preview" class="img-fluid rounded" style="max-height: 200px;">
                      <div class="mt-2">
                        <button type="button" class="btn btn-sm btn-outline-danger" @click.stop="removeFile">
                          <i class="fe fe-trash-2 me-1"></i>
                          Xóa
                        </button>
                      </div>
                    </div>
                  </div>
                  <input 
                    ref="fileInput" 
                    type="file" 
                    accept="image/*" 
                    @change="onFileChange" 
                    style="display: none;">
                  <div v-if="uploadError" class="invalid-feedback d-block mt-2">
                    {{ uploadError }}
                  </div>
                </div>
              </div>
            </div>

            <!-- Thông tin phiếu đối soát -->
            <div class="col-sm-12 col-md-6 col-lg-6 col-xl-6 grid-margin">
              <div class="card shadow-none">
                <div class="card-header">
                  <h5 class="card-title mb-0">
                    <i class="fe fe-info me-2"></i>
                    Thông tin phiếu đối soát
                  </h5>
                </div>
                <div class="card-body">
                  <div class="alert alert-warning mb-3">
                    <i class="fe fe-alert-circle me-2"></i>
                    Khách hàng cần chuyển tiền cho công ty
                  </div>
                  <div class="row">
                    <div class="col-12 mb-3">
                      <label class="form-label fw-semibold">Ghi chú chuyển khoản</label>
                      <textarea 
                        v-model="formData.transferInfo" 
                        class="form-control" 
                        rows="3"
                        placeholder="Nhập ghi chú về việc chuyển khoản (nếu có)..."></textarea>
                    </div>
                    <div class="col-12 mb-3">
                      <label class="form-label fw-semibold">Ngày chuyển khoản</label>
                      <input 
                        type="date" 
                        v-model="formData.transferDate" 
                        class="form-control"
                        :max="new Date().toISOString().split('T')[0]">
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- Orders List -->
          <div class="card mb-4" v-if="orders.length > 0">
            <div class="card-header d-flex justify-content-between align-items-center">
              <h5 class="card-title mb-0">
                <i class="bx bx-list-ul me-2"></i>
                Danh sách đơn hàng ({{ orders.length }})
              </h5>
              <div>
                <button type="button" class="btn btn-sm btn-outline-primary me-2" @click="selectAllOrders">
                  <i class="bx bx-check-square me-1"></i>
                  Chọn tất cả
                </button>
                <button type="button" class="btn btn-sm btn-outline-secondary" @click="deselectAllOrders">
                  <i class="bx bx-square me-1"></i>
                  Bỏ chọn tất cả
                </button>
              </div>
            </div>
            <div class="card-body">
              <!-- Selected orders summary -->
              <div class="alert alert-success mb-3" v-if="selectedOrdersSummary.count > 0">
                <div class="row text-center">
                  <div class="col-md-3">
                    <div class="fw-semibold">{{ selectedOrdersSummary.count }}</div>
                    <div class="small">Đơn đã chọn</div>
                  </div>
                  <div class="col-md-3">
                    <div class="fw-semibold">{{ formatCurrency(selectedOrdersSummary.totalCod) }}</div>
                    <div class="small">Tổng COD</div>
                  </div>
                  <div class="col-md-3">
                    <div class="fw-semibold">{{ formatCurrency(selectedOrdersSummary.totalFee) }}</div>
                    <div class="small">Tổng phí</div>
                  </div>
                  <div class="col-md-3">
                    <div class="fw-semibold text-success">{{ formatCurrency(selectedOrdersSummary.netAmount) }}</div>
                    <div class="small">Tiền thực chuyển</div>
                  </div>
                </div>
              </div>

              <!-- Orders table -->
              <div class="table-responsive">
                <table class="table table-hover align-middle">
                  <thead class="table-light">
                    <tr>
                      <th width="50">
                        <input type="checkbox" class="form-check-input" :checked="allOrdersSelected"
                          @change="toggleAllOrders" />
                      </th>
                      <th>Mã đơn</th>
                      <th>Ngày tạo</th>
                      <th class="text-end">Tiền COD</th>
                      <th class="text-end">Phí dịch vụ</th>
                      <th class="text-end">Tiền thực</th>
                      <th>Trạng thái COD</th>
                      <th>Người nhận</th>
                      <th>Địa chỉ giao</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="order in orders" :key="order.Id">
                      <td>
                        <input type="checkbox" class="form-check-input" :value="order.Id" v-model="formData.orderIds"
                          :disabled="!order.CanReconcile" />
                      </td>
                      <td>
                        <div class="fw-semibold">
                          <router-link :to="{ name: 'orderTrack', params: { code: order.Code } }" target="_blank">
                            {{ order.Code }}
                          </router-link>

                        </div>
                        <div class="text-muted small" v-if="order.PartnerCode">
                          {{ order.PartnerCode }}
                        </div>
                        <div class="text-muted small" v-if="!order.CanReconcile">
                          <i class="text-warning">Không thể đối soát</i>
                        </div>
                      </td>
                      <td>
                        <span class="text-muted">{{ formatDate(order.CreatedTime) }}</span>
                      </td>
                      <td class="text-end">
                        <span class="fw-semibold">{{ formatCurrency(order.CodAmount) }}</span>
                      </td>
                      <td class="text-end">
                        <span class="text-warning">{{ formatCurrency(order.ServiceFee) }}</span>
                      </td>
                      <td class="text-end">
                        <span class="fw-semibold text-success">{{ formatCurrency(order.NetAmount) }}</span>
                      </td>
                      <td>
                        <span class="badge" :class="order.CanReconcile ? 'bg-success' : 'bg-warning'">
                          {{ order.CodStageStr }}
                        </span>
                      </td>
                      <td>
                        <div>{{ order.ReceiverName }}</div>
                        <div class="text-muted small">{{ order.ReceiverPhone }}</div>
                      </td>
                      <td>
                        <span class="text-muted small">{{ order.DeliveryAddress }}</span>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>

          <!-- Action buttons -->
          <div class="card">
            <div class="card-body">
              <div class="d-flex justify-content-between">
                <button type="button" class="btn btn-outline-secondary" @click="handleCancel" :disabled="submitting">
                  <i class="bx bx-x me-1"></i>
                  Hủy
                </button>

                <div>
                  <button type="button" class="btn btn-outline-primary me-2" @click="loadOrders"
                    :disabled="!canLoadOrders || submitting">
                    <i class="bx bx-refresh me-1"></i>
                    Tải đơn hàng
                  </button>
                  <button type="submit" class="btn btn-primary" :disabled="!canSubmit || submitting">
                    <span v-if="submitting" class="spinner-border spinner-border-sm me-2"></span>
                    <i v-else class="bx bx-check me-1"></i>
                    {{ submitting ? 'Đang tạo...' : 'Tạo đối soát' }}
                  </button>
                </div>
              </div>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>

  <!-- Modal tạo tài khoản ngân hàng -->
  <LadaDialog :visible="showCreateBankAccountModal && formData.customerId">
    <template #header>
      <div class="modal-header">
        <h5 class="modal-title">
          <i class="fe fe-credit-card me-2"></i>
          Tạo tài khoản ngân hàng mới
        </h5>
        <button @click="closeCreateBankAccountModal" type="button" class="close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
    </template>
    <template #body>
      <CreateOrUpdateBankAccount v-if="formData.customerId" :id="0" :customerId="formData.customerId"
        @cancel="closeCreateBankAccountModal" />
    </template>
  </LadaDialog>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useToast } from 'vue-toastification';
import reconciliationService from '@/services/reconciliationService';
import customerService from '@/services/customerService';
import customerBankAccountService from '@/services/customerBankAccountService';
import CreateOrUpdateBankAccount from '@/views/crm/customer/detail/components/CreateOrUpdateBankAccount.vue';
import {
  formatCurrency,
  formatDate,
  getDefaultDateRange,
  dateToISOString,
  calculateTotalCodAmount,
  calculateTotalFeeAmount,
  calculateNetAmount
} from '@/infrastructure/utilities/reconciliationHelpers';

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

// Reactive data
const submitting = ref(false);
const orders = ref([]);
const customerInfo = ref(null);
const customerLoading = ref(false);
const bankAccounts = ref([]);
const bankAccountsLoading = ref(false);
const selectedBankAccount = ref(null);
const showCreateBankAccountModal = ref(false);
const uploadedFile = ref(null);
const uploadedFilePreview = ref(null);
const uploadError = ref('');
const fileInput = ref(null);

const formData = reactive({
  customerId: null,
  fromDate: null,
  toDate: null,
  orderIds: [],
  note: '',
  bankAccountNumber: '',
  bankAccountHolderName: '',
  bankCode: '',
  bankName: '',
  bankBranchName: '',
  bankBranchAddress: '',
  transferInfo: '',
  transferDate: null,
  autoConfirm: false,
});

const errors = reactive({
  fromDate: '',
  toDate: '',
  bankAccountNumber: '',
  bankAccountHolderName: '',
});

// Computed properties
const canLoadOrders = computed(() => {
  return formData.customerId;
});

const canSubmit = computed(() => {
  return canLoadOrders.value &&
    formData.orderIds.length > 0 &&
    formData.bankAccountNumber &&
    formData.bankAccountHolderName &&
    !submitting.value;
});

const selectedOrders = computed(() => {
  return orders.value.filter(order => formData.orderIds.includes(order.Id));
});

const selectedOrdersSummary = computed(() => {
  const selected = selectedOrders.value;
  const totalCod = calculateTotalCodAmount(selected);
  const totalFee = calculateTotalFeeAmount(selected);
  const netAmount = calculateNetAmount(totalCod, totalFee);

  return {
    count: selected.length,
    totalCod,
    totalFee,
    netAmount
  };
});

const allOrdersSelected = computed(() => {
  const reconcilableOrders = orders.value.filter(order => order.CanReconcile);
  return reconcilableOrders.length > 0 && formData.orderIds.length === reconcilableOrders.length;
});

// Methods
const validateForm = () => {
  // Reset errors
  Object.keys(errors).forEach(key => errors[key] = '');

  let isValid = true;

  // Validate dates
  if (!formData.fromDate) {
    errors.fromDate = 'Vui lòng chọn từ ngày';
    isValid = false;
  }

  if (!formData.toDate) {
    errors.toDate = 'Vui lòng chọn đến ngày';
    isValid = false;
  }

  if (formData.fromDate && formData.toDate && formData.fromDate >= formData.toDate) {
    errors.toDate = 'Đến ngày phải lớn hơn từ ngày';
    isValid = false;
  }

  // Validate bank info
  if (!formData.bankAccountNumber) {
    errors.bankAccountNumber = 'Vui lòng nhập số tài khoản';
    isValid = false;
  }

  if (!formData.bankAccountHolderName) {
    errors.bankAccountHolderName = 'Vui lòng nhập tên chủ tài khoản';
    isValid = false;
  }

  return isValid;
};

const loadCustomerInfo = async (customerId) => {
  try {
    customerLoading.value = true;
    const result = await customerService.getById(parseInt(customerId));
    customerInfo.value = result;
  } catch (error) {
    console.error('Error loading customer info:', error);
    toast.error('Có lỗi xảy ra khi tải thông tin khách hàng');
  } finally {
    customerLoading.value = false;
  }
};

const loadBankAccounts = async (customerId) => {
  try {
    bankAccountsLoading.value = true;
    const result = await customerBankAccountService.getByCustomerId(parseInt(customerId));
    bankAccounts.value = result || [];

    // Tự động chọn tài khoản mặc định
    const defaultAccount = bankAccounts.value.find(account => account.IsDefault);
    if (defaultAccount) {
      selectedBankAccount.value = defaultAccount;
      updateFormWithBankAccount(defaultAccount);
    } else if (bankAccounts.value.length > 0) {
      // Nếu không có tài khoản mặc định, chọn tài khoản đầu tiên
      selectedBankAccount.value = bankAccounts.value[0];
      updateFormWithBankAccount(bankAccounts.value[0]);
    }
  } catch (error) {
    console.error('Error loading bank accounts:', error);
    toast.error('Có lỗi xảy ra khi tải danh sách tài khoản ngân hàng');
  } finally {
    bankAccountsLoading.value = false;
  }
};

const updateFormWithBankAccount = (account) => {
  if (account) {
    formData.bankAccountNumber = account.AccountNumber;
    formData.bankAccountHolderName = account.AccountHolderName;
    formData.bankCode = account.BankCode;
    formData.bankName = account.BankName;
    formData.bankBranchName = account.BranchName || '';
    formData.bankBranchAddress = account.BranchAddress || '';
  }
};

const onBankAccountChange = (account) => {
  selectedBankAccount.value = account;
  updateFormWithBankAccount(account);
};

const openCreateBankAccountModal = () => {
  if (!formData.customerId) {
    toast.error('Không tìm thấy thông tin khách hàng');
    return;
  }
  showCreateBankAccountModal.value = true;
};

const closeCreateBankAccountModal = async () => {
  showCreateBankAccountModal.value = false;

  // Reload danh sách tài khoản ngân hàng để cập nhật danh sách mới
  await loadBankAccounts(formData.customerId);
};

const initializeCustomer = async (customerId) => {
  // Gán customerId vào formData
  formData.customerId = parseInt(customerId);

  // Load thông tin khách hàng và tài khoản ngân hàng song song
  await Promise.all([
    loadCustomerInfo(customerId),
    loadBankAccounts(customerId)
  ]);

  // Tự động load đơn hàng nếu đã có đủ thông tin
  if (canLoadOrders.value) {
    loadOrders();
  }
};

const loadOrders = async () => {
  if (!canLoadOrders.value) return;

  try {
    const searchModel = {
      pagination: {
        from: 0,
        pageIndex: 1,
        pageSize: 1000, // Lấy tất cả đơn hàng
        total: 0,
        totalPages: 0,
        totalItemCount: 0,
        number: 0,
        numberOfPages: 0
      },
      search: {
        predicateObject: {
          CustomerId: formData.customerId,
          Keyword: ""
        }
      },
      sort: {
        predicate: "CreatedTime",
        reverse: true
      },
      isExport: false
    };

    const result = await reconciliationService.getReconciliableOrders(searchModel);
    orders.value = result.Items || [];

    // Auto-select all orders that can be reconciled
    formData.orderIds = orders.value
      .filter(order => order.CanReconcile)
      .map(order => order.Id);

    if (orders.value.length === 0) {
      toast.warning('Không có đơn hàng nào có thể đối soát trong khoảng thời gian này');
    } else {
      // toast.success(`Đã tải ${orders.value.length} đơn hàng có thể đối soát`);
    }
  } catch (error) {
    console.error('Error loading orders:', error);
    toast.error('Có lỗi xảy ra khi tải danh sách đơn hàng');
    orders.value = [];
    formData.orderIds = [];
  }
};



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

  if (formData.orderIds.length === 0) {
    toast.error('Vui lòng tải và chọn đơn hàng cần đối soát');
    return;
  }

  try {
    submitting.value = true;

    const submitData = {
      customerId: formData.customerId,
      fromDate: dateToISOString(formData.fromDate),
      toDate: dateToISOString(formData.toDate),
      orderIds: formData.orderIds,
      note: formData.note,
      bankAccountNumber: formData.bankAccountNumber,
      bankAccountHolderName: formData.bankAccountHolderName,
      bankCode: formData.bankCode,
      bankName: formData.bankName,
      bankBranchName: formData.bankBranchName,
      bankBranchAddress: formData.bankBranchAddress,
      transferInfo: formData.transferInfo,
      autoConfirm: formData.autoConfirm,
    };

    const result = await reconciliationService.create(submitData);

    if (result && result.Result === 1) {
      toast.success(result.Message || 'Tạo đối soát thành công');
      router.push({ name: 'reconciliation-list' });
    } else {
      toast.error(result?.Message || 'Có lỗi xảy ra khi tạo đối soát');
    }
  } catch (error) {
    console.error('Error creating reconciliation:', error);
    toast.error('Có lỗi xảy ra khi tạo đối soát');
  } finally {
    submitting.value = false;
  }
};

const handleCancel = () => {
  router.push({ name: 'reconciliation-management', query: { tab: 'customers' } });
};

const selectAllOrders = () => {
  formData.orderIds = orders.value
    .filter(order => order.CanReconcile)
    .map(order => order.Id);
};

const deselectAllOrders = () => {
  formData.orderIds = [];
};

const toggleAllOrders = () => {
  if (allOrdersSelected.value) {
    deselectAllOrders();
  } else {
    selectAllOrders();
  }
};

// File upload methods
const triggerFileInput = () => {
  if (fileInput.value) {
    fileInput.value.click();
  }
};

const validateFile = (file) => {
  uploadError.value = '';
  
  // Check file type
  const validTypes = ['image/jpeg', 'image/jpg', 'image/png'];
  if (!validTypes.includes(file.type)) {
    uploadError.value = 'Chỉ hỗ trợ file ảnh định dạng JPG, PNG';
    return false;
  }
  
  // Check file size (5MB)
  const maxSize = 5 * 1024 * 1024;
  if (file.size > maxSize) {
    uploadError.value = 'Kích thước file không được vượt quá 5MB';
    return false;
  }
  
  return true;
};

const onFileChange = (event) => {
  const file = event.target.files[0];
  if (file && validateFile(file)) {
    uploadedFile.value = file;
    
    // Create preview
    const reader = new FileReader();
    reader.onload = (e) => {
      uploadedFilePreview.value = e.target.result;
    };
    reader.readAsDataURL(file);
  }
};

const removeFile = () => {
  uploadedFile.value = null;
  uploadedFilePreview.value = null;
  uploadError.value = '';
  if (fileInput.value) {
    fileInput.value.value = '';
  }
};

const onDragOver = (event) => {
  event.currentTarget.classList.add('border-primary');
};

const onDragLeave = (event) => {
  event.currentTarget.classList.remove('border-primary');
};

const onDrop = (event) => {
  event.currentTarget.classList.remove('border-primary');
  const file = event.dataTransfer.files[0];
  if (file && validateFile(file)) {
    uploadedFile.value = file;
    
    // Create preview
    const reader = new FileReader();
    reader.onload = (e) => {
      uploadedFilePreview.value = e.target.result;
    };
    reader.readAsDataURL(file);
  }
};

// Lifecycle
onMounted(() => {
  // Set default date range
  const defaultRange = getDefaultDateRange();
  formData.fromDate = new Date(defaultRange.fromDate);
  formData.toDate = new Date(defaultRange.toDate);

  // Initialize customer if customerId is provided
  const customerId = route.params.customerId;
  if (customerId) {
    initializeCustomer(customerId);
  }
});


</script>

<style scoped>
.card-title {
  color: #495057;
}

.alert-info {
  background-color: #e7f3ff;
  border-color: #b8daff;
  color: #004085;
}

.form-check-input:checked {
  background-color: #0d6efd;
  border-color: #0d6efd;
}

.spinner-border-sm {
  width: 1rem;
  height: 1rem;
}

.tag {
  display: inline-block;
  padding: 0.25rem 0.5rem;
  font-size: 0.75rem;
  font-weight: 500;
  line-height: 1;
  text-align: center;
  white-space: nowrap;
  vertical-align: baseline;
  border-radius: 0.25rem;
}

.tag-green {
  color: #fff;
  background-color: #198754;
}

.tag-red {
  color: #fff;
  background-color: #dc3545;
}

.is-invalid {
  border-color: #dc3545;
}

.invalid-feedback {
  display: block;
}

.upload-area {
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: #f8f9fa;
}

.upload-area:hover {
  background-color: #e9ecef;
  border-color: #0d6efd !important;
}

.border-dashed {
  border-style: dashed !important;
  border-width: 2px !important;
}

.upload-area.border-primary {
  background-color: #e7f3ff;
  border-color: #0d6efd !important;
}
</style>
