<template>
  <div class="container-fluid">
    <!-- Header -->
    <div class="row">
      <div class="col-12">
        <div class="page-title-box d-sm-flex align-items-center justify-content-between">
          <h4 class="mb-sm-0">Chi tiết phiếu đối soát cước</h4>
          <div class="page-title-right">
            <ol class="breadcrumb m-0">
              <li class="breadcrumb-item">
                <router-link to="/">Trang chủ</router-link>
              </li>
              <li class="breadcrumb-item">
                <router-link :to="{ name: 'shipping-fee-reconciliation-list' }">Đối soát cước</router-link>
              </li>
              <li class="breadcrumb-item active">Chi tiết phiếu đối soát</li>
            </ol>
          </div>
        </div>
      </div>
    </div>

    <!-- Loading -->
    <div v-if="loading" class="row">
      <div class="col-12">
        <div class="card">
          <div class="card-body text-center py-5">
            <div class="spinner-border text-primary" role="status">
              <span class="visually-hidden">Đang tải...</span>
            </div>
            <p class="mt-2 mb-0">Đang tải thông tin đối soát...</p>
          </div>
        </div>
      </div>
    </div>

    <!-- Content -->
    <div v-else-if="reconciliation">
      <!-- Reconciliation Info -->
      <div class="row mb-3">
        <div class="col-12">
          <div class="card">
            <div class="card-header">
              <div class="d-flex justify-content-between align-items-center">
                <h5 class="card-title mb-0">
                  <i class="bx bx-file me-2"></i>
                  Thông tin phiếu đối soát cước
                </h5>
                <div>
                  <span :class="getStatusBadgeClass(reconciliation.Status)">
                    {{ getStatusLabel(reconciliation.Status) }}
                  </span>
                </div>
              </div>
            </div>
            <div class="card-body">
              <div class="row">
                <div class="col-md-6">
                  <div class="row mb-3">
                    <div class="col-sm-4">
                      <strong>Mã đối soát:</strong>
                    </div>
                    <div class="col-sm-8">
                      {{ reconciliation.Code }}
                    </div>
                  </div>
                  <div class="row mb-3">
                    <div class="col-sm-4">
                      <strong>Khách hàng:</strong>
                    </div>
                    <div class="col-sm-8">
                      <div>{{ reconciliation.CustomerName }}</div>
                      <div class="text-muted small">{{ reconciliation.CustomerPhone }}</div>
                    </div>
                  </div>
                  <div class="row mb-3">
                    <div class="col-sm-4">
                      <strong>Ngày tạo:</strong>
                    </div>
                    <div class="col-sm-8">
                      <div>{{ formatDateTime(reconciliation.CreatedDate) }}</div>
                      <div class="text-muted small">Bởi: {{ reconciliation.CreatedByName }}</div>
                    </div>
                  </div>
                </div>
                <div class="col-md-6">
                  <div class="row mb-3">
                    <div class="col-sm-4">
                      <strong>Số đơn hàng:</strong>
                    </div>
                    <div class="col-sm-8">
                      {{ reconciliation.OrderCount }} đơn hàng
                    </div>
                  </div>
                  <div class="row mb-3">
                    <div class="col-sm-4">
                      <strong>Tổng cước:</strong>
                    </div>
                    <div class="col-sm-8">
                      <span class="fw-semibold">{{ formatCurrency(reconciliation.TotalShippingFeeAmount) }}</span>
                    </div>
                  </div>
                  <div class="row mb-3">
                    <div class="col-sm-4">
                      <strong>Thực chuyển:</strong>
                    </div>
                    <div class="col-sm-8">
                      <span class="fw-semibold text-success">{{ formatCurrency(reconciliation.NetAmount) }}</span>
                    </div>
                  </div>
                </div>
              </div>

              <!-- Bank Account Info -->
              <div v-if="reconciliation.BankAccountNumber" class="row mt-4">
                <div class="col-12">
                  <h6 class="mb-3">
                    <i class="bx bx-credit-card me-2"></i>
                    Thông tin tài khoản ngân hàng
                  </h6>
                  <div class="row">
                    <div class="col-md-6">
                      <div class="row mb-2">
                        <div class="col-sm-4">
                          <strong>Số tài khoản:</strong>
                        </div>
                        <div class="col-sm-8">
                          {{ reconciliation.BankAccountNumber }}
                        </div>
                      </div>
                      <div class="row mb-2">
                        <div class="col-sm-4">
                          <strong>Chủ tài khoản:</strong>
                        </div>
                        <div class="col-sm-8">
                          {{ reconciliation.BankAccountHolderName }}
                        </div>
                      </div>
                    </div>
                    <div class="col-md-6">
                      <div class="row mb-2">
                        <div class="col-sm-4">
                          <strong>Ngân hàng:</strong>
                        </div>
                        <div class="col-sm-8">
                          {{ reconciliation.BankName }}
                        </div>
                      </div>
                      <div class="row mb-2">
                        <div class="col-sm-4">
                          <strong>Chi nhánh:</strong>
                        </div>
                        <div class="col-sm-8">
                          {{ reconciliation.BankBranchName }}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- Note -->
              <div v-if="reconciliation.Note" class="row mt-4">
                <div class="col-12">
                  <h6 class="mb-3">
                    <i class="bx bx-note me-2"></i>
                    Ghi chú
                  </h6>
                  <div class="bg-light p-3 rounded">
                    {{ reconciliation.Note }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Actions -->
      <div class="row mb-3">
        <div class="col-12">
          <div class="card">
            <div class="card-body">
              <div class="d-flex gap-2">
                <button v-if="canConfirm" type="button" class="btn btn-success" @click="handleConfirm"
                  :disabled="actionLoading">
                  <i class="bx bx-check me-1"></i>
                  Xác nhận
                </button>
                <button v-if="canMarkAsTransferredStatus" type="button" class="btn btn-primary"
                  @click="handleMarkAsTransferred" :disabled="actionLoading">
                  <i class="bx bx-transfer me-1"></i>
                  Đánh dấu đã chuyển
                </button>
                <button v-if="canCancel" type="button" class="btn btn-danger" @click="handleCancel"
                  :disabled="actionLoading">
                  <i class="bx bx-x me-1"></i>
                  Hủy đối soát
                </button>
                <button type="button" class="btn btn-info" @click="handleExport" :disabled="actionLoading">
                  <i class="bx bx-download me-1"></i>
                  Xuất Excel
                </button>
                <router-link :to="{ name: 'shipping-fee-reconciliation-list' }" class="btn btn-outline-secondary">
                  <i class="bx bx-arrow-back me-1"></i>
                  Quay lại
                </router-link>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Orders List -->
      <div class="row">
        <div class="col-12">
          <div class="card">
            <div class="card-header">
              <h5 class="card-title mb-0">
                <i class="bx bx-package me-2"></i>
                Danh sách đơn hàng ({{ reconciliation.OrderCount }})
              </h5>
            </div>
            <div class="card-body">
              <div class="table-responsive">
                <table class="table table-hover align-middle">
                  <thead class="table-light">
                    <tr>
                      <th>Mã đơn hàng</th>
                      <th>Người nhận</th>
                      <th>Ngày tạo</th>
                      <th class="text-end">Cước phí</th>
                      <th class="text-end">Phí dự kiến</th>
                      <th class="text-end">Thực chuyển</th>
                      <th class="text-center">Trạng thái</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="order in reconciliation.Orders" :key="order.Id">
                      <td>
                        <div class="fw-semibold">{{ order.Code }}</div>
                      </td>
                      <td>
                        <div>{{ order.ReceiverName }}</div>
                        <div class="text-muted small">{{ order.ReceiverPhone }}</div>
                      </td>
                      <td>{{ formatDate(order.CreatedDate) }}</td>
                      <td class="text-end">{{ formatCurrency(order.ShippingFeeAmount) }}</td>
                      <td class="text-end">{{ formatCurrency(order.EstimatedFeeAmount) }}</td>
                      <td class="text-end">{{ formatCurrency(order.NetAmount) }}</td>
                      <td class="text-center">
                        <span :class="getOrderStatusClass(order.Status)">
                          {{ order.StatusStr }}
                        </span>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </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="bx bx-error-circle display-4 text-danger"></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ị xóa.</p>
            <router-link :to="{ name: 'shipping-fee-reconciliation-list' }" class="btn btn-primary">
              <i class="bx bx-arrow-back me-1"></i>
              Quay lại danh sách
            </router-link>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useToast } from 'vue-toastification';
