<template>
  <div>
    <!-- Breadcrumb Header -->
    <div class="breadcrumb-header justify-content-between">
      <div class="my-auto">
        <h4 class="page-title">Chi tiết đối soát khách hàng</h4>
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="javascript:void(0);">Trang chủ</a></li>
          <li class="breadcrumb-item"><router-link to="/doi-soat/khach-hang">Đối soát khách hàng</router-link></li>
          <li class="breadcrumb-item active" aria-current="page">Chi tiết</li>
        </ol>
      </div>
      <div class="d-flex my-xl-auto right-content">
        <button type="button" class="btn btn-outline-secondary" @click="goBack">
          <i class="fe fe-arrow-left me-1"></i>
          Quay lại
        </button>
      </div>
    </div>

    <div class="row row-sm">
      <div class="col-12">
        <!-- Customer Info & Wizard Steps Combined Card -->
        <div class="card mb-3" v-if="customerInfo">
          <div class="card-body">
            <div class="row align-items-center">
              <!-- Customer Info Column -->
              <div class="col-lg-6">
                <div class="customer-profile d-flex align-items-center">
                  <div class="customer-avatar me-3">
                    <i class="fe fe-user"></i>
                  </div>
                  <div>
                    <h5 class="mb-1">
                      <router-link :to="{ name: 'crm-customer-detail', params: { id: customerId } }"
                        class="text-primary text-decoration-none" target="_blank">
                        {{ customerInfo.CustomerName }}
                        <i class="fe fe-external-link ms-1 tx-12"></i>
                      </router-link>
                    </h5>
                    <div class="text-muted">
                      <span v-if="customerInfo.CustomerCode" class="badge bg-light text-dark me-2">
                        {{ customerInfo.CustomerCode }}
                      </span>
                      <i class="fe fe-phone me-1"></i>{{ customerInfo.CustomerPhone }}
                    </div>
                    <div class="text-muted tx-12 mt-1" v-if="customerInfo.CustomerEmail">
                      <i class="fe fe-mail me-1"></i>{{ customerInfo.CustomerEmail }}
                    </div>
                  </div>
                </div>
              </div>

              <!-- Wizard Steps Column -->
              <div class="col-lg-6">
                <div class="wizard-steps">
                  <div class="step" :class="{ active: currentStep === 1, completed: currentStep > 1 }">
                    <div class="step-number">1</div>
                    <div class="step-title">Chọn đơn hàng</div>
                  </div>
                  <div class="step-line" :class="{ active: currentStep > 1 }"></div>
                  <div class="step" :class="{ active: currentStep === 2, completed: currentStep > 2 }">
                    <div class="step-number">2</div>
                    <div class="step-title">Thanh toán</div>
                  </div>
                  <div class="step-line" :class="{ active: currentStep > 2 }"></div>
                  <div class="step" :class="{ active: currentStep === 3 }">
                    <div class="step-number">3</div>
                    <div class="step-title">Xác nhận</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Step 1: Select Orders -->
        <div v-if="currentStep === 1">
          <!-- Summary Cards -->
          <div class="row mb-3" v-if="!loading && orders.length > 0">
            <div class="col-md-3">
              <div class="card summary-card bg-primary-gradient text-white">
                <div class="card-body py-3">
                  <div class="d-flex align-items-center justify-content-between">
                    <div>
                      <h6 class="mb-1 text-white-50">Đơn đã chọn</h6>
                      <h3 class="mb-0 fw-bold">{{ selectedSummary.totalOrders }} / {{ orders.length }}</h3>
                    </div>
                    <div class="summary-icon">
                      <i class="fe fe-check-square"></i>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-md-3">
              <div class="card summary-card bg-info-gradient text-white">
                <div class="card-body py-3">
                  <div class="d-flex align-items-center justify-content-between">
                    <div>
                      <h6 class="mb-1 text-white-50">Tổng tiền COD</h6>
                      <h3 class="mb-0 fw-bold">{{ formatCurrencyShort(selectedSummary.totalCodAmount) }}</h3>
                    </div>
                    <div class="summary-icon">
                      <i class="fe fe-dollar-sign"></i>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-md-3">
              <div class="card summary-card bg-warning-gradient text-white">
                <div class="card-body py-3">
                  <div class="d-flex align-items-center justify-content-between">
                    <div>
                      <h6 class="mb-1 text-white-50">Tổng phí</h6>
                      <h3 class="mb-0 fw-bold">{{ formatCurrencyShort(selectedSummary.totalFeeAmount) }}</h3>
                    </div>
                    <div class="summary-icon">
                      <i class="fe fe-percent"></i>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="col-md-3">
              <div class="card summary-card" :class="reconciliationType.cardClass">
                <div class="card-body py-3">
                  <div class="d-flex align-items-center justify-content-between">
                    <div>
                      <h6 class="mb-1 text-white-50">{{ reconciliationType.label }}</h6>
                      <h3 class="mb-0 fw-bold">{{ formatCurrencyShort(Math.abs(selectedSummary.netAmount)) }}</h3>
                    </div>
                    <div class="summary-icon">
                      <i :class="reconciliationType.icon"></i>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- Orders Table -->
          <div class="card card-table shadow-none">
            <div class="card-header d-flex justify-content-between align-items-center">
              <h6 class="mb-0">
                <i class="fe fe-list me-2"></i>
                Chọn đơn hàng cần đối soát
                <span class="badge bg-primary ms-2" v-if="selectedOrders.length > 0">
                  Đã chọn {{ selectedOrders.length }}/{{ orders.length }}
                </span>
              </h6>
              <div class="d-flex align-items-center" v-if="!loading && orders.length > 0">
                <button type="button" class="btn btn-sm btn-outline-secondary me-2" @click="selectAllOrders"
                  v-if="!isAllSelected">
                  <i class="fe fe-check-square me-1"></i>Chọn tất cả
                </button>
                <button type="button" class="btn btn-sm btn-outline-secondary me-2" @click="deselectAllOrders" v-else>
                  <i class="fe fe-square me-1"></i>Bỏ chọn
                </button>
                <button type="button" class="btn btn-sm btn-outline-primary me-2" @click="loadOrders"
                  :disabled="loading">
                  <i class="fe fe-refresh-cw"></i>
                </button>
                <button type="button" class="btn btn-sm btn-outline-success" @click="handleExportExcel"
                  :disabled="loading || exporting || orders.length === 0">
                  <span v-if="exporting" class="spinner-border spinner-border-sm me-1"></span>
                  <i v-else class="fe fe-download me-1"></i>
                  Export Excel
                </button>
              </div>
            </div>
            <div class="card-body card-table-body">
              <div class="table-responsive border-top orders-table-container">
                <table class="table table-vcenter table-hover mb-0" style="min-height:300px">
                  <thead>
                    <tr>
                      <th class="wd-lg-3p min-width-1 text-center">
                        <div class="form-check">
                          <input class="form-check-input" type="checkbox" :checked="isAllSelected"
                            @change="toggleSelectAll" id="selectAllCheckbox">
                        </div>
                      </th>
                      <th class="wd-lg-15p min-width-1"><span>Mã đơn hàng</span></th>
                      <th class="wd-lg-20p min-width-1"><span>Thông tin tài chính</span></th>
                      <th class="wd-lg-10p min-width-1 text-center"><span>Ngày giao</span></th>
                      <th class="wd-lg-20p min-width-1"><span>Người nhận</span></th>
                      <th class="wd-lg-15p min-width-1"><span>Ghi chú</span></th>
                    </tr>
                  </thead>
                  <tbody v-if="loading">
                    <tr>
                      <td colspan="6" class="tx-semibold text-center text-default py-5">
                        <span class="spinner-border spinner-border-sm me-2"></span>
                        <span>Đang tải dữ liệu...</span>
                      </td>
                    </tr>
                  </tbody>
                  <tbody v-if="!loading && orders.length <= 0">
                    <tr>
                      <td colspan="6" class="tx-semibold text-center text-muted py-5">
                        <i class="fe fe-inbox fs-3 d-block mb-2"></i>
                        Không có đơn hàng nào có thể đối soát!
                      </td>
                    </tr>
                  </tbody>
                  <tbody v-if="!loading && orders.length > 0" class="tx-13">
                    <tr v-for="order in orders" :key="order.OrderId" class="order-row"
                      :class="{ 'selected-row': isOrderSelected(order.OrderId) }">
                      <!-- Checkbox -->
                      <td class="align-middle text-center">
                        <div class="form-check d-flex justify-content-center">
                          <input class="form-check-input" type="checkbox" :checked="isOrderSelected(order.OrderId)"
                            @change="toggleOrderSelection(order.OrderId)">
                        </div>
                      </td>
                      <!-- Mã đơn hàng + Trạng thái -->
                      <td class="align-middle">
                        <div class="order-info">
                          <!-- Mã đơn hàng -->
                          <div class="order-code fw-semibold mb-1">
                            <router-link :to="{ name: 'orderTrack', params: { code: order.OrderCode } }" target="_blank"
                              class="text-primary">
                              {{ order.OrderCode }}
                            </router-link>
                          </div>
                          <!-- Mã đối tác -->
                          <div class="text-muted tx-11 mb-1" v-if="order.PartnerCode">
                            <i class="fe fe-tag me-1"></i>{{ order.PartnerCode }}
                          </div>
                          <!-- Trạng thái -->
                          <div class="status-badges">
                            <span class="tag me-1" :class="order.OrderStatusCssClass || 'tag-info'">
                              {{ order.OrderStatus || '-' }}
                            </span>
                            <span class="tag" :class="order.PhysicalStatusCssClass || 'tag-info'">
                              {{ order.PhysicalStatus || '-' }}
                            </span>
                          </div>
                        </div>
                      </td>

                      <!-- Thông tin tài chính -->
                      <td class="align-middle">
                        <div class="financial-info">
                          <!-- Tiền COD -->
                          <div class="mb-1">
                            <span class="text-muted tx-11">Tiền COD:</span>
                            <span class="fw-semibold ms-1"
                              :class="order.AppliedCodAmount > 0 ? 'text-info' : 'text-muted'">
                              {{ formatCurrency(order.AppliedCodAmount) }}
                            </span>
                          </div>
                          <!-- Phí vận chuyển -->
                          <div class="mb-1">
                            <span class="text-muted tx-11">Phí VC:</span>
                            <span class="text-warning fw-semibold ms-1">{{ formatCurrency(order.AppliedFeeAmount)
                            }}</span>
                            <span class="text-muted tx-11 ms-1" v-if="order.ShippingFee">
                              (VCVC: {{ formatCurrency(order.ShippingFee) }})
                            </span>
                            <span class="text-muted tx-11 ms-1" v-if="order.ChargeWeight > 0">
                              - {{ order.ChargeWeight }} kg
                            </span>
                          </div>
                          <!-- Tiền ròng -->
                          <div>
                            <span class="text-muted tx-11">Tiền ròng:</span>
                            <span class="fw-bold ms-1" :class="order.NetAmount >= 0 ? 'text-success' : 'text-danger'">
                              {{ formatCurrency(order.NetAmount) }}
                            </span>
                          </div>
                        </div>
                      </td>

                      <!-- Ngày giao -->
                      <td class="text-center align-middle">
                        <span v-if="order.DeliveredDate">{{ formatDate(order.DeliveredDate) }}</span>
                        <span v-else class="text-muted">-</span>
                      </td>

                      <!-- Người nhận -->
                      <td class="align-middle">
                        <div class="receiver-info">
                          <div class="fw-medium">{{ order.ReceiverName }}</div>
                          <div class="text-muted tx-12">
                            <i class="fe fe-phone me-1"></i>{{ order.ReceiverPhone }}
                          </div>
                          <div class="text-muted tx-11 text-truncate" style="max-width: 200px;"
                            :title="order.DeliveryAddress">
                            <i class="fe fe-map-pin me-1"></i>{{ order.DeliveryAddress }}
                          </div>
                        </div>
                      </td>

                      <!-- Ghi chú -->
                      <td class="align-middle">
                        <span class="text-muted tx-12" v-if="order.Note">{{ order.Note }}</span>
                        <span class="text-muted tx-12" v-else>-</span>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
            <div class="card-footer" v-if="!loading && orders.length > 0">
              <div class="d-flex justify-content-end">
                <button type="button" class="btn btn-primary-gradient" @click="goToStep2"
                  :disabled="selectedOrders.length === 0">
                  Tiếp tục
                  <i class="fe fe-arrow-right ms-1"></i>
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- Step 2: Payment Method -->
        <div v-if="currentStep === 2">
          <!-- Reconciliation Type Info -->
          <div class="card mb-3">
            <div class="card-body">
              <div class="row">
                <div class="col-lg-6">
                  <!-- Header showing type -->
                  <div class="reconciliation-type-header mb-3 p-3 rounded-3" :class="reconciliationType.bgClass">
                    <div class="d-flex align-items-center justify-content-between">
                      <div class="d-flex align-items-center">
                        <div class="type-icon me-3">
                          <i :class="reconciliationType.icon" class="fs-3"></i>
                        </div>
                        <div>
                          <h5 class="mb-1" :class="reconciliationType.textClass">{{ reconciliationType.title }}</h5>
                          <p class="mb-0 tx-13">{{ reconciliationType.description }}</p>
                        </div>
                      </div>
                      <div class="text-end">
                        <div class="tx-12 text-muted">Số tiền</div>
                        <h4 class="mb-0 fw-bold" :class="reconciliationType.textClass">{{
                          formatCurrency(Math.abs(selectedSummary.netAmount)) }}</h4>
                      </div>
                    </div>
                  </div>

                  <div v-if="isNegativeReconciliation" class="alert alert-danger border-0 mb-3">
                    <div class="d-flex align-items-start">
                      <i class="fe fe-alert-triangle me-2 mt-1"></i>
                      <div>
                        <strong>Khách hàng cần chuyển tiền cho công ty</strong>
                        <p class="mb-0 tx-13">Sau khi khách hàng chuyển tiền, hãy upload ảnh phiếu chuyển khoản để
                          xác nhận.</p>
                      </div>
                    </div>
                  </div>
                  <div v-if="isPositiveReconciliation" class="alert alert-success border-0 mb-3">
                    <div class="d-flex align-items-start">
                      <i class="fe fe-check-circle me-2 mt-1"></i>
                      <div>
                        <strong>Công ty cần thanh toán cho khách hàng</strong>
                        <p class="mb-0 tx-13">Chọn hoặc xác nhận tài khoản ngân hàng của khách hàng để nhận tiền.</p>
                      </div>
                    </div>
                  </div>

                </div>
                <div class="col-lg-6">
                  <!-- NEGATIVE: Customer owes company - Upload transfer receipt -->
                  <div v-if="isNegativeReconciliation" class="reconciliation-action-section">
                    <!-- Alert và Form upload/thông tin - 2 cột -->
                    <div class="slip-info-section p-4 border rounded-3 bg-light" style="height: calc(100% - 0px);">

                      <label class="form-label">
                        <i class="fe fe-upload me-2"></i>
                        Upload phiếu chuyển khoản
                      </label>

                      <div class="upload-zone mb-3" @click="triggerFileUpload" @dragover.prevent="onDragOver"
                        @dragleave="onDragLeave" @drop.prevent="onFileDrop" :class="{ 'drag-over': isDragging }">
                        <input type="file" ref="fileInput" @change="onFileSelected" accept="image/*" class="d-none" />
                        <div v-if="!uploadedFile" class="text-center py-4">
                          <i class="fe fe-image fs-1 text-muted mb-2 d-block"></i>
                          <p class="mb-1 fw-medium">Kéo thả hoặc click để chọn ảnh</p>
                          <p class="mb-0 tx-12 text-muted">Hỗ trợ: JPG, PNG, GIF (Tối đa 5MB)</p>
                        </div>
                        <div v-else class="text-center py-3">
                          <img :src="uploadedFilePreview" class="uploaded-preview mb-2" />
                          <p class="mb-1 fw-medium text-truncate">{{ uploadedFile.name }}</p>
                          <button type="button" class="btn btn-sm btn-outline-danger" @click.stop="removeUploadedFile">
                            <i class="fe fe-x me-1"></i>Xóa
                          </button>
                        </div>
                      </div>
                      <div class="form-group mb-3">
                        <label class="form-label">Ghi chú chuyển khoản</label>
                        <textarea v-model="transferNote" class="form-control" rows="4"
                          placeholder="Nhập ghi chú về việc chuyển khoản (nếu có)..."></textarea>
                      </div>
                      <div class="form-group mb-0">
                        <label class="form-label">Ngày chuyển khoản</label>
                        <input type="date" v-model="transferDate" class="form-control"
                          :max="new Date().toISOString().split('T')[0]" />
                      </div>
                    </div>
                  </div>

                  <!-- POSITIVE: Company owes customer - Select bank account -->
                  <div v-if="isPositiveReconciliation" class="reconciliation-action-section">

                    <div class="bank-selection-section p-4 border rounded-3 bg-light">
                      <h6 class="mb-3">
                        <i class="fe fe-credit-card me-2"></i>
                        Tài khoản ngân hàng nhận tiền
                      </h6>

                      <!-- Loading state -->
                      <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>

                      <!-- Bank account selection -->
                      <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="badge bg-success-transparent text-success">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="badge bg-success-transparent text-success ms-2">Mặc
                                  định</span>
                              </div>
                            </template>
                          </v-select>
                        </div>

                        <!-- Display selected bank account details -->
                        <div v-if="selectedBankAccount" class="bank-account-details mt-3 p-3 bg-white rounded border">
                          <div class="row">
                            <div class="col-md-6">
                              <div class="mb-2">
                                <label class="form-label fw-semibold tx-12 mb-1">Số tài khoản</label>
                                <div class="tx-13">{{ selectedBankAccount.AccountNumber }}</div>
                              </div>
                              <div class="mb-2">
                                <label class="form-label fw-semibold tx-12 mb-1">Tên chủ tài khoản</label>
                                <div class="tx-13">{{ selectedBankAccount.AccountHolderName }}</div>
                              </div>
                            </div>
                            <div class="col-md-6">
                              <div class="mb-2">
                                <label class="form-label fw-semibold tx-12 mb-1">Ngân hàng</label>
                                <div class="tx-13">{{ selectedBankAccount.BankName }}</div>
                              </div>
                              <div class="mb-2" v-if="selectedBankAccount.BranchName">
                                <label class="form-label fw-semibold tx-12 mb-1">Chi nhánh</label>
                                <div class="tx-13">{{ selectedBankAccount.BranchName }}</div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>

                      <!-- No bank account - show create button -->
                      <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>

                      <!-- Transfer note -->
                      <div class="form-group mt-3">
                        <label class="form-label">Ghi chú thanh toán</label>
                        <textarea v-model="transferNote" class="form-control" rows="2"
                          placeholder="Ghi chú về việc thanh toán cho khách hàng (nếu có)..."></textarea>
                      </div>
                    </div>
                  </div>
                </div>
              </div>



              <!-- ZERO balance -->
              <div v-if="selectedSummary.netAmount === 0" class="reconciliation-action-section">
                <div class="alert alert-info border-0 mb-3">
                  <div class="d-flex align-items-center">
                    <i class="fe fe-info me-2"></i>
                    <div>
                      <strong>Số dư bằng 0</strong>
                      <p class="mb-0 tx-13">Không có khoản thanh toán nào cần thực hiện.</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="card-footer">
              <div class="d-flex justify-content-between">
                <button type="button" class="btn btn-outline-secondary" @click="goToStep1">
                  <i class="fe fe-arrow-left me-1"></i>
                  Quay lại
                </button>
                <button type="button" class="btn btn-primary-gradient" @click="goToStep3">
                  Tiếp tục
                  <i class="fe fe-arrow-right ms-1"></i>
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- Step 3: Review & Confirm -->
        <div v-if="currentStep === 3">
          <div class="card mb-3">
            <div class="card-header">
              <h6 class="mb-0">
                <i class="fe fe-check-circle me-2"></i>
                Xác nhận thông tin đối soát
              </h6>
            </div>
            <div class="card-body">
              <!-- Summary -->
              <div class="review-section mb-4">
                <h6 class="mb-3">Tổng quan</h6>
                <div class="row">
                  <div class="col-md-6">
                    <table class="table table-sm table-borderless">
                      <tr>
                        <td class="text-muted">Số đơn hàng:</td>
                        <td class="fw-semibold">{{ selectedOrders.length }} đơn</td>
                      </tr>
                      <tr>
                        <td class="text-muted">Tổng tiền COD:</td>
                        <td class="fw-semibold text-info">{{ formatCurrency(selectedSummary.totalCodAmount) }}</td>
                      </tr>
                      <tr>
                        <td class="text-muted">Tổng phí dịch vụ:</td>
                        <td class="fw-semibold text-warning">{{ formatCurrency(selectedSummary.totalFeeAmount) }}</td>
                      </tr>
                      <tr>
                        <td class="text-muted">Tiền ròng:</td>
                        <td class="fw-bold" :class="selectedSummary.netAmount >= 0 ? 'text-success' : 'text-danger'">
                          {{ formatCurrency(selectedSummary.netAmount) }}
                        </td>
                      </tr>
                    </table>
                  </div>
                  <div class="col-md-6">
                    <div class="reconciliation-type-badge p-3 rounded-3" :class="reconciliationType.bgClass">
                      <div class="d-flex align-items-center">
                        <i :class="[reconciliationType.icon, reconciliationType.textClass, 'fs-2', 'me-3']"></i>
                        <div>
                          <div class="fw-semibold" :class="reconciliationType.textClass">{{ reconciliationType.title }}
                          </div>
                          <div class="tx-13">{{ reconciliationType.description }}</div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- Selected Orders List -->
              <div class="review-section mb-4">
                <h6 class="mb-3">Danh sách đơn hàng ({{ selectedOrders.length }})</h6>
                <div class="table-responsive">
                  <table class="table table-sm table-hover">
                    <thead>
                      <tr>
                        <th>Mã đơn</th>
                        <th class="text-end">Tiền COD</th>
                        <th class="text-end">Phí</th>
                        <th class="text-end">Tiền ròng</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr v-for="order in selectedOrders" :key="order.OrderId">
                        <td>
                          <router-link :to="{ name: 'orderTrack', params: { code: order.OrderCode } }" target="_blank"
                            class="text-primary">
                            {{ order.OrderCode }}
                          </router-link>
                        </td>
                        <td class="text-end">{{ formatCurrency(order.AppliedCodAmount) }}</td>
                        <td class="text-end">{{ formatCurrency(order.AppliedFeeAmount) }}</td>
                        <td class="text-end" :class="order.NetAmount >= 0 ? 'text-success' : 'text-danger'">
                          {{ formatCurrency(order.NetAmount) }}
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>

              <!-- Internal Note -->
              <div class="review-section mb-4">
                <h6 class="mb-3">Ghi chú nội bộ</h6>
                <div class="form-group">
                  <label class="form-label">Ghi chú về phiếu đối soát (tùy chọn)</label>
                  <textarea v-model="internalNote" class="form-control" rows="3"
                    placeholder="Nhập ghi chú nội bộ về phiếu đối soát này (ví dụ: Đối soát tháng 11/2024 - Đợt 1)..."></textarea>
                  <small class="text-muted">Ghi chú này chỉ dành cho nội bộ, khách hàng sẽ không nhìn thấy.</small>
                </div>
              </div>

              <!-- Payment Info -->
              <div class="review-section" v-if="selectedSummary.netAmount !== 0">
                <h6 class="mb-3">Thông tin thanh toán</h6>
                <div v-if="isNegativeReconciliation">
                  <div class="alert alert-danger">
                    <i class="fe fe-alert-triangle me-2"></i>
                    Khách hàng cần chuyển <strong>{{ formatCurrency(Math.abs(selectedSummary.netAmount)) }}</strong> cho
                    công ty
                  </div>
                  <div v-if="uploadedFile">
                    <p class="mb-1"><strong>Phiếu chuyển khoản:</strong></p>
                    <img :src="uploadedFilePreview" class="uploaded-preview-small mb-2" />
                  </div>
                  <div v-if="transferNote">
                    <p class="mb-1"><strong>Ghi chú:</strong></p>
                    <p class="text-muted">{{ transferNote }}</p>
                  </div>
                </div>
                <div v-if="isPositiveReconciliation">
                  <div class="alert alert-success">
                    <i class="fe fe-check-circle me-2"></i>
                    Công ty cần thanh toán <strong>{{ formatCurrency(selectedSummary.netAmount) }}</strong> cho khách
                    hàng
                  </div>
                  <div v-if="selectedBankAccount">
                    <p class="mb-1"><strong>Tài khoản nhận:</strong></p>
                    <div class="bank-info-review p-3 bg-light rounded">
                      <div>{{ selectedBankAccount.BankName }}</div>
                      <div>STK: {{ selectedBankAccount.AccountNumber }}</div>
                      <div class="text-muted">{{ selectedBankAccount.AccountHolderName }}</div>
                    </div>
                  </div>
                  <div v-if="transferNote" class="mt-2">
                    <p class="mb-1"><strong>Ghi chú:</strong></p>
                    <p class="text-muted">{{ transferNote }}</p>
                  </div>
                </div>
              </div>
            </div>
            <div class="card-footer">
              <div class="d-flex justify-content-between">
                <button type="button" class="btn btn-outline-secondary" @click="goToStep2" :disabled="loading">
                  <i class="fe fe-arrow-left me-1"></i>
                  Quay lại
                </button>
                <button type="button" class="btn btn-success" @click="createReconciliation" :disabled="loading">
                  <span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
                  <i v-else class="fe fe-check me-1"></i>
                  {{ loading ? 'Đang tạo...' : 'Tạo phiếu đối soát' }}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Modal tạo tài khoản ngân hàng -->
  <LadaDialog :visible="showCreateBankAccountModal && 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="customerId" :id="0" :customerId="customerId"
        @cancel="closeCreateBankAccountModal" />
    </template>
  </LadaDialog>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useToast } from 'vue-toastification'
