<template>
  <div class="container-fluid">
    <!-- Breadcrumb -->
    <div class="breadcrumb-header justify-content-between">
      <div class="my-auto">
        <h4 class="page-title">Tạo phiếu chuyển tiề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-search-customers' }">
              Tìm kiếm khách hàng
            </router-link>
          </li>
          <li class="breadcrumb-item active" aria-current="page">
            Tạo phiếu chuyển tiền
          </li>
        </ol>
      </div>
      <div class="d-flex align-items-center">
        <div class="d-flex gap-2">
          <button type="button" class="btn btn-outline-primary" @click="loadOrders" :disabled="loading">
            <i class="fe fe-refresh-cw me-2"></i>Tải lại
          </button>
          <router-link :to="{ name: 'transfer-payment-bill-search-customers' }" class="btn btn-secondary">
            <i class="fe fe-arrow-left me-2"></i>Quay lại
          </router-link>
        </div>
      </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">Tạo phiếu chuyển tiề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 danh sách đơn hàng...</p>
            </div>

            <!-- Content -->
            <div v-else>
              <!-- Header Info -->
              <div class="row mb-3">
                <div class="col-md-8">
                  <div class="d-flex align-items-center">
                    <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>
                      <h5 class="mb-1">
                        <i class="fe fe-user me-2"></i>
                        {{ customerInfo?.customerName || 'Khách hàng' }}
                      </h5>
                      <small class="text-muted">
                        ID: {{ customerInfo?.customerId }}
                        <span v-if="customerInfo?.customerPhone" class="ms-3">
                          <i class="fe fe-phone me-1"></i>{{ customerInfo.customerPhone }}
                        </span>
                        <span v-if="customerInfo?.customerEmail" class="ms-3">
                          <i class="fe fe-mail me-1"></i>{{ customerInfo.customerEmail }}
                        </span>
                      </small>
                      <div v-if="customerInfo?.customerAddress" class="text-muted small mt-1">
                        <i class="fe fe-map-pin me-1"></i>{{ customerInfo.customerAddress }}
                      </div>
                    </div>
                  </div>
                </div>
                <div class="col-md-4 text-end">
                  <!-- Selection info -->
                  <div class="selection-info">
                    <div class="text-muted small">Đã chọn: {{ selectedOrders.length }}/{{ orders.length }} đơn</div>
                    <div class="fw-bold text-success">{{ formatCurrency(totalSelectedAmount) }}</div>
                  </div>
                </div>
              </div>

              <!-- Orders Table -->
              <div v-if="orders.length === 0" class="text-center py-5">
                <empty></empty>
                <p class="text-muted">
                  Không có đơn hàng nào trong khoảng thời gian đã chọn
                </p>
              </div>

              <!-- Orders Table -->
              <div v-else class="table-responsive">
                <table class="table table-sm">
                  <thead>
                    <tr>
                      <!-- Checkbox column -->
                      <th width="40">
                        <div class="checkbox">
                          <div class="form-checkbox custom-control">
                            <input type="checkbox" class="custom-control-input" id="cbxAllOrders"
                              :checked="isAllSelected" @change="toggleSelectAll">
                            <label for="cbxAllOrders" class="custom-control-label mt-1"></label>
                          </div>
                        </div>
                      </th>
                      <th>Mã đơn hàng</th>
                      <th>Người gửi → Người nhận</th>
                      <th>Trạng thái</th>
                      <th>Tiền cước</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="order in orders" :key="order.OrderId">
                      <!-- Checkbox column -->
                      <td>
                        <div class="checkbox">
                          <div class="form-checkbox custom-control">
                            <input type="checkbox" class="custom-control-input" :id="'orderCheckbox_' + order.OrderId"
                              :value="order" v-model="selectedOrders">
                            <label :for="'orderCheckbox_' + order.OrderId" class="custom-control-label mt-1"></label>
                          </div>
                        </div>
                      </td>

                      <!-- Order Code -->
                      <td>
                        <strong>
                          <router-link :to="{ name: 'orderTrack', params: { code: order.OrderCode } }" target="_blank">
                            {{ order.OrderCode }}
                          </router-link>
                        </strong>
                        <br><small class="text-muted">{{ formatDate(order.OrderCreatedTime) }}</small>
                      </td>

                      <!-- Sender Info -->
                      <td>
                        <div class="small">
                          <div><strong>{{ order.SenderName || 'N/A' }}, {{ order.SenderAddress || 'N/A' }}</strong>
                          </div>
                          <div>↕</div>
                          <div><strong>{{ order.ReceiverName || 'N/A' }}, {{ order.ReceiverAddress || 'N/A' }}</strong>
                          </div>
                        </div>
                      </td>

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

                      <!-- Amount -->
                      <td>
                        <span class="fw-bold text-success">{{ order.TransferFeeAmountFormatted }}</span>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- Create Form -->
      <div class="col-lg-4 col-md-4 col-sm-12">
        <Form @submit="onSubmit" :validation-schema="schema">
          <div class="card">
            <div class="card-header">
              <h5 class="card-title">Thông tin phiếu chuyển tiền</h5>
            </div>
            <div class="card-body">
              <!-- Note Field -->
              <div class="mb-3">
                <label class="form-label">Ghi chú</label>
                <Field name="note" v-slot="{ field, errorMessage }">
                  <textarea v-bind="field" class="form-control" :class="{ 'is-invalid': errorMessage }" rows="3"
                    placeholder="Nhập ghi chú..."></textarea>
                  <div v-if="errorMessage" class="invalid-feedback">{{ errorMessage }}</div>
                </Field>
              </div>

              <!-- Transfer Info Field -->
              <div class="mb-3">
                <label class="form-label">Thông tin chuyển khoản</label>
                <Field name="transferInfo" v-slot="{ field, errorMessage }">
                  <textarea v-bind="field" class="form-control" :class="{ 'is-invalid': errorMessage }" rows="3"
                    placeholder="Nhập thông tin chuyển khoản..."></textarea>
                  <div v-if="errorMessage" class="invalid-feedback">{{ errorMessage }}</div>
                </Field>
              </div>

              <!-- File Upload -->
              <div class="mb-3">
                <label class="form-label">Tệp đính kèm</label>
                <input ref="fileInput" type="file" class="form-control" @change="handleFileSelect"
                  accept="image/*,.pdf,.doc,.docx,.xls,.xlsx">
                <div v-if="fileError" class="text-danger small mt-1">{{ fileError }}</div>

                <!-- File Preview -->
                <div v-if="selectedFile" class="mt-2">
                  <div class="d-flex align-items-center justify-content-between p-2 border rounded">
                    <div class="d-flex align-items-center">
                      <i class="fe fe-file me-2"></i>
                      <span class="small">{{ selectedFile.name }}</span>
                    </div>
                    <button type="button" class="btn btn-sm btn-outline-danger" @click="removeFile">
                      <i class="fe fe-x"></i>
                    </button>
                  </div>

                  <!-- Image Preview -->
                  <div v-if="imagePreviewUrl" class="mt-2">
                    <img :src="imagePreviewUrl" alt="Preview" class="img-thumbnail" style="max-width: 200px;">
                  </div>
                </div>
              </div>

              <!-- Submit Button -->
              <div class="d-grid">
                <div class="d-flex gap-2">
                  <button type="submit" class="btn btn-primary" :disabled="loading || selectedOrders.length === 0">
                    <span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
                    <i v-else class="fe fe-save me-2"></i>
                    {{ loading ? 'Đang tạo...' : 'Tạo phiếu chuyển tiền' }}
                  </button>
                  <button type="button" class="btn btn-outline-info me-2" @click="exportToExcel" :disabled="loading">
                    <span v-if="loading" class="spinner-border spinner-border-sm me-2"></span>
                    <i v-else class="bx bx-file-blank me-1"></i>
                    Xuất Excel
                  </button>
                </div>

              </div>

              <!-- Selection Summary -->
              <div v-if="selectedOrders.length > 0" class="mt-3 p-3 bg-light rounded">
                <div class="small text-muted mb-1">Tóm tắt:</div>
                <div class="d-flex justify-content-between">
                  <span>{{ selectedOrders.length }} đơn hàng</span>
                  <span class="fw-bold">{{ formatCurrency(totalSelectedAmount) }}</span>
                </div>
              </div>
            </div>
          </div>
        </Form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useToast } from 'vue-toastification';
