<template>
  <div class="container-fluid">
    <!-- Breadcrumb -->
    <div class="breadcrumb-header justify-content-between">
      <div class="my-auto">
        <h4 class="page-title">Chi tiết hóa đơn thanh toán</h4>
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="/">Trang chủ</a></li>
          <li class="breadcrumb-item">Tài chính</li>
          <li class="breadcrumb-item">
            <router-link :to="{ name: 'transfer-payment-bill' }">
              Hóa đơn thanh toán chuyển khoản
            </router-link>
          </li>
          <li class="breadcrumb-item">
            <router-link :to="{ name: 'transfer-payment-bill-list' }">
              Danh sách hóa đơn
            </router-link>
          </li>
          <li class="breadcrumb-item active" aria-current="page">
            Chi tiết hóa đơn
          </li>
        </ol>
      </div>

    </div>

    <div class="row">
      <div class="col-lg-8 col-md-8 col-sm-12">
        <div class="card">
          <div class="card-header">
            <h4 class="card-title">Chi tiết hóa đơn thanh toán</h4>
          </div>
          <div class="card-body">
            <!-- Loading State -->
            <div v-if="loading" class="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">Đang tải chi tiết hóa đơn...</p>
            </div>

            <!-- Content -->
            <div v-else>
              <!-- Empty State -->
              <div v-if="!billDetail" class="text-center py-5">
                <empty></empty>
                <p class="text-muted">Không tìm thấy hóa đơn hoặc bạn không có quyền xem</p>
              </div>

              <!-- Bill Detail Content -->
              <div v-else>
                <!-- Header Info with Customer and Additional Information -->
                <div class="row mb-3">
                  <!-- Customer Information - Left Side -->
                  <div class="col-12">
                    <div class="d-flex align-items-start">
                      <div class="me-3">
                        <div class="avatar avatar-lg bg-primary-transparent rounded-circle">
                          <i class="fe fe-user tx-primary"></i>
                        </div>
                      </div>
                      <div class="flex-grow-1">
                        <h5 class="mb-2">{{ billDetail.CustomerName || 'Khách hàng' }}</h5>

                        <div class="mb-2">
                          <small class="text-muted">
                            <i class="fe fe-hash me-1"></i>ID: {{ billDetail.CustomerId }}
                            <span v-if="billDetail.CustomerPhone" class="ms-3">
                              <i class="fe fe-phone me-1"></i>{{ billDetail.CustomerPhone }}
                            </span>
                            <span v-if="billDetail.CustomerEmail" class="ms-3">
                              <i class="fe fe-mail me-1"></i>{{ billDetail.CustomerEmail }}
                            </span>
                          </small>
                        </div>

                        <div v-if="billDetail.CustomerAddress" class="mb-2">
                          <small class="text-muted">
                            <i class="fe fe-map-pin me-1"></i>{{ billDetail.CustomerAddress }}
                          </small>
                        </div>
                      </div>
                    </div>

                  </div>

                </div>



                <!-- Orders Table -->
                <div v-if="!billDetail.Orders || billDetail.Orders.length === 0" class="text-center py-5">
                  <empty></empty>
                  <p class="text-muted">Không có đơn hàng nào</p>
                </div>

                <!-- Orders Table -->
                <div v-else class="table-responsive">
                  <table class="table table-striped">
                    <thead>
                      <tr>
                        <th>Mã đơn hàng</th>
                        <th>Thông tin gửi</th>
                        <th>Thông tin nhận</th>
                        <th>Trạng thái</th>
                        <th>Ngày tạo</th>
                        <th>Tiền cước</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr v-for="order in billDetail.Orders" :key="order.OrderId">
                        <!-- Order Code -->
                        <td>
                          <strong>
                            <router-link :to="{ name: 'orderTrack', params: { code: order.OrderCode } }"
                              target="_blank">
                              {{ order.OrderCode }}
                            </router-link>
                          </strong>
                        </td>

                        <!-- Sender Info -->
                        <td>
                          <div>
                            <strong>{{ order.SenderName || 'N/A' }}</strong><br>
                            <small class="text-muted">{{ order.SenderAddress || 'N/A' }}</small>
                          </div>
                        </td>

                        <!-- Receiver Info -->
                        <td>
                          <div>
                            <strong>{{ order.ReceiverName || 'N/A' }}</strong><br>
                            <small class="text-muted">{{ order.ReceiverAddress || 'N/A' }}</small>
                          </div>
                        </td>

                        <!-- Status -->
                        <td>
                          <OrderStatus :type="1" :value="order.Status" :name="order.StatusStr"> </OrderStatus>
                          <OrderStatus :type="2" :value="order.PhysicalStatus" :name="order.PhysicalStatusStr">
                          </OrderStatus>
                        </td>

                        <!-- Created Time -->
                        <td>
                          <small>{{ formatDate(order.OrderCreatedTime, true) }}</small>
                        </td>

                        <!-- Amount -->
                        <td>
                          <span class="fw-bold text-success">{{ order.TransferFeeAmountFormatted }}</span>
                        </td>
                      </tr>
                    </tbody>
                    <tfoot>
                      <tr class="table-info">
                        <td colspan="5" class="text-end fw-bold">Tổng cộng:</td>
                        <td class="fw-bold text-success">{{ formatCurrency(billDetail.TotalAmount) }}</td>
                      </tr>
                    </tfoot>
                  </table>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Action Panel -->
      <div class="col-lg-4 col-md-4 col-sm-12">
        <!-- Bill Information Card -->
        <div class="card mb-3" v-if="billDetail">
          <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="card-title mb-0">Thông tin phiếu thanh toán</h5>
            <span :class="getStatusBadgeClass(billDetail.Status)">
              {{ getStatusText(billDetail.Status) }}
            </span>
          </div>
          <div class="card-body">
            <div class="row">
              <!-- Bill Details - Left Half -->
              <div class="col-md-6">
                <div class="mb-3">
                  <div>

                    <div class="d-flex justify-content-between mb-1 mt-2">
                      <span><i class="fe fe-hash me-1"></i> Mã hóa đơn:</span>
                      <span class="fw-bold">{{ billDetail.Code }}</span>
                    </div>

                    <div class="d-flex justify-content-between mb-1 mt-2">
                      <span><i class="fe fe-clock me-1"></i> Ngày tạo:</span>
                      <span class="fw-bold">{{ billDetail.CreatedTimeDisplay }}</span>
                    </div>

                    <div class="d-flex justify-content-between mb-1 mt-2">
                      <span><i class="fe fe-user me-1"></i> Người tạo:</span>
                      <span class="fw-bold">{{ billDetail.CreatedByUserName }}</span>
                    </div>

                    <!-- <div class="d-flex justify-content-between mb-1 mt-2">
                      <span><i class="fe fe-edit me-1"></i> Cập nhật:</span>
                      <span class="fw-bold">{{ billDetail.UpdatedTimeDisplay }}</span>
                    </div> -->

                    <div class="d-flex justify-content-between mb-1 mt-2">
                      <span><i class="fe fe-package me-1"></i>Số đơn hàng:</span>
                      <span class="fw-bold">{{ billDetail.OrderCount }}</span>
                    </div>
                    <div class="d-flex justify-content-between mt-2">
                      <span><i class="fe fe-dollar-sign me-1"></i>Tổng tiền:</span>
                      <span class="fw-bold text-success">{{ formatCurrency(billDetail.TotalAmount) }}</span>
                    </div>
                    <div v-if="billDetail.ApprovedBy || billDetail.TransactionId"
                      class="d-flex justify-content-between mt-2">
                      <span><i class="fe fe-check-circle me-1"></i>Duyệt bởi:</span>
                      <span class="fw-bold text-success">{{ billDetail.ApprovedByUsername }}</span>
                    </div>
                    <div v-if="billDetail.ApprovedBy || billDetail.TransactionId"
                      class="d-flex justify-content-between mt-2">
                      <span><i class="fe fe-clock me-1"></i>Ngày duyệt:</span>
                      <span class="fw-bold text-success"> {{ billDetail.ApprovedDateDisplay }}

                      </span>
                    </div>
                  </div>
                </div>
              </div>

              <!-- User Input Information - Right Half -->
              <div class="col-md-6">
                <div v-if="billDetail.Note || billDetail.TransferInfo || billDetail.MediaUrl">
                  <div v-if="billDetail.Note || billDetail.TransferInfo" class="mb-3">
                    <div class="">
                      <div v-if="billDetail.Note" class="mb-2">
                        <span class="fw-bold">Ghi chú:</span>
                        <span class="ms-1">{{ billDetail.Note }}</span>
                      </div>
                      <div v-if="billDetail.TransferInfo">
                        <span class="fw-bold">Thông tin chuyển khoản:</span>
                        <span class="ms-1">{{ billDetail.TransferInfo }}</span>
                      </div>
                    </div>
                  </div>
                  <div v-if="billDetail.MediaUrl">
                    <label class="form-label fw-bold small">File đính kèm:</label>
                    <div class="mt-2">
                      <!-- Image Preview with Viewer -->
                      <div v-if="isImageFile(billDetail.MediaUrl)" class="media-preview mb-2">
                        <viewer>
                          <div class="image-container">
                            <img :src="billDetail.MediaUrl" class="media-image"
                              :alt="'File đính kèm - ' + billDetail.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(billDetail.MediaUrl)" :href="billDetail.MediaUrl" target="_blank"
                        class="btn btn-outline-primary btn-sm">
                        <i class="fe fe-download me-2"></i>Tải xuống file
                      </a>
                    </div>
                  </div>
                </div>
              </div>
            </div>



            <!-- Action Buttons -->
            <div class="mt-2 pt-3 border-top d-flex justify-content-between align-items-center gap-2">
              <!-- Left side - Back button -->
              <router-link :to="{ name: 'transfer-payment-bill-list' }" class="btn btn-link">
                <i class="fe fe-arrow-left me-2"></i>Quay lại danh sách
              </router-link>

              <!-- Right side - Action buttons -->
              <div class="d-flex gap-2">
                <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="billDetail.CanCancel" @click="cancelBill" class="btn btn-outline-danger">
                  <i class="fe fe-x me-2"></i>Từ chối
                </button>
                <button v-if="billDetail.CanApprove" @click="approveBill" class="btn btn-outline-success">
                  <i class="fe fe-check me-2"></i>Đã nhận
                </button>
              </div>
            </div>

          </div>
        </div>

      </div>
    </div>

    <!-- Cancel Dialog -->
    <LadaDialog :visible="showCancelDialog">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title">Xác nhận từ chối hóa đơn</h5>
          <button @click="closeCancelDialog" type="button" class="close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
      </template>
      <template #body>
        <CancelForm @confirmed="handleCancelConfirmed" @cancel="closeCancelDialog" />
      </template>
    </LadaDialog>

    <!-- Approve Dialog -->
    <LadaDialog :visible="showApproveDialog">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title">Duyệt hóa đơn</h5>
          <button @click="closeApproveDialog" type="button" class="close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
      </template>
      <template #body>
        <ApproveForm @confirmed="handleApproveConfirmed" @cancel="closeApproveDialog" />
      </template>
    </LadaDialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, reactive, onUnmounted, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { useToast } from 'vue-toastification';