import reconciliationService from '@/services/reconciliationService'
import customerBankAccountService from '@/services/customerBankAccountService'
import CreateOrUpdateBankAccount from '@/views/crm/customer/detail/components/CreateOrUpdateBankAccount.vue'

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

// Reactive data
const loading = ref(false)
const exporting = ref(false)
const orders = reactive([])
const customerInfo = ref(null)
const customerId = ref(null)
const selectedOrderIds = reactive([])
const currentStep = ref(1)

// Upload related
const fileInput = ref(null)
const uploadedFile = ref(null)
const uploadedFilePreview = ref(null)
const isDragging = ref(false)
const transferNote = ref('')
const transferDate = ref(new Date().toISOString().split('T')[0])
const internalNote = ref('') // Ghi chú nội bộ cho phiếu đối soát

// Bank account related
const bankAccounts = ref([])
const bankAccountsLoading = ref(false)
const selectedBankAccount = ref(null)
const showCreateBankAccountModal = ref(false)

// Computed - Selected orders
const selectedOrders = computed(() => {
  return orders.filter(o => selectedOrderIds.includes(o.OrderId))
})

const isAllSelected = computed(() => {
  return orders.length > 0 && selectedOrderIds.length === orders.length
})

// Computed - Summary values (selected orders only)
const selectedSummary = computed(() => {
  const selected = selectedOrders.value
  return {
    totalOrders: selected.length,
    totalCodAmount: selected.reduce((sum, o) => sum + (o.AppliedCodAmount || 0), 0),
    totalFeeAmount: selected.reduce((sum, o) => sum + (o.AppliedFeeAmount || 0), 0),
    netAmount: selected.reduce((sum, o) => sum + (o.NetAmount || 0), 0)
  }
})

