<template>
  <div class="container-fluid">
    <!-- Breadcrumb -->
    <div class="breadcrumb-header justify-content-between">
      <div class="my-auto">
        <h4 class="page-title">Tìm kiếm khách hàng</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 active" aria-current="page">Tìm kiếm khách hàng</li>
        </ol>
      </div>
      <div class="d-flex my-xl-auto right-content align-items-center">
        <router-link :to="{ name: 'transfer-payment-bill' }" class="btn btn-secondary">
          <i class="fe fe-arrow-left me-2"></i>Quay lại
        </router-link>
      </div>
    </div>

    <div class="row">
      <div class="col-sm-12 col-md-12 col-lg-12 col-xl-12 grid-margin">
        <div class="card">
          <form class="card-body" @submit.prevent="search">
            <div class="row">
              <div class="col-lg-4 col-md-6 mb-3">
                <label>Từ khóa tìm kiếm</label>
                <input type="text" v-model="searchModel.Search.PredicateObject.Keyword" class="form-control"
                  placeholder="Tên khách hàng, số điện thoại...">
              </div>
              <div class="col-lg-2 col-md-3 mb-3 d-flex align-items-end">
                <button type="submit" class="btn btn-primary me-2">
                  <i class="fe fe-search me-2"></i>Tìm kiếm
                </button>
                <button type="button" @click="clearSearch" class="btn btn-outline-secondary">
                  <i class="fe fe-x me-2"></i>Xóa
                </button>
              </div>
            </div>
          </form>

        </div>

      </div>
    </div>


    <div class="row">
      <div class="col-12">
        <div class="card">


          <!-- Results Table -->
          <div class="table-responsive">
            <table class="table table-hover mg-b-0 text-md-nowrap">
              <thead>
                <tr>
                  <th class="wd-20p">Khách hàng</th>
                  <th class="wd-15p">Liên hệ</th>
                  <th class="wd-10p">Số đơn hàng</th>
                  <th class="wd-15p">Tổng tiền cước</th>
                  <th class="wd-15p">Thời gian đơn hàng</th>
                  <th class="wd-10p">Mức độ ưu tiên</th>
                  <th class="wd-15p">Thao tác</th>
                </tr>
              </thead>
              <tbody v-if="loading">
                <tr>
                  <td colspan="7" class="tx-semibold text-center text-default">
                    <span class="spinner-border spinner-border-sm"></span>
                  </td>
                </tr>
              </tbody>
              <tbody v-if="!loading && items.length <= 0">
                <tr>
                  <td colspan="7" class="tx-semibold text-center text-danger">
                    Không tìm thấy khách hàng nào có đơn hàng cần tạo hóa đơn!
                  </td>
                </tr>
              </tbody>
              <tbody>
                <tr v-for="customer in items" :key="customer.CustomerId" class="cursor-pointer"
                  @click="selectCustomer(customer)">
                  <td>
                    <div>
                      <strong>{{ customer.CustomerName }}</strong>
                      <br>
                      <small class="text-muted">ID: {{ customer.CustomerId }}</small>
                    </div>
                  </td>
                  <td>
                    <div>
                      <div><i class="fe fe-phone me-1"></i>{{ customer.CustomerPhone }}</div>
                      <div v-if="customer.CustomerEmail">
                        <i class="fe fe-mail me-1"></i>{{ customer.CustomerEmail }}
                      </div>
                    </div>
                  </td>
                  <td>
                    <span class="badge bg-info">{{ customer.PendingOrderCount }} đơn</span>
                  </td>
                  <td>
                    <strong class="text-success">{{ customer.TotalPendingAmountFormatted }}</strong>
                  </td>
                  <td>
                    <div>
                      <small>Từ: {{ formatDate(customer.OldestOrderDate) }}</small><br>
                      <small>Đến: {{ formatDate(customer.LatestOrderDate) }}</small>
                    </div>
                  </td>
                  <td>
                    <span class="badge" :class="getPriorityClass(customer.PriorityLevel)">
                      {{ customer.PriorityLevel }}
                    </span>
                  </td>
                  <td>
                    <button @click.stop="selectCustomer(customer)" class="btn btn-sm btn-primary"
                      title="Chọn khách hàng này">
                      <i class="fe fe-arrow-right"></i>
                    </button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
          <div class="card-body">
            <!-- Pagination -->
            <pager ref="ctrlPager" v-show="!loading && items.length > 0" @PageSizeChanged="PageSizeChanged"
              @PageIndexChanged="PageIndexChanged" :Total="searchModel.Pagination.Total" :TotalCurrent="items.length" />
          </div>

        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useToast } from 'vue-toastification';