import { useUserStore } from '@/stores/userStore';
import transferPaymentBillService from '@/services/transferPaymentBillService';
import financeExcelExportService from '@/services/financeExcelExportService';
import { formatCurrency, formatDate } from '@/components/transfer-payment-bill/utils';
import { StatusBadge, Empty, LadaDialog, OrderStatus } from '@/components';
import CancelForm from '@/views/finances/transfer-payment-bill/components/CancelForm.vue';
import ApproveForm from '@/views/finances/transfer-payment-bill/components/ApproveForm.vue';

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

// Props from route
const props = defineProps({
  id: {
    type: [String, Number],
    required: true
  }
});

// Data
const loading = ref(false);
const actionLoading = ref(false);
const billDetail = ref(null);

// Dialog visibility
const showCancelDialog = ref(false);
const showApproveDialog = ref(false);

// Utility methods
function 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));
}

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

// Status utility methods
function getStatusText(status) {
  const statusMap = {
    1: 'Nháp',
    2: 'Đã duyệt',
    8: 'Đã hủy'
  };
  return statusMap[status] || 'Không xác định';
}

function getStatusBadgeClass(status) {
  const baseClass = 'badge';
  const statusClassMap = {
    1: `${baseClass} bg-warning text-dark`, // Draft - Warning (yellow)
    2: `${baseClass} bg-success`,           // Approved - Success (green)
    8: `${baseClass} bg-danger`             // Cancelled - Danger (red)
  };
  return statusClassMap[status] || `${baseClass} bg-secondary`;
}