import { Form, Field } from 'vee-validate';
import * as Yup from 'yup';
import transferPaymentBillService from '@/services/transferPaymentBillService';
import financeExcelExportService from '@/services/financeExcelExportService';
import { formatCurrency, formatDate } from '@/components/transfer-payment-bill/utils';
import { Empty } from '@/components';
import { useUserStore } from '@/stores/userStore';

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

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

// Data
const loading = ref(false);
const customerInfo = ref(null);
const orders = reactive([]);
const selectedOrders = ref([]);
const selectedFile = ref(null);
const fileError = ref('');
const fileInput = ref(null);
const imagePreviewUrl = ref('');

// Computed properties
const totalSelectedAmount = computed(() => {
  return selectedOrders.value.reduce((total, order) => {
    return total + (order.TransferFeeAmount || 0);
  }, 0);
});

const isAllSelected = computed(() => {
  return orders.length > 0 && selectedOrders.value.length === orders.length;
});

// Validation schema
const schema = Yup.object().shape({
  transferInfo: Yup.string()
    .max(1024, 'Thông tin chuyển khoản không được vượt quá 1024 ký tự'),
  note: Yup.string()
    .max(1024, 'Ghi chú không được vượt quá 1024 ký tự')
});

// Methods
async function loadOrders() {
  loading.value = true;
  orders.splice(0, orders.length);
  selectedOrders.value = [];

  try {
    const params = {
      customerId: props.customerId
    };

    const result = await transferPaymentBillService.getTransferableOrdersByCustomer(params);

    console.log('API Response:', result); // Debug log

    // API trả về object với Customer và Orders
    if (result && result.Customer && result.Orders) {
      // Load customer info từ API response
      customerInfo.value = {
        customerId: result.Customer.Id,
        customerName: result.Customer.FullName,
        customerPhone: result.Customer.PhoneNumber,
        customerEmail: result.Customer.Email,
        customerAddress: result.Customer.Address,
        totalOrderCount: result.TotalOrders,
        totalTransferFeeAmount: result.TotalAmount
      };

      // Load orders từ API response
      if (Array.isArray(result.Orders) && result.Orders.length > 0) {
        result.Orders.forEach(order => {
          orders.push(order);
        });
      } else {
        toast.info('Không có đơn hàng nào cho khách hàng này');
      }
    } else {
      toast.info('Không có dữ liệu cho khách hàng này');
    }
  } catch (error) {
    console.error('Error loading orders:', error);
    toast.error('Có lỗi xảy ra khi tải danh sách đơn hàng');
  } finally {
    loading.value = false;
  }
}

