<template>
  <div>
    <!-- Breadcrumb -->
    <div class="breadcrumb-header justify-content-between">
      <div class="my-auto">
        <h4 class="page-title">Quản lý mặt bằng bưu cục</h4>
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="javascript:void(0);">Trang chủ</a></li>
          <li class="breadcrumb-item active" aria-current="page">Mặt bằng</li>
        </ol>
      </div>
    </div>

    <!-- Search Form -->
    <div class="row row-sm">
      <div class="col-lg-12">
        <div class="card shadow-none mb-3">
          <div class="card-header">
            <h5 class="card-title mb-0">
              <i class="fas fa-search me-2"></i>
              Tìm kiếm
            </h5>
          </div>
          <div class="card-body">
            <div class="row">
              <div class="col-lg-4 col-md-6 mb-3">
                <label class="form-label">Từ khóa</label>
                <input
                  type="text"
                  class="form-control"
                  v-model="searchKeyword"
                  placeholder="Mã mặt bằng, địa chỉ..."
                  @keyup.enter="search"
                >
              </div>
              <div class="col-lg-4 col-md-6 mb-3">
                <label class="form-label">Trạng thái</label>
                <select class="form-select" v-model="selectedStatus">
                  <option :value="null">Tất cả</option>
                  <option :value="1">Đang khảo sát</option>
                  <option :value="2">Chờ đánh giá</option>
                  <option :value="3">Đang đàm phán</option>
                  <option :value="4">Đã duyệt</option>
                  <option :value="5">Đã thuê</option>
                  <option :value="6">Từ chối</option>
                  <option :value="7">Đã đóng</option>
                </select>
              </div>
              <div class="col-lg-4 col-md-6 mb-3 d-flex align-items-end">
                <button type="button" class="btn btn-dark me-2" @click="search" :disabled="loading">
                  <i v-show="!loading" class="fe fe-search"></i>
                  <span v-show="loading" class="spinner-border spinner-border-sm"></span>
                  <span class="ms-1">Tìm kiếm</span>
                </button>
                <button type="button" class="btn btn-secondary" @click="resetSearch">
                  <i class="fas fa-redo me-1"></i>Làm mới
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Data Table -->
    <div class="row row-sm">
      <div class="col-lg-12">
        <div class="card card-table shadow-none">
          <div class="card-body card-table-body">
            <!-- Action Bar -->
            <div class="d-flex flex-row justify-content-between mg-b-10">
              <div>
                <button
                  type="button"
                  class="btn btn-outline-secondary mx-2 button-icon mb-1"
                  @click="goToScoringCriteria"
                >
                  <i class="fas fa-sliders-h me-2"></i>Tiêu chí chấm điểm
                </button>
              </div>
              <button
                type="button"
                class="btn btn-outline-primary mx-2 button-icon mb-1"
                @click="goToCreate"
              >
                <i class="fe fe-plus me-2"></i>Tạo mặt bằng
              </button>
            </div>

            <!-- Table -->
            <div class="table-responsive border-top mg-b-10">
              <table class="table table-vcenter mb-0" style="min-height:300px">
                <thead>
                  <tr>
                    <th class="wd-lg-5p min-width-1"><span>STT</span></th>
                    <th class="min-width-2"><span>Mã</span></th>
                    <th class="min-width-3"><span>Địa chỉ</span></th>
                    <th class="min-width-2"><span>Bưu cục</span></th>
                    <th class="min-width-1"><span>Trạng thái</span></th>
                    <th class="min-width-1"><span>Điểm</span></th>
                    <th class="min-width-2"><span>Ngày tạo</span></th>
                    <th class="min-width-2"><span>Hành động</span></th>
                  </tr>
                </thead>

                <!-- Loading -->
                <tbody v-if="loading">
                  <tr>
                    <td colspan="8" class="tx-semibold text-center text-default">
                      <span class="spinner-border spinner-border-sm"></span>
                    </td>
                  </tr>
                </tbody>

                <!-- Empty -->
                <tbody v-if="!loading && items.length <= 0">
                  <tr>
                    <td colspan="8" class="tx-semibold text-center text-danger">
                      Không tìm thấy mặt bằng nào!
                    </td>
                  </tr>
                </tbody>

                <!-- Data -->
                <tbody v-if="!loading && items.length > 0">
                  <tr v-for="(item, index) in items" :key="item.Id">
                    <td class="text-wrap align-top">{{ getRowNumber(index) }}</td>
                    <td class="text-wrap align-top">
                      <strong>{{ item.Code }}</strong>
                    </td>
                    <td class="text-wrap align-top">
                      <div>{{ item.AddressDetail }}</div>
                      <div v-if="item.LocationName" class="small text-muted">
                        <i class="fas fa-map-marker-alt me-1"></i>{{ item.LocationName }}
                      </div>
                    </td>
                    <td class="text-wrap align-top">
                      {{ item.AgencyName }}
                    </td>
                    <td class="text-wrap align-top">
                      <span :class="['badge', getStatusBadge(item.Status)]">
                        {{ item.StatusName || getStatusText(item.Status) }}
                      </span>
                    </td>
                    <td class="text-wrap align-top">
                      <span class="badge bg-dark">{{ item.TotalScore || 0 }}</span>
                    </td>
                    <td class="text-wrap align-top">
                      <div class="text-muted" style="font-size: 0.8rem;">
                        {{ formatDateTime(item.CreatedTime) }}
                      </div>
                      <div v-if="item.CreatedByUserName" class="small text-muted">
                        {{ item.CreatedByUserName }}
                      </div>
                    </td>
                    <td class="align-top pt-2">
                      <button
                        type="button"
                        data-bs-toggle="dropdown"
                        class="mb-1 mt-1 mr-1 btn btn-light dropdown-toggle btn-sm"
                        aria-expanded="false"
                      >
                        <i class="fas fa-cog"></i> Quản lý
                      </button>
                      <div class="dropdown-menu dropdown-menu-arrow">
                        <a @click="viewDetail(item.Id)" class="dropdown-item" href="javascript:void(0);">
                          <i class="fe fe-eye"></i>
                          <span class="mg-l-6">Xem chi tiết</span>
                        </a>
                        <a @click="editItem(item.Id)" class="dropdown-item" href="javascript:void(0);">
                          <i class="fe fe-edit-2"></i>
                          <span class="mg-l-6">Chỉnh sửa</span>
                        </a>
                        <a @click="confirmDelete(item.Id)" class="dropdown-item" href="javascript:void(0);">
                          <i class="fe fe-trash"></i>
                          <span class="mg-l-6">Xóa</span>
                        </a>
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

            <!-- 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>

    <!-- Modal Chi Tiết -->
    <LadaDialog :visible="modalControl.Detail" variant="modal-full">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title">Chi tiết mặt bằng</h5>
          <button @click="closeDetailModal" type="button" class="close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
      </template>
      <template #body>
        <DetailModal v-if="modalControl.Detail" :id="selectedId" @cancel="closeDetailModal" />
      </template>
    </LadaDialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import premiseService from '@/services/premiseService';