// Computed - Reconciliation type (based on selected orders)
const isNegativeReconciliation = computed(() => selectedSummary.value.netAmount < 0)
const isPositiveReconciliation = computed(() => selectedSummary.value.netAmount > 0)

const reconciliationType = computed(() => {
  if (selectedSummary.value.netAmount < 0) {
    return {
      type: 'negative',
      label: 'Khách cần chuyển',
      title: 'Phiếu đối soát ÂM',
      description: 'Khách hàng cần chuyển tiền cước phí dịch vụ cho công ty.',
      icon: 'fe fe-arrow-down-circle',
      cardClass: 'bg-danger-gradient text-white',
      bgClass: 'bg-danger-light',
      textClass: 'text-danger'
    }
  } else if (selectedSummary.value.netAmount > 0) {
    return {
      type: 'positive',
      label: 'Cty trả khách',
      title: 'Phiếu đối soát DƯƠNG',
      description: 'Công ty cần thanh toán tiền COD cho khách hàng.',
      icon: 'fe fe-arrow-up-circle',
      cardClass: 'bg-success-gradient text-white',
      bgClass: 'bg-success-light',
      textClass: 'text-success'
    }
  } else {
    return {
      type: 'zero',
      label: 'Cân bằng',
      title: 'Số dư bằng 0',
      description: 'Tiền COD và phí dịch vụ bằng nhau, không cần thanh toán.',
      icon: 'fe fe-minus-circle',
      cardClass: 'bg-secondary-gradient text-white',
      bgClass: 'bg-secondary-light',
      textClass: 'text-secondary'
    }
  }
})

