<template>
  <div>
    <!-- Breadcrumb Header -->
    <div class="breadcrumb-header justify-content-between">
      <div class="my-auto">
        <h4 class="page-title">Chi tiết phiếu đối soát</h4>
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="javascript:void(0);">Trang chủ</a></li>
          <li class="breadcrumb-item">
            <router-link :to="{ name: 'reconciliation-management', query: { tab: 'slips' } }">
              Danh sách phiếu đối soát
            </router-link>
          </li>
          <li class="breadcrumb-item active" aria-current="page">Chi tiết phiếu</li>
        </ol>
      </div>
      <div class="d-flex gap-2">
        <button type="button" class="btn btn-outline-secondary" @click="goBack">
          <i class="fe fe-arrow-left me-1"></i>
          Quay lại
        </button>

        <!-- Action Buttons -->
        <button type="button" class="btn btn-light-info" @click="handleExportExcel"
          :disabled="processing || !canExportExcel">
          <i class="fe fe-download me-1"></i>
          Export Excel
        </button>

        <button v-if="canReject" type="button" class="btn btn-outline-danger" @click="handleReject"
          :disabled="processing">
          <span v-if="processing && currentAction === 'reject'" class="spinner-border spinner-border-sm me-1"></span>
          <i v-else class="fe fe-x-circle me-1"></i>
          Reject
        </button>

        <button v-if="canApprove" type="button" class="btn btn-success" @click="handleApprove" :disabled="processing">
          <span v-if="processing && currentAction === 'approve'" class="spinner-border spinner-border-sm me-1"></span>
          <i v-else class="fe fe-check-circle me-1"></i>
          Approve
        </button>

        <button v-if="canComplete" type="button" class="btn btn-success" @click="handleComplete" :disabled="processing">
          <span v-if="processing && currentAction === 'complete'" class="spinner-border spinner-border-sm me-1"></span>
          <i v-else class="fe fe-check-square me-1"></i>
          Hoàn thành
        </button>
      </div>
    </div>

    <!-- Loading State -->
    <div v-if="loading" class="row">
      <div class="col-12">
        <div class="card">
          <div class="card-body text-center py-5">
            <span class="spinner-border spinner-border-lg text-brand-red"></span>
            <p class="mt-3 text-muted">Đang tải dữ liệu...</p>
          </div>
        </div>
      </div>
    </div>

    <!-- Main Content -->
    <div v-else-if="slip" class="row row-sm">
      <!-- Slip Information (8 columns) -->
      <div class="col-lg-8">
        <div class="card lada-card">
          <div class="card-header">
            <div class="d-flex justify-content-between align-items-center w-100">
              <div>
                <h2 class="card-title mb-2">Thông tin phiếu đối soát</h2>
                <p class="card-subtitle mb-0">Mã phiếu: <strong class="text-brand-red">{{ slip.Code }}</strong></p>
              </div>
              <span :class="getStatusBadgeClass(slip.Status)">
                {{ slip.StatusName }}
              </span>
            </div>
          </div>
          <div class="card-body">
            <div class="row g-4">
              <!-- Customer -->
              <div class="col-md-4">
                <div class="info-item">
                  <label class="info-label">Khách hàng</label>
                  <p class="info-value fw-medium mb-0">{{ slip.CustomerName }}</p>
                  <p class="info-meta">
                    <i class="fe fe-phone"></i> {{ slip.CustomerPhone }}
                  </p>
                </div>
              </div>

              <!-- Type -->
              <div class="col-md-4">
                <div class="info-item">
                  <label class="info-label">Loại phiếu</label>
                  <span :class="getTypeBadgeClass(slip.Type)">
                    {{ slip.TypeName }}
                  </span>
                </div>
              </div>

              <!-- Creator -->
              <div class="col-md-4">
                <div class="info-item">
                  <label class="info-label">Người tạo</label>
                  <p class="info-value fw-medium mb-0">{{ slip.CreatedByUserName }}</p>
                  <p class="info-meta">{{ formatDateTime(slip.CreatedTime) }}</p>
                </div>
              </div>

              <!-- Financial Summary -->
              <div class="col-md-4">
                <div class="info-item">
                  <label class="info-label">Tổng tiền COD</label>
                  <p class="info-amount">{{ formatCurrency(slip.TotalCodAmount) }}</p>
                </div>
              </div>

              <div class="col-md-4">
                <div class="info-item">
                  <label class="info-label">Tổng phí vận chuyển</label>
                  <p class="info-amount">{{ formatCurrency(slip.TotalFeeAmount) }}</p>
                </div>
              </div>

              <div class="col-md-4">
                <div class="info-item">
                  <label class="info-label">Số tiền cuối cùng</label>
                  <p class="info-amount text-brand-red">{{ formatCurrency(slip.FinalAmount) }}</p>
                </div>
              </div>

              <!-- Order Count -->
              <div class="col-md-4">
                <div class="info-item">
                  <label class="info-label">Số lượng đơn hàng</label>
                  <p class="info-amount">{{ slip.OrderCount }}</p>
                </div>
              </div>

              <!-- Approver -->
              <div class="col-md-4" v-if="slip.ApprovedByUsername">
                <div class="info-item">
                  <label class="info-label">Người duyệt</label>
                  <p class="info-value fw-medium mb-0">{{ slip.ApprovedByUsername }}</p>
                  <p class="info-meta">{{ formatDateTime(slip.ApprovedTime) }}</p>
                </div>
              </div>

              <!-- Completer -->
              <div class="col-md-4" v-if="slip.CompletedByUsername">
                <div class="info-item">
                  <label class="info-label">Người hoàn thành</label>
                  <p class="info-value fw-medium mb-0">{{ slip.CompletedByUsername }}</p>
                  <p class="info-meta">{{ formatDateTime(slip.CompletedTime) }}</p>
                </div>
              </div>

              <!-- Internal Note -->
              <div class="col-12" v-if="slip.InternalNote">
                <div class="info-item">
                  <label class="info-label">Ghi chú nội bộ</label>
                  <p class="info-value mb-0">{{ slip.InternalNote }}</p>
                </div>
              </div>
            </div>


            <!-- Tax Invoice Section -->
            <TaxInvoiceSection v-if="canShowTaxInvoice" :slipId="slip.Id" :customerInfo="{
              id: slip.CustomerId,
              name: slip.CustomerName,
              phone: slip.CustomerPhone
            }" :canCreate="canShowTaxInvoice" @refresh="loadSlipDetail" />
            <!-- OLD TAX INVOICE CODE - TO BE DELETED -->
            <div v-if="false" class="tax-invoice-section-old">
              <div class="section-divider"></div>
              <div class="d-flex justify-content-between align-items-center mb-3">
                <h6 class="section-title mb-0">Hóa đơn thuế</h6>
                <div class="d-flex gap-2">
                  <!-- Create Invoice Button -->
                  <button v-if="!taxInvoice && canCreateTaxInvoice" type="button" class="btn btn-sm btn-primary"
                    @click="handleCreateTaxInvoice" :disabled="processingTax">
                    <span v-if="processingTax && taxAction === 'create'"
                      class="spinner-border spinner-border-sm me-1"></span>
                    <i v-else class="fe fe-plus me-1"></i>
                    Tạo hóa đơn
                  </button>

                  <!-- Update Status Button -->
                  <button v-if="taxInvoice && canUpdateTaxInvoice" type="button" class="btn btn-sm btn-info"
                    @click="handleUpdateTaxInvoiceStatus" :disabled="processingTax">
                    <span v-if="processingTax && taxAction === 'update'"
                      class="spinner-border spinner-border-sm me-1"></span>
                    <i v-else class="fe fe-edit me-1"></i>
                    Cập nhật trạng thái
                  </button>

                  <!-- Delete Invoice Button -->
                  <button v-if="taxInvoice && canDeleteTaxInvoice" type="button" class="btn btn-sm btn-outline-danger"
                    @click="handleDeleteTaxInvoice" :disabled="processingTax">
                    <span v-if="processingTax && taxAction === 'delete'"
                      class="spinner-border spinner-border-sm me-1"></span>
                    <i v-else class="fe fe-trash-2 me-1"></i>
                    Xóa
                  </button>
                </div>
              </div>

              <!-- Tax Invoice Info -->
              <div v-if="taxInvoice" class="tax-invoice-info">
                <div class="row g-4">
                  <!-- Invoice Number -->
                  <div class="col-md-4">
                    <div class="info-item">
                      <label class="info-label">Số hóa đơn</label>
                      <p class="info-value mb-0">{{ taxInvoice.invoiceNumber || '-' }}</p>
                    </div>
                  </div>

                  <!-- Invoice Date -->
                  <div class="col-md-4">
                    <div class="info-item">
                      <label class="info-label">Ngày xuất</label>
                      <p class="info-value mb-0">{{ taxInvoice.invoiceDate ? formatDate(taxInvoice.invoiceDate) : '-' }}
                      </p>
                    </div>
                  </div>

                  <!-- Status -->
                  <div class="col-md-4">
                    <div class="info-item">
                      <label class="info-label">Trạng thái</label>
                      <span :class="getTaxInvoiceStatusBadgeClass(taxInvoice.status)">
                        {{ taxInvoice.statusName }}
                      </span>
                    </div>
                  </div>

                  <!-- Company Info -->
                  <div class="col-md-6">
                    <div class="info-item">
                      <label class="info-label">Công ty</label>
                      <p class="info-value fw-medium mb-0">{{ taxInvoice.companyName }}</p>
                      <p class="info-meta">MST: {{ taxInvoice.taxCode }}</p>
                    </div>
                  </div>

                  <!-- Email -->
                  <div class="col-md-6">
                    <div class="info-item">
                      <label class="info-label">Email hóa đơn</label>
                      <p class="info-value mb-0">{{ taxInvoice.invoiceEmail }}</p>
                    </div>
                  </div>

                  <!-- Address -->
                  <div class="col-12">
                    <div class="info-item">
                      <label class="info-label">Địa chỉ</label>
                      <p class="info-value mb-0">{{ taxInvoice.address }}</p>
                    </div>
                  </div>

                  <!-- Financial Info -->
                  <div class="col-md-4">
                    <div class="info-item">
                      <label class="info-label">Tổng tiền</label>
                      <p class="info-amount">{{ formatCurrency(taxInvoice.totalAmount) }}</p>
                    </div>
                  </div>

                  <div class="col-md-4">
                    <div class="info-item">
                      <label class="info-label">VAT ({{ taxInvoice.vatRate }}%)</label>
                      <p class="info-amount">{{ formatCurrency(taxInvoice.vatAmount) }}</p>
                    </div>
                  </div>

                  <div class="col-md-4">
                    <div class="info-item">
                      <label class="info-label">Tổng cộng</label>
                      <p class="info-amount text-brand-red">{{ formatCurrency(taxInvoice.totalAmountIncludingVat) }}</p>
                    </div>
                  </div>

                  <!-- PDF Download -->
                  <div class="col-12" v-if="taxInvoice.pdfUrl">
                    <a :href="taxInvoice.pdfUrl" target="_blank" class="btn btn-outline-primary btn-sm">
                      <i class="fe fe-file-text me-2"></i>Xem hóa đơn PDF
                    </a>
                  </div>

                  <!-- Note -->
                  <div class="col-12" v-if="taxInvoice.note">
                    <div class="info-item">
                      <label class="info-label">Ghi chú</label>
                      <p class="info-value mb-0">{{ taxInvoice.note }}</p>
                    </div>
                  </div>
                </div>
              </div>

              <!-- No Invoice Message -->
              <div v-else class="alert alert-info mb-0">
                <i class="fe fe-info me-2"></i>
                Phiếu đối soát này chưa có hóa đơn thuế. Nhấn "Tạo hóa đơn" để tạo hóa đơn mới.
              </div>
            </div>

            <!-- Payment Proof Section for Negative Reconciliation (Type 2 - Phiếu Chi) -->
            <div v-if="slip.Type === 2 && (slip.ProofImageUrl || slip.TransferNote || slip.TransferDate)"
              class="payment-proof-section">
              <div class="section-divider"></div>
              <h6 class="section-title">Chứng từ thanh toán</h6>

              <div class="row g-4">
                <!-- Payment Proof Image -->
                <div class="col-12" v-if="slip.ProofImageUrl">
                  <!-- Image Preview with Viewer -->
                  <div v-if="isImageFile(slip.ProofImageUrl)" class="media-preview">
                    <viewer>
                      <div class="image-container">
                        <img :src="slip.ProofImageUrl" class="media-image" :alt="'Chứng từ thanh toán - ' + slip.Code"
                          @error="handleImageError">
                        <div class="image-overlay">
                          <i class="fe fe-eye"></i>
                        </div>
                      </div>
                    </viewer>
                  </div>

                  <!-- Download Button - Only for non-image files -->
                  <a v-if="!isImageFile(slip.ProofImageUrl)" :href="slip.ProofImageUrl" target="_blank"
                    class="btn btn-outline-primary btn-sm">
                    <i class="fe fe-download me-2"></i>Tải xuống file
                  </a>
                </div>

                <!-- Transfer Note -->
                <div class="col-md-6" v-if="slip.TransferNote">
                  <div class="info-item">
                    <label class="info-label">Ghi chú chuyển khoản</label>
                    <p class="info-value mb-0">{{ slip.TransferNote }}</p>
                  </div>
                </div>

                <!-- Transfer Date -->
                <div class="col-md-6" v-if="slip.TransferDate">
                  <div class="info-item">
                    <label class="info-label">Ngày chuyển khoản</label>
                    <p class="info-value mb-0">{{ formatDate(slip.TransferDate) }}</p>
                  </div>
                </div>
              </div>
            </div>

            <!-- Bank Account Section for Positive Reconciliation (Type 1 - Phiếu Thu) -->
            <div v-if="slip.Type === 1 && slip.BankAccountNumber" class="bank-account-section">
              <div class="section-divider"></div>
              <h6 class="section-title">Thông tin tài khoản nhận tiền</h6>

              <div class="bank-account-info-card">
                <div class="row g-4">
                  <!-- Bank Account Number -->
                  <div class="col-md-6">
                    <div class="info-item">
                      <label class="info-label">
                        <i class="fe fe-credit-card me-1"></i>
                        Số tài khoản
                      </label>
                      <p class="info-value fw-bold mb-0">{{ slip.BankAccountNumber }}</p>
                    </div>
                  </div>

                  <!-- Account Holder Name -->
                  <div class="col-md-6">
                    <div class="info-item">
                      <label class="info-label">
                        <i class="fe fe-user me-1"></i>
                        Tên chủ tài khoản
                      </label>
                      <p class="info-value fw-medium mb-0">{{ slip.BankAccountHolderName }}</p>
                    </div>
                  </div>

                  <!-- Bank Name -->
                  <div class="col-md-6">
                    <div class="info-item">
                      <label class="info-label">
                        <i class="fe fe-home me-1"></i>
                        Ngân hàng
                      </label>
                      <p class="info-value mb-0">{{ slip.BankName }}</p>
                      <p class="info-meta" v-if="slip.BankCode">Mã ngân hàng: {{ slip.BankCode }}</p>
                    </div>
                  </div>

                  <!-- Branch Name -->
                  <div class="col-md-6" v-if="slip.BankBranchName">
                    <div class="info-item">
                      <label class="info-label">
                        <i class="fe fe-map-pin me-1"></i>
                        Chi nhánh
                      </label>
                      <p class="info-value mb-0">{{ slip.BankBranchName }}</p>
                    </div>
                  </div>

                  <!-- Branch Address -->
                  <div class="col-12" v-if="slip.BankBranchAddress">
                    <div class="info-item">
                      <label class="info-label">
                        <i class="fe fe-map me-1"></i>
                        Địa chỉ chi nhánh
                      </label>
                      <p class="info-value mb-0">{{ slip.BankBranchAddress }}</p>
                    </div>
                  </div>

                  <!-- Display Info (formatted) -->
                  <div class="col-12" v-if="slip.BankAccountDisplay">
                    <div class="alert alert-info mb-0">
                      <i class="fe fe-info me-2"></i>
                      <strong>Thông tin chuyển khoản:</strong> {{ slip.BankAccountDisplay }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Orders List -->
        <div class="card lada-card">
          <div class="card-header">
            <h2 class="card-title mb-0">Danh sách đơn hàng ({{ details.length }})</h2>
          </div>
          <div class="card-body p-0">
            <div class="table-responsive">
              <table class="table table-hover mb-0">
                <thead>
                  <tr>
                    <th class="text-center" style="width: 60px;">STT</th>
                    <th>Mã đơn hàng</th>
                    <th>Mã vận đơn</th>
                    <th>Người nhận</th>
                    <th class="text-center">Trạng thái</th>
                    <th class="text-end">Tiền COD</th>
                    <th class="text-end">Phí vận chuyển</th>
                    <th class="text-end">Tiền ròng</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(detail, index) in details" :key="detail.Id">
                    <td class="text-center">{{ index + 1 }}</td>
                    <td>
                      <div class="fw-medium">
                        <router-link :to="{ name: 'orderTrack', params: { code: detail.OrderCode } }" target="_blank">
                          {{ detail.OrderCode }}
                        </router-link>
                      </div>
                      <div class="text-muted tx-12" v-if="detail.DeliveredDate">
                        Giao: {{ formatDate(detail.DeliveredDate) }}
                      </div>
                    </td>
                    <td>{{ detail.PartnerCode || '-' }}</td>
                    <td>
                      <div>{{ detail.ReceiverName }}</div>
                      <div class="text-muted tx-12">{{ detail.ReceiverPhone }}</div>
                    </td>
                    <td class="text-center">
                      <div v-if="detail.OrderStatus">
                        <span class="badge bg-success-light text-success">{{ detail.OrderStatus }}</span>
                      </div>
                      <div v-else>-</div>
                    </td>
                    <td class="text-end">{{ formatCurrency(detail.AppliedCodAmount) }}</td>
                    <td class="text-end">{{ formatCurrency(detail.AppliedFeeAmount) }}</td>
                    <td class="text-end fw-bold" :class="detail.NetAmount >= 0 ? 'text-success' : 'text-brand-red'">
                      {{ formatCurrency(detail.NetAmount) }}
                    </td>
                  </tr>
                </tbody>
                <tfoot>
                  <tr class="table-light fw-semibold">
                    <td colspan="5" class="text-end">Tổng cộng:</td>
                    <td class="text-end">{{ formatCurrency(totalCodAmount) }}</td>
                    <td class="text-end">{{ formatCurrency(totalFeeAmount) }}</td>
                    <td class="text-end" :class="totalNetAmount >= 0 ? 'text-success' : 'text-brand-red'">
                      {{ formatCurrency(totalNetAmount) }}
                    </td>
                  </tr>
                </tfoot>
              </table>
            </div>
          </div>
        </div>
      </div>

      <!-- Activity Logs (4 columns) -->
      <div class="col-lg-4">
        <div class="card lada-card">
          <div class="card-header">
            <h2 class="card-title mb-0">Lịch sử thao tác ({{ logs.length }})</h2>
          </div>
          <div class="card-body">
            <div class="timeline">
              <div v-for="log in logs" :key="log.Id" class="timeline-item">
                <div class="timeline-badge" :class="getActionBadgeClass(log.ActionType)">
                  <i :class="getActionIcon(log.ActionType)"></i>
                </div>
                <div class="timeline-content">
                  <h6 class="timeline-title">{{ log.ActionTypeName }}</h6>
                  <p class="timeline-user">
                    Bởi: <strong>{{ log.ActorUsername }}</strong>
                  </p>
                  <p class="timeline-status" v-if="log.OldStatus || log.NewStatus">
                    <span v-if="log.OldStatus">{{ log.OldStatus }}</span>
                    <i class="fe fe-arrow-right mx-1" v-if="log.OldStatus && log.NewStatus"></i>
                    <span v-if="log.NewStatus" class="fw-semibold">{{ log.NewStatus }}</span>
                  </p>
                  <div class="timeline-note" v-if="log.Note">
                    <i class="fe fe-message-square"></i>
                    <span>{{ log.Note }}</span>
                  </div>
                  <p class="timeline-time">{{ formatDateTime(log.CreatedTime) }}</p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Error State -->
    <div v-else class="row">
      <div class="col-12">
        <div class="card">
          <div class="card-body text-center py-5">
            <i class="fe fe-alert-circle text-danger" style="font-size: 3rem;"></i>
            <h5 class="mt-3">Không tìm thấy phiếu đối soát</h5>
            <p class="text-muted">Phiếu đối soát không tồn tại hoặc bạn không có quyền xem.</p>
            <button type="button" class="btn btn-primary mt-3" @click="goBack">
              <i class="fe fe-arrow-left me-1"></i>
              Quay lại danh sách
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- Modal tạo hóa đơn thuế -->
    <LadaDialog :visible="showCreateTaxInvoiceModal">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title">Tạo hóa đơn thuế</h5>
          <button @click="closeCreateTaxInvoiceModal" type="button" class="close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
      </template>
      <template #body>
        <div class="modal-body">
          <!-- Customer Info -->
          <div class="mb-3" v-if="slip">
            <label class="form-label">Khách hàng:</label>
            <div>
              <router-link :to="{ name: 'crm-customer-detail', params: { id: slip.CustomerId } }" target="_blank"
                class="fw-medium text-primary">
                <i class="fe fe-external-link me-1"></i>
                {{ slip.CustomerName }}
              </router-link>
              <div class="text-muted small">{{ slip.CustomerPhone }}</div>
            </div>
          </div>

          <!-- VAT Info Selection -->
          <div class="mb-3">
            <label class="form-label">Thông tin VAT: <span class="text-danger">*</span></label>
            <div class="d-flex gap-2">
              <v-select label="CompanyName" :options="vatInfoOptions" v-model="selectedVatInfoForInvoice"
                :reduce="(option) => option.Id" placeholder="Chọn thông tin VAT..." :loading="loadingVatInfo"
                class="flex-grow-1">
                <template #option="option">
                  <div>
                    <strong>{{ option.CompanyName }}</strong>
                    <br>
                    <small class="text-muted">{{ option.TaxCode }} - {{ option.InvoiceEmail }}</small>
                  </div>
                </template>
                <template #selected-option="option">
                  <div>
                    <strong>{{ option.CompanyName }}</strong>
                    <br>
                    <small class="text-muted">{{ option.TaxCode }}</small>
                  </div>
                </template>
              </v-select>
              <button type="button" class="btn btn-outline-primary btn-sm" @click="openCreateVatModal"
                :disabled="!slip || !slip.CustomerId" title="Tạo thông tin VAT mới">
                <i class="fe fe-plus"></i>
              </button>
            </div>
            <small class="text-muted" v-if="!selectedVatInfoForInvoice">
              Vui lòng chọn thông tin VAT để tiếp tục
            </small>
            <small class="text-info d-block mt-1" v-if="vatInfoOptions.length === 0 && !loadingVatInfo && slip">
              Khách hàng chưa có thông tin VAT. <a href="#" @click.prevent="openCreateVatModal">Tạo mới</a>
            </small>
          </div>

          <!-- Note -->
          <div class="mb-3">
            <label class="form-label">Ghi chú:</label>
            <textarea v-model="taxInvoiceNote" class="form-control" rows="3"
              placeholder="Nhập ghi chú cho hóa đơn (tùy chọn)" maxlength="2048"></textarea>
            <small class="text-muted">Tối đa 2048 ký tự</small>
          </div>
        </div>
      </template>
      <template #footer>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" @click="closeCreateTaxInvoiceModal" :disabled="processingTax">
            Hủy
          </button>
          <button type="button" class="btn btn-primary" @click="submitCreateTaxInvoice"
            :disabled="processingTax || !selectedVatInfoForInvoice">
            <span v-if="processingTax" class="spinner-border spinner-border-sm me-1"></span>
            <i v-else class="fe fe-check me-1"></i>
            Tạo hóa đơn
          </button>
        </div>
      </template>
    </LadaDialog>

    <!-- Modal cập nhật trạng thái hóa đơn -->
    <LadaDialog :visible="showUpdateTaxInvoiceModal">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title">Cập nhật trạng thái hóa đơn</h5>
          <button @click="closeUpdateTaxInvoiceModal" type="button" class="close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
      </template>
      <template #body>
        <div class="modal-body">
          <div class="mb-3">
            <label class="form-label">Trạng thái: <span class="text-danger">*</span></label>
            <select v-model="updateInvoiceStatus" class="form-select">
              <option value="">-- Chọn trạng thái --</option>
              <option value="2">Nháp</option>
              <option value="3">Đã xuất</option>
            </select>
          </div>

          <div class="mb-3">
            <label class="form-label">Số hóa đơn: <span class="text-danger">*</span></label>
            <input type="text" v-model="updateInvoiceNumber" class="form-control" placeholder="Nhập số hóa đơn"
              maxlength="50">
          </div>

          <div class="mb-3">
            <label class="form-label">Ngày xuất hóa đơn: <span class="text-danger">*</span></label>
            <input type="date" v-model="updateInvoiceDate" class="form-control">
          </div>

          <div class="mb-3">
            <label class="form-label">File PDF hóa đơn: <span class="text-danger">*</span></label>
            <input type="file" @change="handlePdfFileChange" class="form-control" accept="application/pdf">
            <small class="text-muted">Chỉ chấp nhận file PDF</small>
          </div>
        </div>
      </template>
      <template #footer>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" @click="closeUpdateTaxInvoiceModal" :disabled="processingTax">
            Hủy
          </button>
          <button type="button" class="btn btn-primary" @click="submitUpdateTaxInvoiceStatus"
            :disabled="processingTax || !updateInvoiceStatus || !updateInvoiceNumber || !updateInvoiceDate || !selectedPdfFile">
            <span v-if="processingTax" class="spinner-border spinner-border-sm me-1"></span>
            <i v-else class="fe fe-save me-1"></i>
            Cập nhật
          </button>
        </div>
      </template>
    </LadaDialog>

    <!-- Modal tạo thông tin VAT mới -->
    <LadaDialog :visible="showCreateVatModal">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title">Tạo thông tin VAT mới</h5>
          <button @click="closeCreateVatModal" type="button" class="close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
      </template>
      <template #body>
        <CreateOrUpdateVatInfo :id="0" :customerId="slip?.CustomerId" @cancel="closeCreateVatModal"
          @success="onVatCreated" />
      </template>
    </LadaDialog>
  </div>
</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 TaxInvoiceSection from './components/TaxInvoiceSection.vue'

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

// Reactive data
const loading = ref(false)
const processing = ref(false)
const currentAction = ref('')
const slip = ref(null)
const details = reactive([])
const logs = reactive([])

// Permission flags
const canApprove = ref(false)
const canReject = ref(false)
const canComplete = ref(false)

// Tax Invoice data
const taxInvoice = ref(null)
const processingTax = ref(false)
const taxAction = ref('')

// VAT Info data
const vatInfoOptions = ref([])
const loadingVatInfo = ref(false)
const selectedVatInfoForInvoice = ref(null)

// Modal states
const showCreateTaxInvoiceModal = ref(false)
const showUpdateTaxInvoiceModal = ref(false)
const showCreateVatModal = ref(false)

// Create tax invoice form
const taxInvoiceNote = ref('')

// Update tax invoice form
const updateInvoiceStatus = ref('')
const updateInvoiceNumber = ref('')
const updateInvoiceDate = ref('')
const selectedPdfFile = ref(null)

// Computed
const totalCodAmount = computed(() => {
  return details.reduce((sum, d) => sum + (d.AppliedCodAmount || 0), 0)
})

const totalFeeAmount = computed(() => {
  return details.reduce((sum, d) => sum + (d.AppliedFeeAmount || 0), 0)
})

const totalNetAmount = computed(() => {
  return details.reduce((sum, d) => sum + (d.NetAmount || 0), 0)
})

// Tax Invoice computed properties
const canShowTaxInvoice = computed(() => {
  // Show tax invoice section for all statuses except Rejected (8)
  // Can create invoice from Draft (1), Pending (2), Approved (3), or Completed (4)
  if (!slip.value) return false

  // Don't allow creating tax invoice for rejected slips (Status = 8)
  const isRejected = slip.value.Status === 8
  return !isRejected
})

const canCreateTaxInvoice = computed(() => {
  // Can create if slip is Approved or Completed and no invoice exists
  return canShowTaxInvoice.value && !taxInvoice.value
})

const canUpdateTaxInvoice = computed(() => {
  // Can update if invoice exists and status is NotIssued (1) or Draft (2)
  return taxInvoice.value && (taxInvoice.value.status === 1 || taxInvoice.value.status === 2)
})

const canDeleteTaxInvoice = computed(() => {
  // Can delete only if status is NotIssued (1)
  return taxInvoice.value && taxInvoice.value.status === 1
})

const canExportExcel = computed(() => {
  // Don't allow exporting Excel for rejected slips (Status = 8)
  if (!slip.value) return false
  return slip.value.Status !== 8
})

// Methods
const formatCurrency = (amount) => {
  if (amount === null || amount === undefined) return '0 ₫'
  return new Intl.NumberFormat('vi-VN', {
    style: 'currency',
    currency: 'VND'
  }).format(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 formatDateTime = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  const time = date.toLocaleTimeString('vi-VN', {
    hour: '2-digit',
    minute: '2-digit'
  })
  const dateStr = date.toLocaleDateString('vi-VN', {
    day: '2-digit',
    month: '2-digit',
    year: 'numeric'
  })
  return `${time} ${dateStr}`
}

// Image utility methods
const isImageFile = (url) => {
  if (!url) return false
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg']
  const urlLower = url.toLowerCase()
  return imageExtensions.some(ext => urlLower.includes(ext))
}

const handleImageError = (event) => {
  console.warn('Failed to load image:', event.target.src)
  // Optionally hide the image preview on error
  event.target.style.display = 'none'
}

const getTypeBadgeClass = (type) => {
  // 1 = Receivable (Thu), 2 = Payable (Chi)
  return type === 1
    ? 'badge badge-type bg-success-light text-success'
    : 'badge badge-type bg-danger-light text-danger'
}

const getStatusBadgeClass = (status) => {
  const classMap = {
    1: 'badge badge-status bg-secondary-light text-secondary', // Draft
    2: 'badge badge-status bg-warning-light text-warning', // PendingApproval
    3: 'badge badge-status bg-info-light text-info', // Approved
    4: 'badge badge-status bg-success-light text-success', // Completed
    8: 'badge badge-status bg-danger-light text-danger' // Rejected
  }
  return classMap[status] || 'badge badge-status bg-secondary-light text-secondary'
}

const getActionBadgeClass = (actionType) => {
  const classMap = {
    1: 'bg-brand-red', // Create
    2: 'bg-info', // Update
    3: 'bg-warning', // Submit
    4: 'bg-success', // Approve
    5: 'bg-danger', // Reject
    6: 'bg-success', // ConfirmPayment
    7: 'bg-secondary' // Cancel
  }
  return classMap[actionType] || 'bg-secondary'
}

const getActionIcon = (actionType) => {
  const iconMap = {
    1: 'fe fe-plus-circle', // Create
    2: 'fe fe-edit', // Update
    3: 'fe fe-send', // Submit
    4: 'fe fe-check-circle', // Approve
    5: 'fe fe-x-circle', // Reject
    6: 'fe fe-dollar-sign', // ConfirmPayment
    7: 'fe fe-slash' // Cancel
  }
  return iconMap[actionType] || 'fe fe-circle'
}

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

const loadSlipDetail = async () => {
  loading.value = true

  try {
    const id = parseInt(route.params.id)
    if (!id || isNaN(id)) {
      toast.error('ID phiếu đối soát không hợp lệ')
      return
    }

    const result = await reconciliationService.getCustomerReconciliationSlipById(id)

    if (result && result.Slip) {
      slip.value = result.Slip

      // Load permission flags
      canApprove.value = result.CanApprove || false
      canReject.value = result.CanReject || false
      canComplete.value = result.CanComplete || false

      // Load details
      details.splice(0, details.length)
      if (result.Details && result.Details.length > 0) {
        result.Details.forEach(detail => {
          details.push(detail)
        })
      }

      // Load logs
      logs.splice(0, logs.length)
      if (result.Logs && result.Logs.length > 0) {
        result.Logs.forEach(log => {
          logs.push(log)
        })
      }
    } else {
      slip.value = null
      toast.error('Không tìm thấy phiếu đối soát')
    }
  } catch (error) {
    console.error('Error loading slip detail:', error)
    slip.value = null

    if (error.response?.status === 403) {
      toast.error('Bạn không có quyền xem phiếu này')
    } else if (error.response?.status === 500) {
      toast.error(error.response?.data?.detail || 'Không thể tải chi tiết phiếu đối soát')
    } else {
      toast.error('Có lỗi xảy ra khi tải chi tiết phiếu đối soát')
    }
  } finally {
    loading.value = false
  }
}

// Load tax invoice for the slip
const loadTaxInvoice = async () => {
  if (!slip.value || !canShowTaxInvoice.value) {
    taxInvoice.value = null
    return
  }

  try {
    const invoice = await taxService.getTaxInvoiceBySlipId(slip.value.Id)
    taxInvoice.value = invoice
  } catch (error) {
    console.error('Error loading tax invoice:', error)
    // Don't show error toast - it's normal if no invoice exists
    taxInvoice.value = null
  }
}

// Load VAT info for customer
const loadVatInfoByCustomer = async (customerId) => {
  if (!customerId) return

  try {
    loadingVatInfo.value = true
    const result = await vatInfoService.getByCustomerId(customerId)
    vatInfoOptions.value = result || []

    // Auto select default VAT info if available
    const defaultVat = vatInfoOptions.value.find(vat => vat.IsDefault)
    if (defaultVat) {
      selectedVatInfoForInvoice.value = defaultVat.Id
    }
  } catch (error) {
    console.error('Error loading VAT info:', error)
    toast.error('Có lỗi xảy ra khi tải thông tin VAT')
  } finally {
    loadingVatInfo.value = false
  }
}

// Action handlers
const handleExportExcel = async () => {
  if (!slip.value) return

  processing.value = true
  currentAction.value = 'export'

  try {
    // Call export API to generate file
    const result = await reconciliationService.exportCustomerReconciliationSlipDetail(
      slip.value.Id,
      {
        FileName: `ChiTietPhieu_${slip.value.Code}`,
        IncludeOrderDetails: true,
        IncludeApprovalInfo: true,
        IncludeNotes: true
      }
    )

    // Check if export was successful
    if (result && result.Result === 1) {
      // Download directly from DownloadUrl
      if (result.DownloadUrl) {
        const link = document.createElement('a')
        link.href = result.DownloadUrl
        link.download = result.FileName || `ChiTietPhieu_${slip.value.Code}.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 Excel thành công')
      } else {
        toast.error('Không có đường dẫn download file')
      }
    } else {
      toast.error(result?.Message || 'Có lỗi xảy ra khi xuất Excel')
    }
  } catch (error) {
    console.error('Error exporting Excel:', error)
    toast.error(error.response?.data?.Message || error.response?.data?.detail || 'Có lỗi xảy ra khi xuất Excel')
  } finally {
    processing.value = false
    currentAction.value = ''
  }
}

const handleApprove = async () => {
  if (!confirm('Bạn có chắc chắn muốn duyệt phiếu đối soát này?')) {
    return
  }

  processing.value = true
  currentAction.value = 'approve'

  try {
    await reconciliationService.approveCustomerReconciliationSlip(slip.value.Id)
    toast.success('Duyệt phiếu đối soát thành công')
    await loadSlipDetail() // Reload to get updated data
  } catch (error) {
    console.error('Error approving slip:', error)
    toast.error(error.response?.data?.detail || 'Có lỗi xảy ra khi duyệt phiếu đối soát')
  } finally {
    processing.value = false
    currentAction.value = ''
  }
}

const handleReject = async () => {
  const reason = prompt('Vui lòng nhập lý do từ chối:')
  if (!reason || reason.trim() === '') {
    toast.warning('Bạn cần nhập lý do từ chối')
    return
  }

  processing.value = true
  currentAction.value = 'reject'

  try {
    await reconciliationService.rejectCustomerReconciliationSlip(slip.value.Id, reason.trim())
    toast.success('Từ chối phiếu đối soát thành công')
    await loadSlipDetail() // Reload to get updated data
  } catch (error) {
    console.error('Error rejecting slip:', error)
    toast.error(error.response?.data?.detail || 'Có lỗi xảy ra khi từ chối phiếu đối soát')
  } finally {
    processing.value = false
    currentAction.value = ''
  }
}

const handleComplete = async () => {
  if (!confirm('Bạn có chắc chắn muốn hoàn thành phiếu đối soát này?')) {
    return
  }

  processing.value = true
  currentAction.value = 'complete'

  try {
    await reconciliationService.completeCustomerReconciliationSlip({
      Id: slip.value.Id,
      ProofImageUrl: slip.value.ProofImageUrl || '',
      Note: ''
    })
    toast.success('Hoàn thành phiếu đối soát thành công')
    await loadSlipDetail() // Reload to get updated data
  } catch (error) {
    console.error('Error completing slip:', error)
    toast.error(error.response?.data?.detail || 'Có lỗi xảy ra khi hoàn thành phiếu đối soát')
  } finally {
    processing.value = false
    currentAction.value = ''
  }
}

// Tax Invoice Handlers
const getTaxInvoiceStatusBadgeClass = (status) => {
  const classMap = {
    1: 'badge badge-status bg-secondary-light text-secondary', // NotIssued
    2: 'badge badge-status bg-info-light text-info', // Draft
    3: 'badge badge-status bg-success-light text-success' // Issued
  }
  return classMap[status] || 'badge badge-status bg-secondary-light text-secondary'
}

// Modal handlers
const openCreateTaxInvoiceModal = () => {
  showCreateTaxInvoiceModal.value = true
}

const closeCreateTaxInvoiceModal = () => {
  showCreateTaxInvoiceModal.value = false
  selectedVatInfoForInvoice.value = null
  taxInvoiceNote.value = ''
}

const openUpdateTaxInvoiceModal = () => {
  showUpdateTaxInvoiceModal.value = true
}

const closeUpdateTaxInvoiceModal = () => {
  showUpdateTaxInvoiceModal.value = false
  updateInvoiceStatus.value = ''
  updateInvoiceNumber.value = ''
  updateInvoiceDate.value = ''
  selectedPdfFile.value = null
}

const handlePdfFileChange = (event) => {
  const file = event.target.files[0]
  if (file) {
    if (file.type !== 'application/pdf') {
      toast.error('Chỉ chấp nhận file PDF')
      event.target.value = ''
      selectedPdfFile.value = null
      return
    }
    selectedPdfFile.value = file
  } else {
    selectedPdfFile.value = null
  }
}

const handleCreateTaxInvoice = async () => {
  if (!slip.value) return

  // Load VAT info for customer
  if (slip.value.CustomerId) {
    await loadVatInfoByCustomer(slip.value.CustomerId)
  }

  openCreateTaxInvoiceModal()
}

const submitCreateTaxInvoice = async () => {
  if (!selectedVatInfoForInvoice.value) {
    toast.warning('Vui lòng chọn thông tin VAT')
    return
  }

  processingTax.value = true
  taxAction.value = 'create'

  try {
    const result = await taxService.createTaxInvoice({
      customerReconciliationSlipId: slip.value.Id,
      vatInfoId: selectedVatInfoForInvoice.value,
      note: taxInvoiceNote.value.trim()
    })

    if (result && result.result === 1) {
      toast.success(result.message || 'Tạo hóa đơn thuế thành công')
      closeCreateTaxInvoiceModal()
      await loadTaxInvoice() // Reload tax invoice
    } else {
      toast.error(result?.message || 'Có lỗi xảy ra khi tạo hóa đơn thuế')
    }
  } catch (error) {
    console.error('Error creating tax invoice:', error)
    toast.error(error.response?.data?.message || error.response?.data?.detail || 'Có lỗi xảy ra khi tạo hóa đơn thuế')
  } finally {
    processingTax.value = false
    taxAction.value = ''
  }
}

const handleUpdateTaxInvoiceStatus = async () => {
  if (!taxInvoice.value) return
  openUpdateTaxInvoiceModal()
}

const submitUpdateTaxInvoiceStatus = async () => {
  if (!updateInvoiceStatus.value || !updateInvoiceNumber.value || !updateInvoiceDate.value || !selectedPdfFile.value) {
    toast.warning('Vui lòng điền đầy đủ thông tin')
    return
  }

  processingTax.value = true
  taxAction.value = 'update'

  try {
    const formData = new FormData()
    formData.append('taxInvoiceId', taxInvoice.value.id)
    formData.append('status', parseInt(updateInvoiceStatus.value))
    formData.append('invoiceNumber', updateInvoiceNumber.value.trim())
    formData.append('invoiceDate', new Date(updateInvoiceDate.value).toISOString())
    formData.append('files', selectedPdfFile.value)

    const result = await taxService.updateTaxInvoiceStatus(formData)

    if (result && result.result === 1) {
      toast.success(result.message || 'Cập nhật trạng thái hóa đơn thành công')
      closeUpdateTaxInvoiceModal()
      await loadTaxInvoice() // Reload tax invoice
    } else {
      toast.error(result?.message || 'Có lỗi xảy ra khi cập nhật trạng thái')
    }
  } catch (error) {
    console.error('Error updating tax invoice status:', error)
    toast.error(error.response?.data?.message || error.response?.data?.detail || 'Có lỗi xảy ra khi cập nhật trạng thái')
  } finally {
    processingTax.value = false
    taxAction.value = ''
  }
}

const handleDeleteTaxInvoice = async () => {
  if (!taxInvoice.value) return

  if (!confirm('Bạn có chắc chắn muốn xóa hóa đơn thuế này? Chỉ có thể xóa hóa đơn ở trạng thái "Chưa xuất".')) {
    return
  }

  processingTax.value = true
  taxAction.value = 'delete'

  try {
    const result = await taxService.deleteTaxInvoice(taxInvoice.value.id)
    toast.success(result.message || 'Xóa hóa đơn thuế thành công')
    taxInvoice.value = null // Clear the invoice
  } catch (error) {
    console.error('Error deleting tax invoice:', error)
    toast.error(error.response?.data?.message || error.response?.data?.detail || 'Có lỗi xảy ra khi xóa hóa đơn thuế')
  } finally {
    processingTax.value = false
    taxAction.value = ''
  }
}

// VAT Modal Handlers
const openCreateVatModal = () => {
  if (!slip.value || !slip.value.CustomerId) {
    toast.error('Vui lòng chọn khách hàng trước')
    return
  }
  showCreateVatModal.value = true
}

const closeCreateVatModal = () => {
  showCreateVatModal.value = false
}

const onVatCreated = async () => {
  // Close modal
  closeCreateVatModal()

  // Reload VAT info for current customer
  if (slip.value && slip.value.CustomerId) {
    await loadVatInfoByCustomer(slip.value.CustomerId)
    toast.success('Tạo thông tin VAT thành công!')
  }
}

onMounted(async () => {
  await loadSlipDetail()
  await loadTaxInvoice()
})
</script>

<style scoped>
/* Brand Colors - LADA Express */
.text-brand-red {
  color: #EF3636 !important;
}

.text-brand-yellow {
  color: #F4B400 !important;
}

.bg-brand-red {
  background-color: #EF3636 !important;
}

.bg-brand-yellow {
  background-color: #F4B400 !important;
}

/* Button Variants */
.btn-light-primary {
  background-color: #e7f3ff;
  border-color: #e7f3ff;
  color: #0d6efd;
}

.btn-light-primary:hover {
  background-color: #d0e7ff;
  border-color: #d0e7ff;
  color: #0d6efd;
}

.btn-light-primary:disabled {
  background-color: #e7f3ff;
  border-color: #e7f3ff;
  color: #0d6efd;
  opacity: 0.6;
}

.btn-light-info {
  background-color: #d1ecf1;
  border-color: #d1ecf1;
  color: #0c5460;
}

.btn-light-info:hover {
  background-color: #bee5eb;
  border-color: #bee5eb;
  color: #0c5460;
}

.btn-light-info:disabled {
  background-color: #d1ecf1;
  border-color: #d1ecf1;
  color: #0c5460;
  opacity: 0.6;
}

/* Badge Variants */
.bg-success-light {
  background-color: rgba(40, 167, 69, 0.1);
}

.bg-danger-light {
  background-color: rgba(239, 54, 54, 0.1);
}

.bg-warning-light {
  background-color: rgba(244, 180, 0, 0.1);
}

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

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

/* Card Styles */
.lada-card {
  border-radius: 8px;
  border: 1px solid #e9ecef;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 1.5rem;
}

.lada-card .card-header {
  background: white;
  border-bottom: 1px solid #e9ecef;
  padding: 1rem 1.5rem;
}

.lada-card .card-title {
  font-size: 1.125rem;
  font-weight: 600;
  color: #212529;
  margin-bottom: 0;
}

.lada-card .card-subtitle {
  font-size: 0.875rem;
  color: #6c757d;
}

/* Info Item */
.info-item {
  margin-bottom: 0;
}

.info-label {
  font-size: 0.75rem;
  font-weight: 600;
  color: #6c757d;
  text-transform: uppercase;
  letter-spacing: 0.5px;
  margin-bottom: 0.5rem;
  display: block;
}

.info-value {
  font-size: 0.9375rem;
  color: #212529;
}

.info-meta {
  font-size: 0.875rem;
  color: #6c757d;
  margin-bottom: 0;
  margin-top: 0.25rem;
}

.info-amount {
  font-size: 1.5rem;
  font-weight: 700;
  color: #212529;
  margin-bottom: 0;
}

/* Badge Styles */
.badge {
  font-weight: 500;
}

.badge-status {
  padding: 0.5rem 1rem;
  border-radius: 9999px;
  font-size: 0.875rem;
}

.badge-type {
  padding: 0.4rem 0.8rem;
  border-radius: 9999px;
  font-size: 0.875rem;
}

/* Table Styles */
.table thead th {
  background-color: #f8f9fa;
  font-weight: 600;
  font-size: 0.75rem;
  text-transform: uppercase;
  color: #6c757d;
  padding: 0.75rem 1.5rem;
  border-bottom: 2px solid #dee2e6;
}

.table tbody td {
  padding: 1rem 1.5rem;
  vertical-align: middle;
  font-size: 0.875rem;
}

.table tfoot td {
  padding: 0.75rem 1.5rem;
  font-size: 0.9375rem;
}

.table-hover tbody tr:hover {
  background-color: rgba(239, 54, 54, 0.03);
}

/* Timeline */
.timeline {
  position: relative;
  padding-left: 40px;
}

.timeline-item {
  position: relative;
  padding-bottom: 1.5rem;
}

.timeline-item:last-child {
  padding-bottom: 0;
}

.timeline-item::before {
  content: '';
  position: absolute;
  left: -28px;
  top: 32px;
  bottom: -12px;
  width: 2px;
  background: #e9ecef;
}

.timeline-item:last-child::before {
  display: none;
}

.timeline-badge {
  position: absolute;
  left: -38px;
  top: 0;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 0.875rem;
}

.timeline-content {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 0.75rem;
}

.timeline-title {
  font-size: 0.9375rem;
  font-weight: 600;
  color: #212529;
  margin-bottom: 0.25rem;
}

.timeline-user {
  font-size: 0.875rem;
  color: #6c757d;
  margin-bottom: 0.5rem;
}

.timeline-status {
  font-size: 0.8125rem;
  color: #6c757d;
  margin-bottom: 0.5rem;
}

.timeline-note {
  font-size: 0.875rem;
  padding: 0.5rem;
  background: white;
  border-radius: 6px;
  display: flex;
  align-items: start;
  gap: 0.5rem;
  margin-bottom: 0.5rem;
}

.timeline-time {
  font-size: 0.75rem;
  color: #adb5bd;
  margin-bottom: 0;
}

/* Action Badge Colors */
.bg-info {
  background-color: #17a2b8 !important;
}

.bg-warning {
  background-color: #F4B400 !important;
}

.bg-success {
  background-color: #28a745 !important;
}

.bg-danger {
  background-color: #dc3545 !important;
}

.bg-secondary {
  background-color: #6c757d !important;
}

/* Media Preview Styles */
.media-preview {
  max-width: 300px;
}

.image-container {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border: 1px solid #dee2e6;
  border-radius: 8px;
  background: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: box-shadow 0.2s;
}

.image-container:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.media-image {
  width: 100%;
  height: 180px;
  object-fit: cover;
  cursor: pointer;
  transition: transform 0.2s;
  display: block;
  position: relative;
  z-index: 1;
}

.media-image:hover {
  transform: scale(1.05);
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.2s;
  color: white;
  font-size: 1.5rem;
  z-index: 2;
  pointer-events: none;
}

.image-container:hover .image-overlay {
  opacity: 1;
}

/* Payment Proof Section */
.payment-proof-section {
  padding: 0 1.5rem 1.5rem;
}

.section-divider {
  height: 1px;
  background: linear-gradient(to right, #dee2e6 0%, #dee2e6 50%, transparent 50%);
  background-size: 8px 1px;
  margin: 1.5rem 0 1rem;
}

.section-title {
  font-size: 0.9375rem;
  font-weight: 600;
  color: #495057;
  margin-bottom: 1rem;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

/* Tax Invoice Section */
.tax-invoice-section {
  padding: 0 1.5rem 1.5rem;
}

.tax-invoice-info {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 1.5rem;
}

/* Bank Account Section */
.bank-account-section {
  padding: 0 1.5rem 1.5rem;
}

.bank-account-info-card {
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 8px;
  padding: 1.5rem;
  border: 1px solid #dee2e6;
}

.bank-account-info-card .info-label {
  color: #495057;
  font-weight: 600;
}

.bank-account-info-card .info-value {
  color: #212529;
}

.bank-account-info-card .alert-info {
  background-color: rgba(23, 162, 184, 0.1);
  border: 1px solid rgba(23, 162, 184, 0.2);
  color: #0c5460;
}

/* Responsive */
@media (max-width: 768px) {
  .timeline {
    padding-left: 30px;
  }

  .timeline-badge {
    left: -30px;
    width: 24px;
    height: 24px;
    font-size: 0.75rem;
  }

  .timeline-item::before {
    left: -23px;
  }
}
</style>
