<template>
  <div>
    <!-- Breadcrumb -->
    <div class="breadcrumb-header justify-content-between">
      <div class="my-auto">
        <h4 class="page-title">Tiêu chí chấm điểm mặt bằng</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);" @click="$router.push({ name: 'premise-list' })">Mặt bằng</a></li>
          <li class="breadcrumb-item active" aria-current="page">Tiêu chí chấm điểm</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="Tìm theo tên tiêu chí..."
                  @keyup.enter="search"
                >
              </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-end mg-b-10">
              <button
                type="button"
                class="btn btn-outline-primary mx-2 button-icon mb-1"
                @click="openCreateModal"
              >
                <i class="fe fe-plus me-2"></i>Thêm tiêu chí
              </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="wd-lg-25p min-width-3"><span>Tên tiêu chí</span></th>
                    <th class="wd-lg-10p min-width-1"><span>Loại</span></th>
                    <th class="wd-lg-10p min-width-1"><span>Thứ tự</span></th>
                    <th class="wd-lg-10p min-width-1"><span>Trạng thái</span></th>
                    <th class="wd-lg-10p min-width-1"><span>Số options</span></th>
                    <th class="wd-lg-15p"><span>Hành động</span></th>
                  </tr>
                </thead>

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

                <!-- Empty -->
                <tbody v-if="!loading && items.length <= 0">
                  <tr>
                    <td colspan="7" class="tx-semibold text-center text-danger">
                      Không tìm thấy tiêu chí 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">
                      <div class="mb-1">
                        <strong>{{ item.Name }}</strong>
                      </div>
                      <div v-if="item.Description" class="small text-muted">{{ item.Description }}</div>
                    </td>
                    <td class="text-wrap align-top">
                      <span :class="['badge', item.CriteriaType === 1 ? 'bg-info' : 'bg-warning']">
                        {{ item.CriteriaType === 1 ? 'Option' : 'Range' }}
                      </span>
                    </td>
                    <td class="text-wrap align-top">{{ item.DisplayOrder }}</td>
                    <td class="text-wrap align-top">
                      <span :class="['badge', item.IsActive ? 'bg-success' : 'bg-secondary']">
                        {{ item.IsActive ? 'Hoạt động' : 'Ngưng' }}
                      </span>
                    </td>
                    <td class="text-wrap align-top">
                      {{ item.Options ? item.Options.length : 0 }}
                    </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="openEditModal(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 Thêm/Sửa tiêu chí -->
    <LadaDialog :visible="modalControl.FormModal" variant="modal-lg">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title">
            <i class="fas fa-edit me-2"></i>
            {{ formData.Id > 0 ? 'Chỉnh sửa tiêu chí' : 'Thêm tiêu chí mới' }}
          </h5>
          <button @click="closeFormModal" type="button" class="close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
      </template>
      <template #body>
        <div v-if="loadingDetail" class="text-center py-4">
          <span class="spinner-border spinner-border-sm"></span> Đang tải...
        </div>
        <div v-else>
          <div class="row">
            <!-- Tên tiêu chí -->
            <div class="col-md-6 mb-3">
              <label>Tên tiêu chí <span class="text-danger">*</span></label>
              <input
                type="text"
                class="form-control"
                v-model="formData.Name"
                placeholder="VD: Vị trí mặt bằng"
              >
            </div>

            <!-- Loại tiêu chí -->
            <div class="col-md-3 mb-3">
              <label>Loại tiêu chí <span class="text-danger">*</span></label>
              <select
                class="form-select"
                v-model="formData.CriteriaType"
                :disabled="formData.Id > 0"
              >
                <option value="">-- Chọn loại --</option>
                <option :value="1">Option</option>
                <option :value="2">Range</option>
              </select>
            </div>

            <!-- Thứ tự hiển thị -->
            <div class="col-md-3 mb-3">
              <label>Thứ tự <span class="text-danger">*</span></label>
              <input
                type="number"
                class="form-control"
                v-model.number="formData.DisplayOrder"
              >
            </div>

            <!-- Mô tả -->
            <div class="col-md-8 mb-3">
              <label>Mô tả</label>
              <textarea
                class="form-control"
                v-model="formData.Description"
                rows="2"
                placeholder="Mô tả tiêu chí"
              ></textarea>
            </div>

            <!-- Trạng thái -->
            <div class="col-md-4 mb-3 d-flex align-items-center pt-4">
              <div class="form-check form-switch">
                <input
                  class="form-check-input"
                  type="checkbox"
                  v-model="formData.IsActive"
                  id="isActiveSwitch"
                >
                <label class="form-check-label" for="isActiveSwitch">Kích hoạt</label>
              </div>
            </div>
          </div>

          <!-- Options -->
          <div v-if="formData.CriteriaType" class="mt-2">
            <div class="d-flex justify-content-between align-items-center mb-2">
              <h6 class="mb-0"><i class="fas fa-list me-2"></i>Danh sách tùy chọn</h6>
              <button type="button" class="btn btn-sm btn-outline-primary" @click="addOption">
                <i class="fe fe-plus me-1"></i>Thêm
              </button>
            </div>
            <div class="table-responsive">
              <table class="table table-bordered table-sm mb-0">
                <thead class="table-light">
                  <tr>
                    <th style="width: 40px">#</th>
                    <th>Nhãn <span class="text-danger">*</span></th>
                    <th v-if="Number(formData.CriteriaType) === 2" style="width: 110px">Min</th>
                    <th v-if="Number(formData.CriteriaType) === 2" style="width: 110px">Max</th>
                    <th style="width: 90px">Điểm <span class="text-danger">*</span></th>
                    <th style="width: 80px">Thứ tự</th>
                    <th style="width: 50px"></th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="(opt, index) in formData.Options" :key="index">
                    <td class="align-middle text-center">{{ index + 1 }}</td>
                    <td>
                      <input type="text" class="form-control form-control-sm" v-model="opt.Label" placeholder="Nhãn">
                    </td>
                    <td v-if="Number(formData.CriteriaType) === 2">
                      <input type="number" class="form-control form-control-sm" v-model.number="opt.MinValue" step="0.01">
                    </td>
                    <td v-if="Number(formData.CriteriaType) === 2">
                      <input type="number" class="form-control form-control-sm" v-model.number="opt.MaxValue" step="0.01">
                    </td>
                    <td>
                      <input type="number" class="form-control form-control-sm" v-model.number="opt.Score">
                    </td>
                    <td>
                      <input type="number" class="form-control form-control-sm" v-model.number="opt.DisplayOrder">
                    </td>
                    <td class="text-center align-middle">
                      <button
                        type="button"
                        class="btn btn-sm btn-outline-danger"
                        @click="removeOption(index)"
                        :disabled="formData.Options.length <= 1"
                      >
                        <i class="fe fe-trash-2"></i>
                      </button>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>

          <!-- Modal Actions -->
          <div class="d-flex justify-content-end gap-2 mt-4">
            <button type="button" class="btn btn-secondary" @click="closeFormModal">
              <i class="fe fe-x me-1"></i>Hủy
            </button>
            <button type="button" class="btn btn-primary" @click="onSubmit" :disabled="saving">
              <span v-if="saving" class="spinner-border spinner-border-sm me-1"></span>
              <i v-else class="fe fe-save me-1"></i>
              {{ formData.Id > 0 ? 'Cập nhật' : 'Lưu' }}
            </button>
          </div>
        </div>
      </template>
    </LadaDialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import premiseScoringService from '@/services/premiseScoringService';