// Methods
async function loadBillDetail() {
  if (!props.id) {
    toast.error('ID hóa đơn không hợp lệ');
    router.push({ name: 'transfer-payment-bill-list' });
    return;
  }

  loading.value = true;
  billDetail.value = null;

  try {
    const result = await transferPaymentBillService.getById(props.id);

    if (result) {
      billDetail.value = result;
    } else {
      toast.error('Không tìm thấy hóa đơn hoặc bạn không có quyền xem');
      router.push({ name: 'transfer-payment-bill-list' });
    }
  } catch (error) {
    console.error('Error loading bill detail:', error);
    toast.error('Có lỗi xảy ra khi tải chi tiết hóa đơn');
    router.push({ name: 'transfer-payment-bill-list' });
  } finally {
    loading.value = false;
  }
}

// Action methods
function cancelBill() {
  if (!billDetail.value?.CanCancel) {
    toast.warning('Không thể hủy hóa đơn này');
    return;
  }

  showCancelDialog.value = true;
}

function approveBill() {
  if (!billDetail.value?.CanApprove) {
    toast.warning('Không thể duyệt hóa đơn này');
    return;
  }

  showApproveDialog.value = true;
}

function closeCancelDialog() {
  showCancelDialog.value = false;
}

function closeApproveDialog() {
  showApproveDialog.value = false;
}

