<template>
  <div class="container-fluid">
    <!-- Breadcrumb -->
    <div class="breadcrumb-header justify-content-between">
      <div class="my-auto">
        <h4 class="page-title">Danh sách 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 active" aria-current="page">Danh sách hóa đơn</li>
        </ol>
      </div>
      <div class="d-flex my-xl-auto right-content align-items-center">
        <div class="d-flex gap-2">
          <router-link :to="{ name: 'transfer-payment-bill-search-customers' }" class="btn btn-primary">
            <i class="fe fe-plus me-2"></i>Tạo mới
          </router-link>
          <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>

    <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-3 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="Mã hóa đơn, tên khách hàng, SĐT...">
              </div>
              <div class="col-lg-2 col-md-3 mb-3">
                <label>Trạng thái</label>
                <select v-model="statusFilter" class="form-select">
                  <option value="">Tất cả trạng thái</option>
                  <option value="Draft">Nháp</option>
                  <option value="Approved">Đã duyệt</option>
                  <option value="Cancelled">Đã hủy</option>
                </select>
              </div>
              <div class="col-lg-2 col-md-3 mb-3">
                <label>Mức độ ưu tiên</label>
                <select v-model="priorityFilter" class="form-select">
                  <option value="">Tất cả mức độ</option>
                  <option value="Low">Thấp</option>
                  <option value="Medium">Trung bình</option>
                  <option value="High">Cao</option>
                  <option value="Urgent">Khẩn cấp</option>
                </select>
              </div>
              <div class="col-lg-3 col-md-6 mb-3">
                <label>Ngày tạo</label>
                <VueDatePicker ref="dateRangePicker" v-model="dateRange" :enable-time-picker="false" range
                  multi-calendars auto-apply :format="format" @update:model-value="handleDateChange">
                  <template #left-sidebar>
                    <DateRangeSidebar @change-date="onChangeDate"></DateRangeSidebar>
                  </template>
                </VueDatePicker>
              </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-sm-12 col-md-12 col-lg-12 col-xl-12 grid-margin">
        <div class="card">
          <div v-if="loading" class="text-center py-4">
            <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 hóa đơn...</p>
          </div>

          <div v-else-if="items.length === 0 && !loading" class="text-center py-4">
            <empty></empty>
            <p class="text-muted">Không tìm thấy hóa đơn nào phù hợp với điều kiện tìm kiếm</p>
          </div>

          <div v-else class="table-responsive">
            <table class="table table-hover mg-b-0 text-md-nowrap">
              <thead>
                <tr>
                  <th>Mã hóa đơn</th>
                  <th>Khách hàng</th>
                  <th>Thời gian</th>
                  <th>Số đơn hàng</th>
                  <th>Tổng tiền</th>
                  <th>Trạng thái</th>
                  <th>Ưu tiên</th>
                  <th>Ngân hàng</th>
                  <th>Người tạo</th>
                  <th>Thao tác</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="bill in items" :key="bill.Id">
                  <td>
                    <router-link :to="{ name: 'transfer-payment-bill-detail', params: { id: bill.Id } }"
                      class="fw-bold text-decoration-none">
                      {{ bill.Code }}
                    </router-link>
                  </td>
                  <td>
                    <div>
                      <strong>{{ bill.CustomerName }}</strong><br>
                      <small class="text-muted">{{ bill.CustomerPhone }}</small>
                    </div>
                  </td>
                  <td>
                    <div>
                      <small>{{ formatDate(bill.FromDate) }} -</small><br>
                      <small>{{ formatDate(bill.ToDate) }}</small>
                    </div>
                  </td>
                  <td>
                    <span class="badge bg-info">{{ bill.OrderCount }} đơn</span>
                  </td>
                  <td>
                    <strong class="text-success">{{ bill.TotalAmountFormatted }}</strong>
                  </td>
                  <td>
                    <StatusBadge :status="mapStatusNumberToString(bill.Status)" />
                  </td>
                  <td>
                    <PriorityIcon :priority="mapPriorityNumberToString(bill.Priority)" :show-text="true" />
                  </td>
                  <td>
                    <div>
                      <strong>{{ bill.CompanyBankName }}</strong><br>
                      <small class="text-muted">{{ bill.CompanyBankAccountNumber }}</small>
                    </div>
                  </td>
                  <td>
                    <div>
                      <small>{{ bill.CreatedByUserName }}</small><br>
                      <small class="text-muted">{{ formatDate(bill.CreatedTime, true) }}</small>
                    </div>
                  </td>
                  <td>
                    <ActionButtons :permissions="bill" @view="viewBill(bill)" @edit="editBill(bill)"
                      @cancel="cancelBill(bill)" @approve="approveBill(bill)" />
                  </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>

    <!-- Cancel Dialog -->
    <LadaDialog ref="cancelDialog" title="Xác nhận hủy hóa đơn" size="md" @confirm="confirmCancel">
      <template #body>
        <div v-if="selectedBill">
          <p>Bạn có chắc chắn muốn hủy hóa đơn <strong>{{ selectedBill.Code }}</strong> không?</p>
          <div class="alert alert-warning">
            <i class="fe fe-alert-triangle me-2"></i>
            Hành động này không thể hoàn tác. Hóa đơn sẽ chuyển sang trạng thái "Đã hủy".
          </div>
        </div>
      </template>
    </LadaDialog>

    <!-- Approve Dialog -->
    <LadaDialog ref="approveDialog" title="Duyệt hóa đơn" size="lg" @confirm="confirmApprove">
      <template #body>
        <div v-if="selectedBill">
          <div class="mb-3">
            <p>Duyệt hóa đơn <strong>{{ selectedBill.Code }}</strong></p>
            <div class="row">
              <div class="col-md-6">
                <small class="text-muted">Khách hàng:</small>
                <p class="mb-1">{{ selectedBill.CustomerName }}</p>
              </div>
              <div class="col-md-6">
                <small class="text-muted">Tổng tiền:</small>
                <p class="mb-1 text-success fw-bold">{{ selectedBill.TotalAmountFormatted }}</p>
              </div>
            </div>
          </div>

          <div class="mb-3">
            <label class="form-label">Ghi chú duyệt</label>
            <textarea v-model="approveData.approvalNote" class="form-control" rows="3"
              placeholder="Nhập ghi chú khi duyệt (tùy chọn)"></textarea>
          </div>

          <div class="mb-3">
            <label class="form-label">Thông tin chuyển khoản</label>
            <textarea v-model="approveData.transferInfo" class="form-control" rows="3"
              placeholder="Nhập thông tin chuyển khoản (tùy chọn)"></textarea>
          </div>
        </div>
      </template>
    </LadaDialog>
  </div>
