<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"><a href="javascript:void(0);">Đối soát</a></li>
          <li class="breadcrumb-item"><a href="javascript:void(0);">Danh sách phiếu đối soát</a></li>
          <li class="breadcrumb-item active" aria-current="page">Chi tiết phiếu đối soát</li>
        </ol>
      </div>
    </div>
    <div class="row row-sm">
      <!-- Loading overlay -->
      <LoadingOverlay v-if="pageLoading" />

      <!-- Main content -->
      <div v-else-if="reconciliation" class="row">
        <!-- Reconciliation Information Section -->
        <div class="col-sm-12 col-md-6 col-lg-6 col-xl-6 grid-margin">
          <div class="card shadow-none">
            <div class="card-header d-flex justify-content-between align-items-center">
              <h5 class="card-title mb-0">
                <i class="fe fe-file-text me-2"></i>
                Thông tin phiếu đối soát
              </h5>
              <div>
                <span :class="getReconciliationStatusClass(reconciliation.Status)">
                  {{ reconciliation.StatusStr }}
                </span>
              </div>
            </div>
            <div class="card-body">
              <div class="row">
                <div class="col-md-4">
                  <div class="mb-3">
                    <label class="form-label fw-semibold">Mã đối soát</label>
                    <div class="form-control-plaintext">{{ reconciliation.Code }}</div>
                  </div>
                  <div class="mb-3">
                    <label class="form-label fw-semibold">Người tạo</label>
                    <div class="form-control-plaintext">{{ reconciliation.CreatedByUsername }}</div>
                  </div>
                </div>
                <div class="col-md-4">
                  <div class="mb-3">
                    <label class="form-label fw-semibold">Ngày tạo</label>
                    <div class="form-control-plaintext">{{ formatDateTime(reconciliation.CreatedTime) }}</div>
                  </div>
                  <div class="mb-3">
                    <label class="form-label fw-semibold">Khoảng thời gian</label>
                    <div class="form-control-plaintext">
                      {{ formatDate(reconciliation.FromDate) }} - {{ formatDate(reconciliation.ToDate) }}
                    </div>
                  </div>
                </div>
                <div class="col-md-4">
                  <div class="mb-3">
                    <label class="form-label fw-semibold">Ngày chuyển tiền</label>
                    <div class="form-control-plaintext">
                      {{ reconciliation.TransferDate ? formatDate(reconciliation.TransferDate) : 'Chưa chuyển' }}
                    </div>
                  </div>
                  <div class="mb-3">
                    <label class="form-label fw-semibold">Ghi chú tạo</label>
                    <div class="form-control-plaintext">
                      {{ reconciliation.Note || 'Không có ghi chú' }}
                    </div>
                  </div>
                </div>
              </div>
              <div class="row">
                <div class="col-md-4">
                  <div class="mb-3">
                    <label class="form-label fw-semibold">Số lượng đơn hàng</label>
                    <div class="form-control-plaintext">
                      <span class="badge bg-info fs-6">{{ reconciliation.OrderCount }}</span>
                    </div>
                  </div>
                </div>
                <div class="col-md-4">
                  <div class="mb-3">
                    <label class="form-label fw-semibold">Tổng tiền COD</label>
                    <div class="form-control-plaintext fw-semibold">
                      {{ formatCurrency(reconciliation.TotalCodAmount) }}
                    </div>
                  </div>
                </div>
                <div class="col-md-4">
                  <div class="mb-3">
                    <label class="form-label fw-semibold">Tổng phí trừ</label>
                    <div class="form-control-plaintext text-warning fw-semibold">
                      {{ formatCurrency(reconciliation.TotalFeeAmount) }}
                    </div>
                  </div>
                </div>
              </div>
              <div class="row">
                <div class="col-md-12">
                  <div class="mb-3">
                    <label class="form-label fw-semibold">Tiền thực chuyển</label>
                    <div class="form-control-plaintext text-success fw-semibold fs-5">
                      {{ formatCurrency(reconciliation.NetAmount) }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Customer & Bank Account Information Section -->
        <div class="col-sm-12 col-md-6 col-lg-6 col-xl-6 grid-margin">
          <div class="card shadow-none">
            <div class="card-header">
              <h5 class="card-title mb-0">
                <i class="fe fe-user me-2"></i>
                Thông tin khách hàng & tài khoản ngân hàng
              </h5>
            </div>
            <div class="card-body">
              <!-- Customer Information -->
              <div class="mb-4">
                <h6 class="fw-semibold text-primary mb-3">
                  <i class="fe fe-user me-1"></i>
                  Thông tin khách hàng
                </h6>
                <div class="row">
                  <div class="col-md-4">
                    <div class="mb-3">
                      <label class="form-label fw-semibold">Tên khách hàng</label>

                      <div class="form-control-plaintext">
                        <router-link v-if="reconciliation.Customer?.Id > 0"
                          :to="{ name: 'crm-customer-detail', params: { id: reconciliation.Customer.Id } }"
                          target="_blank">
                          {{ reconciliation.Customer?.FullName }}
                        </router-link>
                        <span v-else>Chưa có</span>
                      </div>
                    </div>
                    <div class="mb-3">
                      <label class="form-label fw-semibold">Số điện thoại</label>
                      <div class="form-control-plaintext">{{ reconciliation.Customer?.PhoneNumber || 'Chưa có' }}</div>
                    </div>
                  </div>
                  <div class="col-md-4">
                    <div class="mb-3">
                      <label class="form-label fw-semibold">Email</label>
                      <div class="form-control-plaintext">{{ reconciliation.Customer?.Email || 'Chưa có' }}</div>
                    </div>
                    <div class="mb-3">
                      <label class="form-label fw-semibold">Địa chỉ</label>
                      <div class="form-control-plaintext">{{ reconciliation.Customer?.Address || 'Chưa có' }}</div>
                    </div>
                  </div>
                  <div class="col-md-4">
                    <div class="mb-3">
                      <label class="form-label fw-semibold">Sale quản lý</label>
                      <div class="form-control-plaintext">{{ reconciliation.Customer?.ManagerUsername || 'Chưa có' }}
                      </div>
                    </div>
                    <div class="mb-3">
                      <label class="form-label fw-semibold">Trạng thái</label>
                      <div class="form-control-plaintext">
                        <span :class="reconciliation.Customer?.Status === 1 ? 'tag tag-green' : 'tag tag-red'">
                          {{ reconciliation.Customer?.StatusName || 'Chưa có' }}
                        </span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- Bank Account Information -->
              <div v-if="reconciliation.BankAccount">
                <h6 class="fw-semibold text-success mb-3">
                  <i class="fe fe-credit-card me-1"></i>
                  Thông tin tài khoản ngân hàng
                </h6>
                <div class="row">
                  <div class="col-md-4">
                    <div class="mb-3">
                      <label class="form-label fw-semibold">Số tài khoản</label>
                      <div class="form-control-plaintext">{{ reconciliation.BankAccount.AccountNumber }}</div>
                    </div>
                    <div class="mb-3">
                      <label class="form-label fw-semibold">Tên chủ tài khoản</label>
                      <div class="form-control-plaintext">{{ reconciliation.BankAccount.AccountHolderName }}</div>
                    </div>
                  </div>
                  <div class="col-md-4">
                    <div class="mb-3">
                      <label class="form-label fw-semibold">Ngân hàng</label>
                      <div class="form-control-plaintext">{{ reconciliation.BankAccount.BankName }}</div>
                    </div>
                    <div class="mb-3">
                      <label class="form-label fw-semibold">Chi nhánh</label>
                      <div class="form-control-plaintext">{{ reconciliation.BankAccount.BranchName || 'Chưa có' }}</div>
                    </div>
                  </div>
                  <div class="col-md-4">
                    <div class="mb-3">
                      <label class="form-label fw-semibold">Mã ngân hàng</label>
                      <div class="form-control-plaintext">{{ reconciliation.BankAccount.BankCode || 'Chưa có' }}</div>
                    </div>
                    <div class="mb-3">
                      <label class="form-label fw-semibold">Địa chỉ chi nhánh</label>
                      <div class="form-control-plaintext">{{ reconciliation.BankAccount.BranchAddress || 'Chưa có' }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div v-else class="text-center py-3 text-muted">
                <i class="fe fe-credit-card me-2"></i>
                Chưa có thông tin tài khoản ngân hàng
              </div>
            </div>
          </div>
        </div>

        <!-- Transfer Information Section (only show if transferred) -->
        <div v-if="reconciliation.Status === 3" class="col-sm-12 col-md-12 col-lg-12 col-xl-12 grid-margin">
          <div class="card shadow-none">
            <div class="card-header">
              <h5 class="card-title mb-0">
                <i class="bx bx-transfer me-2"></i>
                Thông tin chuyển tiền
              </h5>
            </div>
            <div class="card-body">
              <div class="row">
                <div class="col-md-3">
                  <div class="mb-3">
                    <label class="form-label fw-semibold">Phương thức chuyển tiền</label>
                    <div class="form-control-plaintext">
                      <span class="badge bg-info">
                        {{ getTransferMethodLabel(reconciliation.TransferMethod) }}
                      </span>
                    </div>
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="mb-3">
                    <label class="form-label fw-semibold">Ngày chuyển tiền</label>
                    <div class="form-control-plaintext">
                      {{ reconciliation.TransferDate ? formatDateTime(reconciliation.TransferDate) : 'Chưa có' }}
                    </div>
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="mb-3">
                    <label class="form-label fw-semibold">Người thực hiện</label>
                    <div class="form-control-plaintext">
                      {{ reconciliation.TransferByUsername || 'Chưa có' }}
                    </div>
                  </div>
                </div>
                <div class="col-md-3">
                  <div class="mb-3">
                    <label class="form-label fw-semibold">Số tiền chuyển</label>
                    <div class="form-control-plaintext text-success fw-semibold">
                      {{ formatCurrency(reconciliation.NetAmount) }}
                    </div>
                  </div>
                </div>
              </div>
              <div class="row" v-if="reconciliation.TransferNote || reconciliation.TransferAdditionalInfo">
                <div class="col-md-6" v-if="reconciliation.TransferNote">
                  <div class="mb-3">
                    <label class="form-label fw-semibold">Ghi chú chuyển tiền</label>
                    <div class="form-control-plaintext">
                      {{ reconciliation.TransferNote }}
                    </div>
                  </div>
                </div>
                <div class="col-md-6" v-if="reconciliation.TransferAdditionalInfo">
                  <div class="mb-3">
                    <label class="form-label fw-semibold">Thông tin bổ sung</label>
                    <div class="form-control-plaintext">
                      {{ reconciliation.TransferAdditionalInfo }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Orders List -->
        <div class="card mb-4">
          <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="card-title mb-0">
              <i class="bx bx-list-ul me-2"></i>
              Danh sách đơn hàng ({{ reconciliation.Orders?.length || 0 }})
            </h5>
          </div>
          <div class="card-body">
            <!-- Empty state -->
            <empty v-if="!reconciliation.Orders || reconciliation.Orders.length === 0" icon="bx bx-package"
              message="Không có đơn hàng nào" />

            <!-- Orders table -->
            <div v-else class="table-responsive">
              <table class="table table-hover align-middle">
                <thead class="table-light">
                  <tr>
                    <th>Mã đơn</th>
                    <th>Ngày thu COD</th>
                    <th class="text-end">Tiền COD</th>
                    <th class="text-end">Phí dịch vụ</th>
                    <th class="text-end">Tiền thực</th>
                    <th class="text-end">Phí vận chuyển</th>
                    <th>Người nhận</th>
                    <th>Địa chỉ giao</th>
                    <th>Ghi chú</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="order in reconciliation.Orders" :key="order.Id">
                    <td>

                      <div class="fw-semibold">

                        <router-link :to="{ name: 'orderTrack', params: { code: order.OrderCode } }" target="_blank">
                          {{ order.OrderCode }}
                        </router-link>
                      </div>
                      <div class="text-muted small" v-if="order.PartnerCode">
                        {{ order.PartnerCode }}
                      </div>
                    </td>
                    <td>
                      <span class="text-muted">{{ order.CodCollectedDate ? formatDateTime(order.CodCollectedDate) :
                        'Chưa thu' }}</span>
                    </td>
                    <td class="text-end">
                      <span class="fw-semibold">{{ formatCurrency(order.CodAmount) }}</span>
                    </td>
                    <td class="text-end">
                      <span class="text-warning">{{ formatCurrency(order.FeeAmount) }}</span>
                    </td>
                    <td class="text-end">
                      <span class="fw-semibold text-success">{{ formatCurrency(order.NetAmount) }}</span>
                    </td>
                    <td class="text-end">
                      <span class="text-info">{{ formatCurrency(order.ShippingFee) }}</span>
                    </td>
                    <td>
                      <div>{{ order.ReceiverName || 'Chưa có' }}</div>
                      <div class="text-muted small">{{ order.ReceiverPhone || 'Chưa có' }}</div>
                    </td>
                    <td>
                      <div class="text-muted small">{{ order.DeliveryAddress || 'Chưa có' }}</div>
                    </td>
                    <td>
                      <div class="text-muted small">{{ order.Note || 'Không có' }}</div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

            <!-- Summary -->
            <div v-if="reconciliation.Orders && reconciliation.Orders.length > 0" class="mt-3 p-3 bg-light rounded">
              <div class="row text-center">
                <div class="col-md-3">
                  <div class="fw-semibold text-primary">{{ reconciliation.Orders.length }}</div>
                  <div class="text-muted small">Tổng đơn hàng</div>
                </div>
                <div class="col-md-3">
                  <div class="fw-semibold text-success">{{ formatCurrency(reconciliation.TotalCodAmount) }}</div>
                  <div class="text-muted small">Tổng tiền COD</div>
                </div>
                <div class="col-md-3">
                  <div class="fw-semibold text-warning">{{ formatCurrency(reconciliation.TotalFeeAmount) }}</div>
                  <div class="text-muted small">Tổng phí</div>
                </div>
                <div class="col-md-3">
                  <div class="fw-semibold text-success">{{ formatCurrency(reconciliation.NetAmount) }}</div>
                  <div class="text-muted small">Tiền thực chuyển</div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Action buttons -->
        <div class="card">
          <div class="card-body">
            <div class="d-flex justify-content-between">
              <button type="button" class="btn btn-outline-secondary" @click="goBack">
                <i class="bx bx-arrow-back me-1"></i>
                Quay lại
              </button>

              <div>
                <button type="button" class="btn btn-outline-info me-2" @click="exportToExcel" :disabled="actionLoading">
                  <span v-if="actionLoading" class="spinner-border spinner-border-sm me-2"></span>
                  <i v-else class="bx bx-file-blank me-1"></i>
                  Xuất Excel
                </button>

                <button v-if="canConfirmReconciliation(reconciliation.Status)" type="button"
                  class="btn btn-primary me-2" @click="confirmReconciliation" :disabled="actionLoading">
                  <span v-if="actionLoading" class="spinner-border spinner-border-sm me-2"></span>
                  <i v-else class="bx bx-check me-1"></i>
                  Xác nhận
                </button>

                <button v-if="canMarkAsTransferred(reconciliation.Status)" type="button" class="btn btn-success me-2"
                  @click="showTransferModal" :disabled="actionLoading">
                  <span v-if="actionLoading" class="spinner-border spinner-border-sm me-2"></span>
                  <i v-else class="bx bx-transfer me-1"></i>
                  Cập nhật đã chuyển tiền
                </button>

                <button v-if="canCancelReconciliation(reconciliation.Status)" type="button"
                  class="btn btn-outline-danger" @click="cancelReconciliation" :disabled="actionLoading">
                  <span v-if="actionLoading" class="spinner-border spinner-border-sm me-2"></span>
                  <i v-else class="bx bx-x me-1"></i>
                  Hủy đối soát
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Error state -->
      <div v-else class="col-12">
        <div class="card">
          <div class="card-body text-center py-5">
            <i class="bx bx-error-circle display-1 text-danger"></i>
            <h4 class="mt-3">Không tìm thấy phiếu đối soát</h4>
            <p class="text-muted">Phiếu đối soát không tồn tại hoặc đã bị xóa.</p>
            <button type="button" class="btn btn-primary" @click="goBack">
              <i class="bx bx-arrow-back me-1"></i>
              Quay lại danh sách
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- Transfer Dialog -->
    <LadaDialog :visible="modalControl.Transfer">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title">
            <i class="bx bx-transfer me-2"></i>
            Cập nhật đã chuyển tiền
          </h5>
          <button @click="closeTransferModal" type="button" class="close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
      </template>
      <template #body>
        <TransferReconciliationForm :reconciliation="reconciliation" @cancel="closeTransferModal"
          @success="onTransferSuccess" />
      </template>
    </LadaDialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useToast } from 'vue-toastification';
import { useUserStore } from '@/stores/userStore';
import reconciliationService from '@/services/reconciliationService';
import financeExcelExportService from '@/services/financeExcelExportService';
import TransferReconciliationForm from './components/TransferReconciliationForm.vue';
import {
  formatCurrency,
  formatDate,
  formatDateTime
} from '@/infrastructure/utilities/reconciliationHelpers';
import {
  getReconciliationStatusClass,
  canConfirmReconciliation,
  canMarkAsTransferred,
  canCancelReconciliation,
  getTransferMethodLabel
} from '@/infrastructure/utilities/reconciliationConstants';

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

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

// Modal control
const modalControl = reactive({
  Transfer: false
});

// Data is now available directly from reconciliation object

// Methods
const loadReconciliation = async () => {
  try {
    pageLoading.value = true;

    const id = parseInt(route.params.id);
    if (!id) {
      toast.error('ID phiếu đối soát không hợp lệ');
      router.push({ name: 'reconciliation-list' });
      return;
    }

    const result = await reconciliationService.getById(id);

    if (result) {
      reconciliation.value = result;
      // Orders are now included in the reconciliation data
    } else {
      toast.error('Không tìm thấy phiếu đối soát');
    }
  } 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 {
    pageLoading.value = false;
  }
};

// Orders are now included in reconciliation data from server

const confirmReconciliation = async () => {
  if (!confirm(`Bạn có chắc chắn muốn xác nhận đối soát ${reconciliation.value.Code}?`)) {
    return;
  }

  try {
    actionLoading.value = true;

    const result = await reconciliationService.confirm(reconciliation.value.Id);
    if (result && result.Result === 1) {
      toast.success('Xác nhận đối soát thành công');
      // Reload reconciliation to get updated status
      await loadReconciliation();
    } else {
      toast.error(result?.Message || 'Có lỗi xảy ra khi xác nhận đối soát');
    }
  } catch (error) {
    console.error('Error confirming reconciliation:', error);
    toast.error('Có lỗi xảy ra khi xác nhận đối soát');
  } finally {
    actionLoading.value = false;
  }
};

const showTransferModal = () => {
  modalControl.Transfer = true;
};

const closeTransferModal = () => {
  modalControl.Transfer = false;
};

const onTransferSuccess = async () => {
  // Reload reconciliation to get updated status
  await loadReconciliation();
};

const cancelReconciliation = async () => {
  const reason = prompt('Nhập lý do hủy đối soát:');
  if (!reason) return;

  try {
    actionLoading.value = true;

    const result = await reconciliationService.cancel(reconciliation.value.Id, reason);
    if (result && result.Result === 1) {
      toast.success('Hủy đối soát thành công');
      // Reload reconciliation to get updated status
      await loadReconciliation();
    } else {
      toast.error(result?.Message || 'Có lỗi xảy ra khi hủy đối soát');
    }
  } catch (error) {
    console.error('Error cancelling reconciliation:', error);
    toast.error('Có lỗi xảy ra khi hủy đối soát');
  } finally {
    actionLoading.value = false;
  }
};

const exportToExcel = async () => {
  if (!reconciliation.value) {
    toast.error('Không có dữ liệu để xuất Excel');
    return;
  }

  if (!userStore.user) {
    toast.error('Vui lòng đăng nhập để sử dụng chức năng này');
    return;
  }

  try {
    actionLoading.value = true;
    
    // Gọi API xuất Excel chi tiết phiếu đối soát
    const result = await financeExcelExportService.exportReconciliationDetail(
      reconciliation.value.Id,
      userStore.user.Id,
      userStore.user.UserName
    );
    
    if (result && result.Result === 1) {
      // Sử dụng DownloadUrl có sẵn từ API response
      if (result.DownloadUrl) {
        // Tạo link download trực tiếp từ DownloadUrl
        const link = document.createElement('a');
        link.href = result.DownloadUrl;
        link.download = result.FileName || `Chi_tiet_doi_soat_${reconciliation.value.Code}_${new Date().toISOString().split('T')[0]}.xlsx`;
        link.target = '_blank'; // Mở trong tab mới để tránh vấn đề CORS
        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 to Excel:', error);
    toast.error('Có lỗi xảy ra khi xuất Excel');
  } finally {
    actionLoading.value = false;
  }
};

const goBack = () => {
  router.push({ name: 'reconciliation-list' });
};

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

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

.form-control-plaintext {
  padding-left: 0;
  padding-right: 0;
}

.badge.fs-6 {
  font-size: 1rem !important;
}

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

.display-1 {
  font-size: 6rem;
}

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

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

.tag-red {
  color: #fff;
  background-color: #dc3545;
}
</style>
