<template>
  <div>
    <!-- Breadcrumb Header -->
    <div class="breadcrumb-header justify-content-between">
      <div class="my-auto">
        <h4 class="page-title">Tạo đối soát cước mới</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 cước</a></li>
          <li class="breadcrumb-item"><a href="javascript:void(0);">Khách hàng cần đối soát</a></li>
          <li class="breadcrumb-item active" aria-current="page">Tạo đối soát cước mới</li>
        </ol>
      </div>
    </div>
    <div class="row row-sm">
      <!-- Customer 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
            </h5>
          </div>
          <div class="card-body">
            <div v-if="customerLoading" class="text-center py-4">
              <span class="spinner-border spinner-border-sm"></span>
              <span class="ms-2">Đang tải thông tin khách hàng...</span>
            </div>
            <div v-else-if="customerInfo" 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">{{ customerInfo.FullName || 'Chưa có' }}</div>
                </div>
                <div class="mb-3">
                  <label class="form-label fw-semibold">Số điện thoại</label>
                  <div class="form-control-plaintext">{{ customerInfo.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">{{ customerInfo.Email || 'Chưa có' }}</div>
                </div>
                <div class="mb-3">
                  <label class="form-label fw-semibold">Địa chỉ</label>
                  <div class="form-control-plaintext">{{ customerInfo.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">{{ customerInfo.Manager?.FullName || '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="customerInfo.Status === 1 ? 'tag tag-green' : 'tag tag-red'">
                      {{ customerInfo.StatusStr || 'Chưa có' }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
            <div v-else class="text-center py-4 text-muted">
              Không tìm thấy thông tin khách hàng
            </div>
          </div>
        </div>
      </div>

      <!-- Bank Account Selection 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-credit-card me-2"></i>
              Chọn tài khoản ngân hàng
            </h5>
          </div>
          <div class="card-body">
            <div v-if="bankAccountsLoading" class="text-center py-4">
              <span class="spinner-border spinner-border-sm"></span>
              <span class="ms-2">Đang tải danh sách tài khoản ngân hàng...</span>
            </div>
            <div v-else-if="bankAccounts.length > 0">
              <div class="mb-3">
                <div class="d-flex justify-content-between align-items-center mb-2">
                  <label class="form-label fw-semibold mb-0">Chọn tài khoản ngân hàng</label>
                  <button type="button" class="btn btn-sm btn-outline-primary" @click="openCreateBankAccountModal">
                    <i class="fe fe-plus me-1"></i>
                    Tạo mới
                  </button>
                </div>
                <v-select :options="bankAccounts" :reduce="(account) => account" label="AccountNumber"
                  v-model="selectedBankAccount" @update:model-value="onBankAccountChange"
                  placeholder="Chọn tài khoản ngân hàng...">
                  <template #option="{ AccountNumber, AccountHolderName, BankName, IsDefault }">
                    <div class="d-flex justify-content-between align-items-center">
                      <div>
                        <div class="fw-semibold">{{ AccountNumber }}</div>
                        <div class="text-muted tx-12">{{ AccountHolderName }} - {{ BankName }}</div>
                      </div>
                      <div v-if="IsDefault">
                        <span class="badge bg-primary">Mặc định</span>
                      </div>
                    </div>
                  </template>
                </v-select>
              </div>
            </div>
            <div v-else class="text-center py-4">
              <div class="text-muted mb-3">Chưa có tài khoản ngân hàng nào</div>
              <button type="button" class="btn btn-primary" @click="openCreateBankAccountModal">
                <i class="fe fe-plus me-1"></i>
                Tạo tài khoản ngân hàng
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Order Selection Section -->
    <div class="row row-sm">
      <div class="col-sm-12 grid-margin">
        <div class="card shadow-none">
          <div class="card-header">
            <h5 class="card-title mb-0">
              <i class="fe fe-package me-2"></i>
              Chọn đơn hàng đối soát cước
            </h5>
          </div>
          <div class="card-body">
            <!-- Date Range Selection -->
            <div class="row mb-3">
              <div class="col-md-3">
                <label class="form-label fw-semibold">Từ ngày <span class="text-danger">*</span></label>
                <input type="date" v-model="formData.fromDate" class="form-control"
                  :class="{ 'is-invalid': errors.fromDate }" />
                <div v-if="errors.fromDate" class="invalid-feedback">{{ errors.fromDate }}</div>
              </div>
              <div class="col-md-3">
                <label class="form-label fw-semibold">Đến ngày <span class="text-danger">*</span></label>
                <input type="date" v-model="formData.toDate" class="form-control"
                  :class="{ 'is-invalid': errors.toDate }" />
                <div v-if="errors.toDate" class="invalid-feedback">{{ errors.toDate }}</div>
              </div>
              <div class="col-md-3 d-flex align-items-end">
                <button type="button" class="btn btn-primary" @click="loadOrders" :disabled="!canLoadOrders">
                  <i class="fe fe-search me-1"></i>
                  Tải đơn hàng
                </button>
              </div>
            </div>

            <!-- Orders List -->
            <div v-if="orders.length > 0">
              <div class="d-flex justify-content-between align-items-center mb-3">
                <div>
                  <span class="fw-semibold">Tổng: {{ orders.length }} đơn hàng</span>
                  <span class="text-muted ms-2">({{ formData.orderIds.length }} đã chọn)</span>
                </div>
                <div>
                  <button type="button" class="btn btn-sm btn-outline-primary me-2" @click="selectAllOrders">
                    Chọn tất cả
                  </button>
                  <button type="button" class="btn btn-sm btn-outline-secondary" @click="deselectAllOrders">
                    Bỏ chọn tất cả
                  </button>
                </div>
              </div>

              <div class="table-responsive">
                <table class="table table-sm table-hover">
                  <thead>
                    <tr>
                      <th width="50">
                        <input type="checkbox" class="form-check-input"
                          :checked="formData.orderIds.length === orders.filter(o => o.CanReconcile).length"
                          @change="toggleAllOrders" />
                      </th>
                      <th>Mã đơn hàng</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>Trạng thái</th>
                    </tr>
                  </thead>
                  <tbody>
                    <tr v-for="order in orders" :key="order.Id" :class="{ 'table-secondary': !order.CanReconcile }">
                      <td>
                        <input type="checkbox" class="form-check-input" :value="order.Id" v-model="formData.orderIds"
                          :disabled="!order.CanReconcile" />
                      </td>
                      <td>
                        <div class="fw-semibold">{{ order.Code }}</div>
                        <div class="text-muted tx-12">{{ order.ReceiverName }}</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>
                        <span :class="getOrderStatusClass(order.Status)">
                          {{ order.StatusStr }}
                        </span>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>

              <!-- Summary -->
              <div class="row mt-3">
                <div class="col-md-6">
                  <div class="card bg-light">
                    <div class="card-body py-2">
                      <div class="row text-center">
                        <div class="col-4">
                          <div class="fw-semibold">{{ formData.orderIds.length }}</div>
                          <div class="text-muted tx-12">Đơn hàng</div>
                        </div>
                        <div class="col-4">
                          <div class="fw-semibold">{{ formatCurrency(totalShippingFeeAmount) }}</div>
                          <div class="text-muted tx-12">Tổng cước</div>
                        </div>
                        <div class="col-4">
                          <div class="fw-semibold text-success">{{ formatCurrency(totalNetAmount) }}</div>
                          <div class="text-muted tx-12">Thực chuyển</div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div v-else-if="formData.customerId" class="text-center py-4 text-muted">
              Chọn khoảng thời gian và nhấn "Tải đơn hàng" để hiển thị danh sách đơn hàng có thể đối soát cước
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Form Actions -->
    <div class="row row-sm">
      <div class="col-sm-12 grid-margin">
        <div class="card shadow-none">
          <div class="card-header">
            <h5 class="card-title mb-0">
              <i class="fe fe-edit me-2"></i>
              Thông tin bổ sung
            </h5>
          </div>
          <div class="card-body">
            <div class="row">
              <div class="col-md-6">
                <div class="mb-3">
                  <label class="form-label">Ghi chú</label>
                  <textarea v-model="formData.note" class="form-control" rows="3"
                    placeholder="Nhập ghi chú cho phiếu đối soát..."></textarea>
                </div>
              </div>
              <div class="col-md-6">
                <div class="mb-3">
                  <label class="form-label">Thông tin chuyển tiền</label>
                  <textarea v-model="formData.transferInfo" class="form-control" rows="3"
                    placeholder="Nhập thông tin chuyển tiền..."></textarea>
                </div>
                <div class="form-check">
                  <input type="checkbox" v-model="formData.autoConfirm" class="form-check-input" id="autoConfirm">
                  <label class="form-check-label" for="autoConfirm">
                    Tự động xác nhận sau khi tạo
                  </label>
                </div>
              </div>
            </div>

            <!-- Action Buttons -->
            <div class="row mt-4">
              <div class="col-12">
                <div class="d-flex gap-2">
                  <button type="button" class="btn btn-primary" @click="handleSubmit" :disabled="submitting">
                    <span v-if="submitting" class="spinner-border spinner-border-sm me-2"></span>
                    <i v-else class="fe fe-save me-2"></i>
                    {{ submitting ? 'Đang tạo...' : 'Tạo đối soát' }}
                  </button>
                  <button type="button" class="btn btn-outline-secondary" @click="handleCancel" :disabled="submitting">
                    <i class="fe fe-x me-2"></i>
                    Hủy
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useToast } from 'vue-toastification';
import reconciliationService from '@/services/reconciliationService';
import customerService from '@/services/customerService';
import customerBankAccountService from '@/services/customerBankAccountService';
import { ReconciliationType } from '@/infrastructure/utilities/reconciliationConstants';
import {
  formatCurrency,
  formatDate,
  getDefaultDateRange,
  dateToISOString,
  calculateTotalShippingFeeAmount,
  calculateNetAmount
} from '@/infrastructure/utilities/reconciliationHelpers';

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

// Reactive data
const submitting = ref(false);
const orders = ref([]);
const customerInfo = ref(null);
const customerLoading = ref(false);
const bankAccounts = ref([]);
const bankAccountsLoading = ref(false);
const selectedBankAccount = ref(null);
const showCreateBankAccountModal = ref(false);

const formData = reactive({
  customerId: null,
  fromDate: null,
  toDate: null,
  orderIds: [],
  note: '',
  bankAccountNumber: '',
  bankAccountHolderName: '',
  bankCode: '',
  bankName: '',
  bankBranchName: '',
  bankBranchAddress: '',
  transferInfo: '',
  autoConfirm: false,
  reconciliationType: ReconciliationType.ShippingFee // Thêm loại đối soát
});

const errors = reactive({
  fromDate: '',
  toDate: '',
  bankAccountNumber: '',
  bankAccountHolderName: '',
});

// Computed properties
const canLoadOrders = computed(() => {
  return formData.customerId && formData.fromDate && formData.toDate;
});

const totalShippingFeeAmount = computed(() => {
  return calculateTotalShippingFeeAmount(orders.value, formData.orderIds);
});

const totalNetAmount = computed(() => {
  return calculateNetAmount(orders.value, formData.orderIds);
});

// Methods

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 openCreateBankAccountModal = () => {
  showCreateBankAccountModal.value = true;
};

const onBankAccountChange = (account) => {
  if (account) {
    formData.bankAccountNumber = account.AccountNumber;
    formData.bankAccountHolderName = account.AccountHolderName;
    formData.bankCode = account.BankCode;
    formData.bankName = account.BankName;
    formData.bankBranchName = account.BranchName;
    formData.bankBranchAddress = account.BranchAddress;
  }
};

const loadOrders = async () => {
  if (!canLoadOrders.value) return;

  try {
    const searchModel = {
      Pagination: { PageIndex: 1, PageSize: 1000, Total: 0 },
      Sort: { Predicate: '', Reverse: false },
      Search: {
        PredicateObject: {
          CustomerId: formData.customerId,
          FromDate: formData.fromDate,
          ToDate: formData.toDate
        }
      }
    };

    const result = await reconciliationService.getReconciliableOrders(searchModel, ReconciliationType.ShippingFee);
    orders.value = result.Items || [];
    formData.orderIds = [];
  } 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');
  }
};

const selectAllOrders = () => {
  formData.orderIds = orders.value
    .filter(order => order.CanReconcile)
    .map(order => order.Id);
};

const deselectAllOrders = () => {
  formData.orderIds = [];
};

const toggleAllOrders = (event) => {
  if (event.target.checked) {
    selectAllOrders();
  } else {
    deselectAllOrders();
  }
};

const loadCustomerInfo = async () => {
  if (!formData.customerId) return;

  try {
    customerLoading.value = true;
    const result = await customerService.getById(formData.customerId);
    customerInfo.value = result;
  } catch (error) {
    console.error('Error loading customer info:', error);
    toast.error('Có lỗi xảy ra khi tải thông tin khách hàng');
  } finally {
    customerLoading.value = false;
  }
};

const loadBankAccounts = async () => {
  if (!formData.customerId) return;

  try {
    bankAccountsLoading.value = true;
    const result = await customerBankAccountService.getByCustomerId(formData.customerId);
    bankAccounts.value = result || [];

    // Auto select default bank account
    const defaultAccount = bankAccounts.value.find(account => account.IsDefault);
    if (defaultAccount) {
      selectedBankAccount.value = defaultAccount;
      onBankAccountChange(defaultAccount);
    }
  } catch (error) {
    console.error('Error loading bank accounts:', error);
    toast.error('Có lỗi xảy ra khi tải danh sách tài khoản ngân hàng');
  } finally {
    bankAccountsLoading.value = false;
  }
};

const handleSubmit = async () => {
  // Validate form
  errors.fromDate = '';
  errors.toDate = '';
  errors.bankAccountNumber = '';
  errors.bankAccountHolderName = '';

  let hasError = false;

  if (!formData.fromDate) {
    errors.fromDate = 'Vui lòng chọn từ ngày';
    hasError = true;
  }

  if (!formData.toDate) {
    errors.toDate = 'Vui lòng chọn đến ngày';
    hasError = true;
  }

  if (!formData.bankAccountNumber) {
    errors.bankAccountNumber = 'Vui lòng chọn tài khoản ngân hàng';
    hasError = true;
  }

  if (!formData.bankAccountHolderName) {
    errors.bankAccountHolderName = 'Vui lòng chọn tài khoản ngân hàng';
    hasError = true;
  }

  if (formData.orderIds.length === 0) {
    toast.error('Vui lòng chọn ít nhất một đơn hàng');
    hasError = true;
  }

  if (hasError) return;

  try {
    submitting.value = true;

    const submitData = {
      customerId: formData.customerId,
      fromDate: formData.fromDate,
      toDate: formData.toDate,
      orderIds: formData.orderIds,
      note: formData.note,
      bankAccountNumber: formData.bankAccountNumber,
      bankAccountHolderName: formData.bankAccountHolderName,
      bankCode: formData.bankCode,
      bankName: formData.bankName,
      bankBranchName: formData.bankBranchName,
      bankBranchAddress: formData.bankBranchAddress,
      transferInfo: formData.transferInfo,
      autoConfirm: formData.autoConfirm
    };

    const result = await reconciliationService.create(submitData, ReconciliationType.ShippingFee);

    if (result && result.Result === 1) {
      toast.success(result.Message || 'Tạo đối soát cước thành công');
      router.push({ name: 'shipping-fee-reconciliation-list' });
    } else {
      toast.error(result?.Message || 'Có lỗi xảy ra khi tạo đối soát cước');
    }
  } catch (error) {
    console.error('Error creating reconciliation:', error);
    toast.error('Có lỗi xảy ra khi tạo đối soát cước');
  } finally {
    submitting.value = false;
  }
};

const handleCancel = () => {
  router.push({ name: 'customer-shipping-fee-reconciliation-list' });
};

onMounted(async () => {
  // Initialize component
  const customerId = route.params.customerId;
  if (customerId) {
    formData.customerId = parseInt(customerId);
    await Promise.all([
      loadCustomerInfo(),
      loadBankAccounts()
    ]);
  }

  // Set default date range
  const dateRange = getDefaultDateRange();
  formData.fromDate = dateToISOString(dateRange.start);
  formData.toDate = dateToISOString(dateRange.end);
});
</script>

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

.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;
}

.badge {
  font-size: 0.75rem;
}

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

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

.table-secondary {
  opacity: 0.6;
}
</style>