import { useToast } from 'vue-toastification';
import moment from 'moment';

import DetailModal from './detail.vue';
import { LadaDialog } from '@/components/index';

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

const modalControl = reactive({ Detail: false });
const selectedId = ref(0);

function closeDetailModal() {
  modalControl.Detail = false;
  search(); // reload if any data changed
}

//#region DATA
const loading = ref(false);
const searchKeyword = ref('');
const selectedStatus = ref(null);
const items = reactive([]);
const ctrlPager = ref();

const searchModel = reactive({
  Pagination: {
    Total: 0,
    PageIndex: 1,
    PageSize: 15,
  },
  Sort: {
    Predicate: 'CreatedTime',
    Reverse: true,
  },
  Search: {
    PredicateObject: {
      Keyword: '',
    },
  },
});
//#endregion

//#region LIFECYCLE
onMounted(() => {
  search();
});
//#endregion

//#region FORMATTING
function formatDateTime(value) {
  if (!value) return '';
  return moment(value).format('DD/MM/YYYY HH:mm');
}
//#endregion

//#region HELPERS
function getRowNumber(index) {
  return (searchModel.Pagination.PageIndex - 1) * searchModel.Pagination.PageSize + index + 1;
}

function getStatusText(status) {
  switch (status) {
    case 1: return 'Đang khảo sát';
    case 2: return 'Chờ đánh giá';
    case 3: return 'Đang đàm phán';
    case 4: return 'Đã duyệt';
    case 5: return 'Đã thuê';
    case 6: return 'Từ chối';
    case 7: return 'Đã đóng';
    default: return `#${status}`;
  }
}

function getStatusBadge(status) {
  switch (status) {
    case 1: return 'bg-info';
    case 2: return 'bg-warning';
    case 3: return 'bg-primary';
    case 4: return 'bg-success';
    case 5: return 'bg-success';
    case 6: return 'bg-danger';
    case 7: return 'bg-secondary';
    default: return 'bg-secondary';
  }
}
//#endregion

//#region SEARCH
async function search() {
  searchModel.Pagination.PageIndex = 1;
  if (ctrlPager.value) {
    ctrlPager.value.Refresh();
  }
  await loadData();
}

async function loadData() {
  loading.value = true;
  try {
    searchModel.Search.PredicateObject.Keyword = searchKeyword.value || null;

    const result = await premiseService.search(searchModel);
    items.splice(0, items.length);
    if (result && result.Items && result.Items.length > 0) {
      result.Items.forEach(item => {
        items.push(item);
      });
    }
    searchModel.Pagination.Total = result?.TotalRecord || 0;
  } catch (error) {
    console.error('Error loading premises:', error);
    toast.error('Có lỗi xảy ra khi tải dữ liệu');
  } finally {
    loading.value = false;
  }
}

function resetSearch() {
  searchKeyword.value = '';
  selectedStatus.value = null;
  search();
}
//#endregion

//#region PAGINATION
function pageSizeChanged(pagesize) {
  searchModel.Pagination.PageSize = pagesize;
  searchModel.Pagination.PageIndex = 1;
  loadData();
}

function pageIndexChanged(pageIndex) {
  searchModel.Pagination.PageIndex = pageIndex;
  loadData();
}
//#endregion

//#region NAVIGATION
function goToCreate() {
  router.push({ name: 'premise-create' });
}

function goToScoringCriteria() {
  router.push({ name: 'scoring-criteria-list' });
}

function viewDetail(id) {
  selectedId.value = id;
  modalControl.Detail = true;
}

function editItem(id) {
  router.push({ name: 'premise-edit', params: { id } });
}
//#endregion

//#region DELETE
async function confirmDelete(id) {
  if (!confirm('Bạn có chắc chắn muốn xóa mặt bằng này?\n\nLưu ý: Thao tác này không thể hoàn tác.')) {
    return;
  }

  try {
    const result = await premiseService.delete(id);
    if (result && result.Result === 1) {
      toast.success(result.Message || 'Xóa mặt bằng thành công');
      await search();
    } else {
      toast.error(result.Message || 'Không thể xóa mặt bằng');
    }
  } catch (error) {
    console.error('Error deleting:', error);
    toast.error('Có lỗi xảy ra khi xóa mặt bằng');
  }
}
//#endregion
</script>