</template>

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

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,
      Status: null
    }
  }
});

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

// Filters
const statusFilter = ref('');
const priorityFilter = ref('');
const dateRange = ref([
  moment().subtract(30, 'days').toDate(),
  moment().toDate()
]);

// Dialog data
const selectedBill = ref(null);
const cancelDialog = ref();
const approveDialog = ref();
const approveData = reactive({
  approvalNote: '',
  transferInfo: ''
});

// Date picker methods
const format = (dates) => {
  if (!dates || dates.length !== 2) return '';
  const start = moment(dates[0]);
  const end = moment(dates[1]);
  return `${start.format('DD/MM/YYYY')} - ${end.format('DD/MM/YYYY')}`;
};

const onChangeDate = (dates) => {
  dateRange.value = dates;
  search();
};

const handleDateChange = (dates) => {
  if (dates && dates.length === 2) {
    search();
  }
};

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

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

  try {
    // Update search model with current filters
    searchModel.Search.PredicateObject.Status = statusFilter.value || null;
    searchModel.Search.PredicateObject.Priority = priorityFilter.value || null;


    const result = await transferPaymentBillService.search(searchModel);

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

    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 hóa đơn nào phù hợp với từ khóa tìm kiếm');
    }
  } catch (error) {
    console.error('Error searching bills:', error);
    toast.error('Có lỗi xảy ra khi tìm kiếm hóa đơn');
  } finally {
    loading.value = false;
  }
}