// Methods
const formatCurrency = (amount) => {
  if (amount === null || amount === undefined) return '0 ₫'
  return new Intl.NumberFormat('vi-VN', {
    style: 'currency',
    currency: 'VND'
  }).format(amount)
}

const formatCurrencyShort = (amount) => {
  if (amount === null || amount === undefined) return '0 ₫'
  const absAmount = Math.abs(amount)
  const sign = amount < 0 ? '-' : ''
  if (absAmount >= 1000000000) {
    return sign + (absAmount / 1000000000).toFixed(1) + ' tỷ'
  }
  if (absAmount >= 1000000) {
    return sign + (absAmount / 1000000).toFixed(1) + ' tr'
  }
  if (absAmount >= 1000) {
    return sign + (absAmount / 1000).toFixed(0) + 'k'
  }
  return formatCurrency(amount)
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleDateString('vi-VN', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric'
  })
}

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

// Export Excel handler
const handleExportExcel = async () => {
  if (!customerId.value) {
    toast.error('Không tìm thấy ID khách hàng')
    return
  }

  if (orders.length === 0) {
    toast.warning('Không có đơn hàng nào để xuất')
    return
  }

  exporting.value = true
  toast.info('Đang xuất file Excel...')

  try {
    // Call API to export Excel
    const result = await reconciliationService.exportReconciliableOrders(customerId.value, {
      FileName: `DanhSachDonHangCanDoiSoat_${customerInfo.value?.CustomerCode || customerId.value}`,
      IncludeOrderDetails: true
    })

    // Check if export was successful
    if (result.Result === 1 && result.DownloadUrl) {
      // Create download link pointing directly to media server URL
      // This avoids CORS issues because we're not fetching via API client
      const link = document.createElement('a')
      link.href = result.DownloadUrl
      link.download = result.FileName || `DanhSachDonHangCanDoiSoat_${customerId.value}.xlsx`
      link.target = '_blank' // Open in new tab to avoid CORS issues
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)

      toast.success(`Xuất file Excel thành công! (${result.TotalRecords} đơn hàng)`)
    } else {
      toast.error(result.Message || 'Xuất file Excel thất bại')
    }
  } catch (error) {
    console.error('Error exporting Excel:', error)

    let errorMessage = 'Xuất file Excel thất bại'
    if (error.response?.data?.detail) {
      errorMessage = error.response.data.detail
    } else if (error.response?.data?.title) {
      errorMessage = error.response.data.title
    } else if (error.response?.data?.Message) {
      errorMessage = error.response.data.Message
    } else if (error.message) {
      errorMessage = error.message
    }

    toast.error(errorMessage)
  } finally {
    exporting.value = false
  }
}