import { useToast } from 'vue-toastification';
import { LadaDialog } from '@/components/index';

const toast = useToast();

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

const searchModel = reactive({
  Pagination: {
    Total: 0,
    PageIndex: 1,
    PageSize: 15,
  },
  Sort: {
    Predicate: 'DisplayOrder',
    Reverse: false,
  },
  Search: {
    PredicateObject: {
      Keyword: '',
    },
  },
});

// Modal control
const modalControl = reactive({
  FormModal: false,
});

const formData = reactive({
  Id: 0,
  Name: '',
  Description: '',
  CriteriaType: '',
  DisplayOrder: 1,
  IsActive: true,
  Options: [
    { Id: 0, Label: '', MinValue: null, MaxValue: null, Score: 0, DisplayOrder: 1 }
  ],
});
//#endregion

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

//#region HELPERS
function getRowNumber(index) {
  return (searchModel.Pagination.PageIndex - 1) * searchModel.Pagination.PageSize + index + 1;
}
//#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 premiseScoringService.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 scoring criteria:', error);
    toast.error('Có lỗi xảy ra khi tải dữ liệu');
  } finally {
    loading.value = false;
  }
}

function resetSearch() {
  searchKeyword.value = '';
  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 MODAL
function resetFormData() {
  formData.Id = 0;
  formData.Name = '';
  formData.Description = '';
  formData.CriteriaType = '';
  formData.DisplayOrder = 1;
  formData.IsActive = true;
  formData.Options.splice(0, formData.Options.length);
  formData.Options.push({ Id: 0, Label: '', MinValue: null, MaxValue: null, Score: 0, DisplayOrder: 1 });
}

function openCreateModal() {
  resetFormData();
  modalControl.FormModal = true;
}

async function openEditModal(id) {
  resetFormData();
  modalControl.FormModal = true;
  loadingDetail.value = true;

  try {
    const result = await premiseScoringService.getById(id);
    if (result) {
      formData.Id = result.Id;
      formData.Name = result.Name;
      formData.Description = result.Description || '';
      formData.CriteriaType = result.CriteriaType;
      formData.DisplayOrder = result.DisplayOrder;
      formData.IsActive = result.IsActive;

      if (result.Options && result.Options.length > 0) {
        formData.Options.splice(0, formData.Options.length);
        result.Options.forEach(opt => {
          formData.Options.push({
            Id: opt.Id,
            Label: opt.Label,
            MinValue: opt.MinValue,
            MaxValue: opt.MaxValue,
            Score: opt.Score,
            DisplayOrder: opt.DisplayOrder,
          });
        });
      }
    } else {
      toast.error('Không tìm thấy tiêu chí');
      closeFormModal();
    }
  } catch (error) {
    console.error('Error loading criteria:', error);
    toast.error('Có lỗi xảy ra khi tải tiêu chí');
    closeFormModal();
  } finally {
    loadingDetail.value = false;
  }
}

function closeFormModal() {
  modalControl.FormModal = false;
}
//#endregion

//#region OPTIONS
function addOption() {
  const nextOrder = formData.Options.length + 1;
  formData.Options.push({
    Id: 0,
    Label: '',
    MinValue: null,
    MaxValue: null,
    Score: 0,
    DisplayOrder: nextOrder,
  });
}

function removeOption(index) {
  if (formData.Options.length <= 1) return;
  formData.Options.splice(index, 1);
}
//#endregion

//#region SUBMIT
async function onSubmit() {
  // Validate
  if (!formData.Name || !formData.Name.trim()) {
    toast.error('Vui lòng nhập tên tiêu chí');
    return;
  }
  if (!formData.CriteriaType) {
    toast.error('Vui lòng chọn loại tiêu chí');
    return;
  }

  const invalidOptions = formData.Options.filter(opt => !opt.Label || opt.Label.trim() === '');
  if (invalidOptions.length > 0) {
    toast.error('Vui lòng nhập nhãn cho tất cả tùy chọn');
    return;
  }

  if (Number(formData.CriteriaType) === 2) {
    const invalidRange = formData.Options.filter(opt => opt.MinValue === null || opt.MaxValue === null);
    if (invalidRange.length > 0) {
      toast.error('Vui lòng nhập giá trị min/max cho tất cả tùy chọn');
      return;
    }
  }

  saving.value = true;
  try {
    let updatedBy = 0;
    let updatedByUserName = '';
    if (localStorage.user) {
      const curUser = JSON.parse(localStorage.user);
      updatedBy = curUser.UserId || curUser.Id || 0;
      updatedByUserName = curUser.UserName || curUser.FullName || '';
    }

    const model = {
      Id: formData.Id,
      Name: formData.Name,
      Description: formData.Description,
      CriteriaType: Number(formData.CriteriaType),
      DisplayOrder: Number(formData.DisplayOrder),
      IsActive: formData.IsActive,
      Options: formData.Options.map(opt => ({
        Id: opt.Id || 0,
        Label: opt.Label,
        MinValue: Number(formData.CriteriaType) === 2 ? opt.MinValue : null,
        MaxValue: Number(formData.CriteriaType) === 2 ? opt.MaxValue : null,
        Score: Number(opt.Score),
        DisplayOrder: Number(opt.DisplayOrder),
      })),
      UpdatedBy: updatedBy,
      UpdatedByUserName: updatedByUserName,
    };

    const result = await premiseScoringService.createOrUpdate(model);
    if (result && result.Result === 1) {
      toast.success(formData.Id > 0 ? 'Cập nhật tiêu chí thành công' : 'Thêm tiêu chí thành công');
      closeFormModal();
      await search();
    } else {
      toast.error(result.Message || 'Không thể lưu tiêu chí');
    }
  } catch (error) {
    console.error('Error saving criteria:', error);
    toast.error('Có lỗi xảy ra khi lưu tiêu chí');
  } finally {
    saving.value = false;
  }
}
//#endregion

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

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