function clearSearch() {
  searchModel.Search.PredicateObject.Keyword = '';
  searchModel.Search.PredicateObject.Status = null;
  searchModel.Search.PredicateObject.Priority = null;
  statusFilter.value = '';
  priorityFilter.value = '';
  search();
}

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

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

// Row styling based on status
function getRowClass(statusName) {
  const statusClasses = {
    'Nháp': 'table-row-draft',
    'Đã duyệt': 'table-row-approved',
    'Đã hủy': 'table-row-cancelled'
  };
  return statusClasses[statusName] || '';
}

// Action handlers
function viewBill(bill) {
  router.push({
    name: 'transfer-payment-bill-detail',
    params: { id: bill.Id }
  });
}

function editBill() {
  // Navigate to edit page (if implemented)
  toast.info('Chức năng chỉnh sửa đang được phát triển');
}

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

  selectedBill.value = bill;
  cancelDialog.value?.show();
}

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

  selectedBill.value = bill;
  approveData.approvalNote = '';
  approveData.transferInfo = '';
  approveDialog.value?.show();
}

async function confirmCancel() {
  if (!selectedBill.value) return;

  try {
    const result = await transferPaymentBillService.cancel(selectedBill.value.Id);

    if (result.result === 'Success') {
      toast.success(result.message || 'Hủy hóa đơn thành công');
      await loadData(); // Refresh list
    } else {
      toast.error(result.message || 'Có lỗi xảy ra khi hủy hóa đơn');
    }
  } catch (error) {
    console.error('Error cancelling bill:', error);
    toast.error('Có lỗi xảy ra khi hủy hóa đơn');
  } finally {
    cancelDialog.value?.hide();
    selectedBill.value = null;
  }
}

async function confirmApprove() {
  if (!selectedBill.value) return;

  try {
    const approveModel = {
      id: selectedBill.value.Id,
      approvalNote: approveData.approvalNote,
      transferInfo: approveData.transferInfo,
      approvedBy: 1, // TODO: Get from user context
      approvedByUsername: 'admin' // TODO: Get from user context
    };

    const result = await transferPaymentBillService.approve(approveModel);

    if (result.result === 'Success') {
      toast.success(result.message || 'Duyệt hóa đơn thành công');
      await loadData(); // Refresh list
    } 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 {
    approveDialog.value?.hide();
    selectedBill.value = null;
  }
}

// Watch filters for auto-search
watch([statusFilter, priorityFilter], () => {
  search();
});

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

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

.table th {
  background-color: #f8f9fa;
  border-top: none;
  font-weight: 600;
  color: #495057;
}

.table-row-draft {
  background-color: rgba(13, 110, 253, 0.05);
}

.table-row-approved {
  background-color: rgba(25, 135, 84, 0.05);
}

.table-row-cancelled {
  background-color: rgba(220, 53, 69, 0.05);
}

.table-row-draft:hover {
  background-color: rgba(13, 110, 253, 0.1);
}

.table-row-approved:hover {
  background-color: rgba(25, 135, 84, 0.1);
}

.table-row-cancelled:hover {
  background-color: rgba(220, 53, 69, 0.1);
}

.badge {
  font-size: 0.75rem;
}

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

.fw-bold {
  font-weight: 600 !important;
}

.text-decoration-none {
  text-decoration: none !important;
}

.text-decoration-none:hover {
  text-decoration: underline !important;
}

.alert-warning {
  background-color: #fff3cd;
  border-color: #ffecb5;
  color: #664d03;
}

.form-label {
  font-weight: 600;
  color: #495057;
  margin-bottom: 0.5rem;
}
</style>