import transferPaymentBillService from '@/services/transferPaymentBillService';
import { formatDate } from '@/components/transfer-payment-bill/utils';

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

// Search model following the project pattern
const searchModel = reactive({
  Pagination: {
    Total: 0,
    PageIndex: 1,
    PageSize: 25
  },
  Sort: {
    Predicate: '',
    Reverse: true
  },
  Search: {
    PredicateObject: {
      Keyword: '',
      Priority: null
    }
  }
});

// Data
const items = reactive([]);
const loading = ref(false);
const ctrlPager = ref();



// Methods
async function search() {
  searchModel.page = 1;
  searchModel.Pagination.PageIndex = 1;
  ctrlPager.value?.Refresh();
  await loadData();
}

async function loadData() {
  loading.value = true;
  items.splice(0, items.length);

  try {
    // Convert to API format


    const result = await transferPaymentBillService.searchCustomersForTransferPayment(searchModel);

    if (result.Items && result.Items.length > 0) {
      result.Items.forEach(customer => {
        items.push(customer);
      });

      // Store customers data in sessionStorage for use in select-orders page
      sessionStorage.setItem('transferPaymentBillCustomers', JSON.stringify(result.Items));
    }

    searchModel.Pagination.Total = result.TotalRecord || 0;

    if (result.Items && result.Items.length === 0 && searchModel.Search.PredicateObject.Keyword) {
      toast.info('Không tìm thấy khách hàng nào phù hợp với từ khóa tìm kiếm');
    }
  } catch (error) {
    console.error('Error searching customers:', error);
    toast.error('Có lỗi xảy ra khi tìm kiếm khách hàng');
  } finally {
    loading.value = false;
  }
}

function clearSearch() {
  searchModel.Search.PredicateObject.Keyword = '';
  search();
}

function PageSizeChanged(pageSize) {
  searchModel.Pagination.PageSize = pageSize;
  searchModel.Pagination.PageIndex = 1;
  loadData();
}

function PageIndexChanged(pageIndex) {
  searchModel.Pagination.PageIndex = pageIndex;
  loadData();
}

function getPriorityClass(priorityLevel) {
  const priorityClasses = {
    'Thấp': 'bg-secondary',
    'Trung bình': 'bg-info',
    'Cao': 'bg-warning',
    'Khẩn cấp': 'bg-danger'
  };
  return priorityClasses[priorityLevel] || 'bg-secondary';
}

function selectCustomer(customer) {
  // Navigate to create page with customer ID
  router.push({
    name: 'transfer-payment-bill-create',
    params: { customerId: customer.CustomerId }
  });
}

// Load initial data
onMounted(() => {
  loadData();
});
</script>

<style scoped>
.cursor-pointer {
  cursor: pointer;
}

.cursor-pointer:hover {
  background-color: rgba(0, 123, 255, 0.1);
}

.card-search {
  background-color: #f8f9fa;
  border: 1px solid #dee2e6;
}

.badge {
  font-size: 0.75rem;
}

/* Width classes following project pattern */
.wd-10p {
  width: 10%;
}

.wd-15p {
  width: 15%;
}

.wd-20p {
  width: 20%;
}

/* Text classes following project pattern */
.tx-semibold {
  font-weight: 600;
}

.text-default {
  color: #495057;
}

.card-stats {
  border: none;
  box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
  transition: transform 0.2s ease-in-out;
}

.card-stats:hover {
  transform: translateY(-2px);
  box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
}

.icon-wrapper {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-wrapper i {
  font-size: 1.5rem;
}

.card-stats h3 {
  font-size: 1.75rem;
  font-weight: 700;
  color: #495057;
}

.card-stats .text-muted {
  font-size: 0.875rem;
  font-weight: 500;
}
</style>