function toggleSelectAll() {
  if (isAllSelected.value) {
    selectedOrders.value = [];
  } else {
    selectedOrders.value = [...orders];
  }
}

// File handling methods
function handleFileSelect(event) {
  const file = event.target.files[0];
  if (!file) {
    removeFile();
    return;
  }

  // Validate file size (max 10MB)
  const maxSize = 10 * 1024 * 1024; // 10MB
  if (file.size > maxSize) {
    fileError.value = 'Kích thước file không được vượt quá 10MB';
    return;
  }

  // Validate file type
  const allowedTypes = [
    'image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/bmp', 'image/webp',
    'application/pdf',
    'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  ];

  if (!allowedTypes.includes(file.type)) {
    fileError.value = 'Loại file không được hỗ trợ. Chỉ chấp nhận: hình ảnh, PDF, Word, Excel';
    return;
  }

  selectedFile.value = file;
  fileError.value = '';

  // Create preview URL for images
  if (file.type.startsWith('image/')) {
    const reader = new FileReader();
    reader.onload = (e) => {
      imagePreviewUrl.value = e.target.result;
    };
    reader.readAsDataURL(file);
  } else {
    imagePreviewUrl.value = '';
  }
}

function removeFile() {
  selectedFile.value = null;
  imagePreviewUrl.value = '';
  fileError.value = '';
  if (fileInput.value) {
    fileInput.value.value = '';
  }
}

// Submit form
async function onSubmit(values) {
  if (selectedOrders.value.length === 0) {
    toast.warning('Vui lòng chọn ít nhất một đơn hàng');
    return;
  }

  if (!selectedFile.value) {
    toast.warning('Vui lòng chọn file đính kèm');
    return;
  }

  loading.value = true;

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

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

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

    // Add file
    formData.append('Files', selectedFile.value);

    // Handle null/undefined values
    if (values.note == null || values.note == undefined) {
      values.note = '';
    }
    if (values.transferInfo == null || values.transferInfo == undefined) {
      values.transferInfo = '';
    }

    // Add other fields
    formData.append('Note', values.note || '');
    formData.append('TransferInfo', values.transferInfo || '');

    console.log(formData);

    const result = await transferPaymentBillService.create(formData);

    if (result.Result === 1) {
      toast.success('Tạo phiếu chuyển tiền thành công');

      // Clear session storage
      sessionStorage.removeItem('transferPaymentBillCreateData');
      sessionStorage.removeItem('transferPaymentBillCustomers');

      // Navigate to detail page
      router.push({
        name: 'transfer-payment-bill-detail',
        params: { id: result.Id }
      });
    } else {
      console.log('Trạng thái khác 1');
      toast.error(result.Message || 'Có lỗi xảy ra khi tạo phiếu chuyển tiền');
    }
  } catch (error) {
    console.log('vào catch');
    console.error('Error creating bill:', error);
    toast.error('Có lỗi xảy ra khi tạo phiếu chuyển tiền');
  } finally {
    loading.value = false;
  }
}


// Excel export method
async function exportToExcel() {

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

  try {
    loading.value = true;

    // Gọi API xuất Excel chi tiết phiếu chuyển khoản
    const result = await financeExcelExportService.exportCustomerTransferableOrdersExcel(
      {
        customerId: props.customerId
      }
    );

    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 || `Danh_sach_don_chuyen_khoan_${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 {
    loading.value = false;
  }
}

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

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

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

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

.checkbox {
  display: flex;
  align-items: center;
  justify-content: center;
}

.pd-l-7 {
  padding-left: 7px;
}
</style>