import reconciliationService from '@/services/reconciliationService';
import {
  getReconciliationStatusLabel,
  getReconciliationStatusClass,
  canConfirmReconciliation,
  canMarkAsTransferred,
  canCancelReconciliation
} from '@/infrastructure/utilities/reconciliationConstants';
import {
  formatCurrency,
  formatDate,
  formatDateTime
} from '@/infrastructure/utilities/reconciliationHelpers';

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

// Reactive data
const loading = ref(false);
const actionLoading = ref(false);
const reconciliation = ref(null);

// Computed properties
const canConfirm = computed(() => {
  return reconciliation.value && canConfirmReconciliation(reconciliation.value.Status);
});

const canMarkAsTransferredStatus = computed(() => {
  return reconciliation.value && canMarkAsTransferred(reconciliation.value.Status);
});

const canCancel = computed(() => {
  return reconciliation.value && canCancelReconciliation(reconciliation.value.Status);
});

// Methods
const loadReconciliation = async () => {
  try {
    loading.value = true;
    const id = route.params.id;
    const result = await reconciliationService.getById(id);
    reconciliation.value = result;
  } catch (error) {
    console.error('Error loading reconciliation:', error);
    toast.error('Có lỗi xảy ra khi tải thông tin đối soát');
  } finally {
    loading.value = false;
  }
};

const getStatusLabel = (status) => {
  return getReconciliationStatusLabel(status);
};

const getStatusBadgeClass = (status) => {
  return getReconciliationStatusClass(status);
};

const getOrderStatusClass = (status) => {
  const statusClasses = {
    1: 'badge bg-warning',
    2: 'badge bg-info',
    3: 'badge bg-success',
    4: 'badge bg-danger'
  };
  return statusClasses[status] || 'badge bg-secondary';
};

const handleConfirm = async () => {
  // Implementation for confirm action
};

const handleMarkAsTransferred = async () => {
  // Implementation for mark as transferred action
};

const handleCancel = async () => {
  // Implementation for cancel action
};

const handleExport = async () => {
  // Implementation for export action
};

onMounted(() => {
  loadReconciliation();
});
</script>

<style scoped>
.table th {
  border-top: none;
  font-weight: 600;
  color: #495057;
}

.badge {
  font-size: 0.75rem;
}

.btn-sm {
  padding: 0.25rem 0.5rem;
  font-size: 0.875rem;
}

.spinner-border {
  width: 2rem;
  height: 2rem;
}

.display-4 {
  font-size: 3.5rem;
}

.bg-light {
  background-color: #f8f9fa !important;
}

.text-muted {
  color: #6c757d !important;
}

.fw-semibold {
  font-weight: 600 !important;
}

.small {
  font-size: 0.875rem;
}
</style>