async function handleCancelConfirmed(payload) {
  if (!billDetail.value?.Id) return;

  loading.value = true;

  try {
    const requestData = {
      transferPaymentBillId: billDetail.value.Id,
      cancelReason: payload.cancelReason
    };

    const result = await transferPaymentBillService.cancel(requestData);

    if (result.Result === 1) {
      toast.success('Từ chối hóa đơn thành công');
      showCancelDialog.value = false; // Close dialog
      await loadBillDetail(); // Reload to get updated status
    } else {
      toast.error(result.message || 'Có lỗi xảy ra khi từ chối hóa đơn');
    }
  } catch (error) {
    console.error('Error canceling bill:', error);
    toast.error('Có lỗi xảy ra khi từ chối hóa đơn');
  } finally {
    loading.value = false;
  }
}

async function handleApproveConfirmed(payload) {
  if (!billDetail.value?.Id) return;

  loading.value = true;

  try {
    const result = await transferPaymentBillService.approve({
      id: billDetail.value.Id,
      approvalNote: payload.approvalNote
    });

    if (result.Result === 1) {
      toast.success('Duyệt hóa đơn thành công');
      showApproveDialog.value = false; // Close dialog
      await loadBillDetail(); // Reload to get updated status
    } else {
      toast.error(result.message || 'Có lỗi xảy ra khi duyệt hóa đơn');
    }
  } catch (error) {
    console.error('Error approving bill:', error);
    toast.error('Có lỗi xảy ra khi duyệt hóa đơn');
  } finally {
    loading.value = false;
  }
}

// Excel export method
async function exportToExcel() {
  if (!billDetail.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 chuyển khoản
    const result = await financeExcelExportService.exportTransferPaymentBillDetail(
      billDetail.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_phieu_chuyen_khoan_${billDetail.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;
  }
}

// Load initial data
onMounted(() => {
  loadBillDetail();
});

// Cleanup on unmount
onUnmounted(() => {
  showCancelDialog.value = false;
  showApproveDialog.value = false;
});

// Watch for prop changes
watch(() => props.id, () => {
  loadBillDetail();
});
</script>

<style scoped>
.bill-info {
  text-align: right;
}

.bill-info .small {
  font-size: 0.875rem;
}

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

.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: 120px;
  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;
}

/* Modal Styles */
.modal-header {
  border-bottom: 1px solid #dee2e6;
  padding: 1rem;
}

.modal-header .close {
  background: none;
  border: none;
  font-size: 1.5rem;
  font-weight: bold;
  color: #6c757d;
  cursor: pointer;
  padding: 0;
  margin: 0;
  line-height: 1;
}

.modal-header .close:hover {
  color: #343a40;
}

.modal-footer {
  border-top: 1px solid #dee2e6;
  padding: 1rem;
  display: flex;
  justify-content: flex-end;
  gap: 0.5rem;
}

.modal-title {
  margin: 0;
  font-size: 1.25rem;
  font-weight: 600;
  color: #495057;
}

/* Prevent body scroll when modal is open */
.modal.show {
  overflow: hidden;
}

.modal.show~body {
  overflow: hidden;
}

/* Form validation styles */
.form-label .text-danger {
  color: #dc3545;
}

.form-control:invalid {
  border-color: #dc3545;
}

.form-control:invalid:focus {
  border-color: #dc3545;
  box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25);
}

/* Spinner styles for action buttons */
.spinner-border-sm {
  width: 1rem;
  height: 1rem;
}
</style>