// Wizard navigation
const goToStep1 = () => {
  currentStep.value = 1
}

const goToStep2 = () => {
  if (selectedOrders.value.length === 0) {
    toast.warning('Vui lòng chọn ít nhất một đơn hàng')
    return
  }
  currentStep.value = 2
}

const goToStep3 = () => {
  currentStep.value = 3
}

const createReconciliation = async () => {
  // Validation
  if (!customerId.value) {
    toast.error('Không tìm thấy ID khách hàng')
    return
  }

  if (selectedOrders.value.length === 0) {
    toast.error('Vui lòng chọn ít nhất một đơn hàng')
    return
  }

  // Confirm
  const confirmed = await new Promise((resolve) => {
    const result = confirm(
      `Bạn có chắc muốn tạo phiếu đối soát cho ${selectedOrders.value.length} đơn hàng?\n` +
      `Tổng tiền COD: ${formatCurrency(selectedSummary.value.totalCodAmount)}\n` +
      `Tổng phí: ${formatCurrency(selectedSummary.value.totalFeeAmount)}\n` +
      `Tiền ròng: ${formatCurrency(selectedSummary.value.netAmount)}`
    )
    resolve(result)
  })

  if (!confirmed) return

  // Show loading
  loading.value = true

  try {
    // Use FormData for file upload
    const formData = new FormData()

    // Add basic fields
    formData.append('CustomerId', customerId.value)

    // Add order IDs
    selectedOrders.value.forEach(order => {
      formData.append('OrderIds', order.OrderId)
    })

    // Add internal note
    if (internalNote.value) {
      formData.append('InternalNote', internalNote.value)
    }

    // For negative reconciliation (customer owes company), add payment proof
    if (isNegativeReconciliation.value) {
      // Upload image file if available
      if (uploadedFile.value) {
        formData.append('Files', uploadedFile.value)
      }

      // Add transfer information
      if (transferNote.value) {
        formData.append('TransferNote', transferNote.value)
      }
      if (transferDate.value) {
        formData.append('TransferDate', transferDate.value)
      }
    }

    // For positive reconciliation (company owes customer), add bank account
    if (isPositiveReconciliation.value && selectedBankAccount.value) {
      formData.append('BankAccountNumber', selectedBankAccount.value.AccountNumber || selectedBankAccount.value)
      formData.append('BankAccountHolderName', selectedBankAccount.value.AccountHolderName || '')
      formData.append('BankCode', selectedBankAccount.value.BankCode || '')
      formData.append('BankName', selectedBankAccount.value.BankName || '')
      formData.append('BankBranchName', selectedBankAccount.value.BranchName || '')
      formData.append('BankBranchAddress', selectedBankAccount.value.BranchAddress || '')
      if (transferNote.value) {
        formData.append('PaymentNote', transferNote.value)
      }
    }

    // Call API with FormData
    const result = await reconciliationService.createCustomerReconciliationSlip(formData)

    // Success
    toast.success(result.Message || 'Tạo phiếu đối soát thành công!')

    // Navigate to reconciliation management with slips tab
    router.push({ name: 'reconciliation-management', query: { tab: 'slips' } })
  } catch (error) {
    console.error('Error creating reconciliation:', error)

    // Extract error message from API response
    let errorMessage = 'Tạo phiếu đối soát thất bại'
    if (error.response?.data?.detail) {
      errorMessage = error.response.data.detail
    } else if (error.response?.data?.title) {
      errorMessage = error.response.data.title
    } else if (error.message) {
      errorMessage = error.message
    }

    toast.error(errorMessage)
  } finally {
    loading.value = false
  }
}

// Order selection methods
const isOrderSelected = (orderId) => {
  return selectedOrderIds.includes(orderId)
}

const toggleOrderSelection = (orderId) => {
  const index = selectedOrderIds.indexOf(orderId)
  if (index === -1) {
    selectedOrderIds.push(orderId)
  } else {
    selectedOrderIds.splice(index, 1)
  }
}

const toggleSelectAll = () => {
  if (isAllSelected.value) {
    deselectAllOrders()
  } else {
    selectAllOrders()
  }
}

const selectAllOrders = () => {
  selectedOrderIds.splice(0, selectedOrderIds.length)
  orders.forEach(order => {
    selectedOrderIds.push(order.OrderId)
  })
}

const deselectAllOrders = () => {
  selectedOrderIds.splice(0, selectedOrderIds.length)
}

// File upload methods
const triggerFileUpload = () => {
  fileInput.value?.click()
}

const onFileSelected = (event) => {
  const file = event.target.files?.[0]
  if (file) {
    handleFile(file)
  }
}

const onDragOver = () => {
  isDragging.value = true
}

const onDragLeave = () => {
  isDragging.value = false
}

const onFileDrop = (event) => {
  isDragging.value = false
  const file = event.dataTransfer?.files?.[0]
  if (file) {
    handleFile(file)
  }
}

const handleFile = (file) => {
  // Validate file type
  if (!file.type.startsWith('image/')) {
    toast.error('Chỉ hỗ trợ file ảnh!')
    return
  }
  // Validate file size (5MB)
  if (file.size > 5 * 1024 * 1024) {
    toast.error('Kích thước file tối đa là 5MB!')
    return
  }

  uploadedFile.value = file

  // Create preview
  const reader = new FileReader()
  reader.onload = (e) => {
    uploadedFilePreview.value = e.target?.result
  }
  reader.readAsDataURL(file)
}

const removeUploadedFile = () => {
  uploadedFile.value = null
  uploadedFilePreview.value = null
  if (fileInput.value) {
    fileInput.value.value = ''
  }
}

async function loadOrders() {
  loading.value = true
  orders.splice(0, orders.length)
  selectedOrderIds.splice(0, selectedOrderIds.length)

  try {
    const result = await reconciliationService.getReconciliableOrdersByCustomerId(customerId.value)

    if (result && result.length > 0) {
      result.forEach(order => {
        orders.push(order)
      })

      // Tự động chọn tất cả đơn hàng
      selectAllOrders()

      // Thử lấy thông tin khách hàng từ CustomerReconciliationList đã cache
      // hoặc từ đơn hàng đầu tiên
      if (!customerInfo.value) {
        // Tải thông tin khách hàng từ API getCustomersOverview
        await loadCustomerInfo()
      }
    }
  } 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')
  } finally {
    loading.value = false
  }
}

async function loadCustomerInfo() {
  try {
    // Tìm kiếm thông tin khách hàng từ API overview
    const searchModel = {
      Pagination: { PageIndex: 1, PageSize: 100 },
      Sort: { Predicate: 'LatestOrderDate', Reverse: true },
      Search: { PredicateObject: { Keyword: '' } }
    }

    const searchResult = await reconciliationService.getCustomersOverview(searchModel)

    if (searchResult.Items) {
      const customer = searchResult.Items.find(c => c.CustomerId == customerId.value)
      if (customer) {
        customerInfo.value = customer
      }
    }

    // Load bank accounts for the customer
    await loadBankAccounts(customerId.value)
  } catch (error) {
    console.error('Error loading customer info:', error)
  }
}

// Bank account methods
async function loadBankAccounts(customerIdParam) {
  try {
    bankAccountsLoading.value = true
    const result = await customerBankAccountService.getByCustomerId(parseInt(customerIdParam))
    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
  }
}

function updateFormWithBankAccount(account) {
  // This function can be used to update form data if needed
  // For now, we just store the selected account object
  if (account) {
    selectedBankAccount.value = account
  }
}

function onBankAccountChange(account) {
  selectedBankAccount.value = account
  updateFormWithBankAccount(account)
}

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

async function closeCreateBankAccountModal() {
  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(customerId.value)
}

onMounted(() => {
  customerId.value = route.params.customerId
  if (customerId.value) {
    loadOrders()
  } else {
    toast.error('Không tìm thấy ID khách hàng')
    router.push({ name: 'reconciliation-management', query: { tab: 'customers' } })
  }
})
</script>

<style scoped>
/* Card Styles */
.card-customer-info {
  border: none;
  border-radius: 12px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
}

.customer-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 1.5rem;
}

.bank-account-info {
  padding: 1rem;
  background: white;
  border-radius: 8px;
  border-left: 4px solid #17a2b8;
}

/* Wizard Steps */
.wizard-steps {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 1rem 0;
}

.step {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}

.step-number {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #e9ecef;
  color: #6c757d;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 1rem;
  transition: all 0.3s ease;
  border: 3px solid #e9ecef;
}

.step.active .step-number {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-color: #667eea;
  transform: scale(1.1);
}

.step.completed .step-number {
  background: #28a745;
  color: white;
  border-color: #28a745;
}

.step-title {
  margin-top: 0.5rem;
  font-size: 0.8rem;
  color: #6c757d;
  font-weight: 500;
}

.step.active .step-title {
  color: #667eea;
  font-weight: 600;
}

.step.completed .step-title {
  color: #28a745;
}

.step-line {
  width: 60px;
  height: 3px;
  background: #e9ecef;
  margin: 0 0.5rem;
  transition: all 0.3s ease;
}

.step-line.active {
  background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
}

.summary-card {
  border: none;
  border-radius: 12px;
  overflow: hidden;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.summary-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.summary-icon {
  font-size: 2rem;
  opacity: 0.8;
}

.bg-primary-gradient {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.bg-info-gradient {
  background: linear-gradient(135deg, #17a2b8 0%, #138496 100%);
}

.bg-warning-gradient {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.bg-success-gradient {
  background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
}

.bg-danger-gradient {
  background: linear-gradient(135deg, #ff6b6b 0%, #c0392b 100%);
}

.bg-secondary-gradient {
  background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
}

/* Reconciliation type styles */
.reconciliation-type-header {
  transition: all 0.3s ease;
}

.type-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
}

.bg-danger-light {
  background-color: rgba(220, 53, 69, 0.1);
  border: 1px solid rgba(220, 53, 69, 0.2);
}

.bg-success-light {
  background-color: rgba(40, 167, 69, 0.1);
  border: 1px solid rgba(40, 167, 69, 0.2);
}

.bg-secondary-light {
  background-color: rgba(108, 117, 125, 0.1);
  border: 1px solid rgba(108, 117, 125, 0.2);
}

/* Upload zone styles */
.upload-zone {
  border: 2px dashed #dee2e6;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: white;
}

.upload-zone:hover {
  border-color: #667eea;
  background: rgba(102, 126, 234, 0.02);
}

.upload-zone.drag-over {
  border-color: #667eea;
  background: rgba(102, 126, 234, 0.05);
}

.uploaded-preview {
  max-width: 150px;
  max-height: 150px;
  border-radius: 8px;
  object-fit: cover;
}

.uploaded-preview-small {
  max-width: 100px;
  max-height: 100px;
  border-radius: 8px;
  object-fit: cover;
}

/* Bank account card */
.bank-account-card {
  background: white;
  transition: all 0.2s ease;
}

.bank-account-card:hover {
  border-color: #667eea !important;
}

.bank-account-card.selected {
  border-color: #28a745 !important;
  background: rgba(40, 167, 69, 0.02);
}

.bank-logo {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  background: rgba(102, 126, 234, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
}

.bg-success-transparent {
  background-color: rgba(40, 167, 69, 0.15);
}

/* Table Styles */
.orders-table-container {
  max-height: 500px;
  overflow-y: auto;
}

.orders-table-container::-webkit-scrollbar {
  width: 8px;
}

.orders-table-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.orders-table-container::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 4px;
}

.orders-table-container::-webkit-scrollbar-thumb:hover {
  background: #555;
}

.table th {
  border-top: none;
  font-weight: 600;
  color: #495057;
  background-color: #f8f9fa;
  padding: 0.75rem;
  font-size: 0.85rem;
  position: sticky;
  top: 0;
  z-index: 10;
}

.table-hover tbody tr:hover {
  background-color: rgba(102, 126, 234, 0.05);
}

.order-row {
  transition: background-color 0.15s ease;
  cursor: pointer;
}

.order-row.selected-row {
  background-color: rgba(102, 126, 234, 0.08);
}

.order-row.selected-row:hover {
  background-color: rgba(102, 126, 234, 0.12);
}

.order-code {
  font-size: 0.9rem;
}

.order-info {
  line-height: 1.6;
}

.financial-info {
  line-height: 1.8;
}

.financial-info>div {
  display: flex;
  align-items: baseline;
}

.status-badges {
  margin-top: 0.25rem;
}

.status-badges .badge {
  font-size: 0.7rem;
  padding: 0.25rem 0.4rem;
}

.receiver-info {
  line-height: 1.5;
}

/* Checkbox styles */
.form-check-input {
  width: 1.1em;
  height: 1.1em;
  cursor: pointer;
}

.form-check-input:checked {
  background-color: #667eea;
  border-color: #667eea;
}

/* Badge Styles */
.badge {
  font-weight: 500;
  padding: 0.4rem 0.6rem;
  border-radius: 6px;
}

.bg-secondary-transparent {
  background-color: rgba(108, 117, 125, 0.15);
}

.bg-primary-transparent {
  background-color: rgba(102, 126, 234, 0.15);
}

.bg-info-transparent {
  background-color: rgba(23, 162, 184, 0.15);
}

/* Status Info */
.status-info {
  line-height: 1.4;
}

.status-info .badge {
  font-size: 0.75rem;
  padding: 0.3rem 0.5rem;
  white-space: nowrap;
}


/* Button Styles */
.btn-primary-gradient {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
}

.btn-primary-gradient:hover {
  background: linear-gradient(135deg, #5a6fd6 0%, #6a4190 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
  color: white;
}

.btn-primary-gradient:disabled {
  opacity: 0.7;
  transform: none;
  box-shadow: none;
}

/* Review section */
.review-section {
  padding: 1rem;
  background: #f8f9fa;
  border-radius: 8px;
}

.bank-info-review {
  line-height: 1.6;
}

/* Spinner */
.spinner-border {
  width: 1rem;
  height: 1rem;
}

/* Responsive */
@media (max-width: 768px) {
  .wizard-steps {
    flex-direction: column;
  }

  .step-line {
    width: 3px;
    height: 50px;
    margin: 0.5rem 0;
  }

  .summary-card .card-body {
    padding: 0.75rem;
  }

  .summary-icon {
    font-size: 1.5rem;
  }

  .customer-avatar {
    width: 50px;
    height: 50px;
    font-size: 1.2rem;
  }

  .reconciliation-type-header {
    flex-direction: column;
    text-align: center;
  }

  .type-icon {
    margin-bottom: 1rem;
  }
}
</style>
