<template>
  <div class="income-categories-page">
    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center mb-4">
      <div>
        <h4 class="mb-1">Quản lý danh mục doanh thu</h4>
        <p class="text-muted mb-0">Quản lý các danh mục doanh thu trong hệ thống</p>
      </div>
      <button type="button" class="btn btn-primary" @click="openCreateModal">
        <i class="fe fe-plus me-2"></i>Thêm danh mục
      </button>
    </div>

    <!-- Search Form -->
    <div class="card mb-4">
      <div class="card-body">
        <div class="row">
          <div class="col-md-4 mb-3">
            <label class="form-label">Từ khóa tìm kiếm</label>
            <input type="text" class="form-control" v-model="searchModel.Search.PredicateObject.Name"
              placeholder="Tìm theo tên, mô tả..." @keyup.enter="handleSearch" />
          </div>
          <div class="col-md-4 mb-3">
            <label class="form-label">Danh mục cha</label>
            <v-select v-model="searchModel.Search.PredicateObject.ParentId" :reduce="(option) => option.Id" label="Name"
              :filterable="false" :options="parentCategories" @search="getParentCategories"
              placeholder="Chọn danh mục cha..." clearable>
              <template #no-options="{ search, searching, loading }">
                Gõ từ khóa để tìm....
              </template>
              <template v-slot:option="option">
                <span :style="{ paddingLeft: (option.Level || 0) * 20 + 'px' }">
                  {{ option.Name }}
                  <small v-if="option.Level > 0" class="text-muted">(Level {{ option.Level }})</small>
                </span>
              </template>
            </v-select>
          </div>
          <div class="col-md-2 mb-3">
            <label class="form-label">Kiểu hiển thị</label>
            <v-select v-model="searchModel.Search.PredicateObject.DisplayMode" :options="displayModeOptions"
              label="label" :reduce="option => option.value" placeholder="Chọn kiểu hiển thị..." :clearable="false"
              @option:selected="handleDisplayModeChange" />
          </div>
          <div class="col-md-2 mb-3 d-flex align-items-end">
            <div class="d-flex gap-2">
              <button type="button" class="btn btn-primary" @click="handleSearch">
                <i class="fe fe-search me-2"></i>Tìm kiếm
              </button>
              <button type="button" class="btn btn-outline-secondary" @click="handleReset">
                <i class="fe fe-refresh-cw me-2"></i>Đặt lại
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- Data Table -->
    <div class="card">
      <div class="card-body">
        <LoadingOverlay :show="loading" />

        <div v-if="!loading && categories.length === 0" class="text-center py-5">
          <empty />
          <p class="text-muted mt-3">Không có danh mục doanh thu nào</p>
        </div>

        <!-- List Mode -->
        <div v-else-if="isListMode" class="table-responsive">
          <table class="table table-vcenter mb-0">
            <thead>
              <tr>
                <th class="wd-lg-8p">ID</th>
                <th class="wd-lg-18p">Tên danh mục</th>
                <th class="wd-lg-10p">Mã tài khoản</th>
                <th class="wd-lg-12p">Danh mục cha</th>
                <th class="wd-lg-18p">Mô tả</th>
                <th class="wd-lg-8p">Thứ tự</th>
                <th class="wd-lg-10p">Người phê duyệt</th>
                <th class="wd-lg-10p">Ngày tạo</th>
                <th class="wd-lg-6p">Thao tác</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="category in categories" :key="category.Id">
                <td>{{ category.Id }}</td>
                <td>
                  <strong>{{ category.Name }}</strong>
                  <span v-if="category.Level > 0" class="badge bg-secondary ms-2">Level {{ category.Level }}</span>
                </td>
                <td>
                  <span class="badge bg-light text-dark">{{ category.AccountCode || '-' }}</span>
                </td>
                <td>{{ category.ParentName || '-' }}</td>
                <td>{{ category.Description || '-' }}</td>
                <td>
                  <span class="badge bg-info">{{ category.DisplayOrder }}</span>
                </td>
                <td>{{ category.ApprovedByUserName || '-' }}</td>
                <td>{{ formatDate(category.CreatedDate) }}</td>
                <td>
                  <div class="d-flex gap-1">
                    <button type="button" class="btn btn-sm btn-outline-primary" @click="openEditModal(category)"
                      title="Chỉnh sửa">
                      <i class="fe fe-edit-2"></i>
                    </button>
                    <button type="button" class="btn btn-sm btn-outline-danger" @click="confirmDelete(category)"
                      title="Xóa">
                      <i class="fe fe-trash-2"></i>
                    </button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- Tree Mode -->
        <div v-else class="tree-mode-container">
          <div class="tree-view">
            <div v-for="category in categories" :key="category.Id" class="tree-node">
              <CategoryTreeNode :category="category" @edit="openEditModal" @delete="confirmDelete"
                @toggle="toggleNode" />
            </div>
          </div>
        </div>

        <!-- Pagination - Only show in List Mode -->
        <Pager v-if="isListMode && !loading && categories.length > 0" ref="ctrlPager"
          :Total="searchModel.Pagination.Total" :TotalCurrent="categories.length"
          @PageSizeChanged="handlePageSizeChanged" @PageIndexChanged="handlePageIndexChanged" />

        <!-- Tree Mode Info -->
        <div v-if="isTreeMode" class="mt-3">
          <div class="alert alert-info">
            <i class="fe fe-info me-2"></i>
            <strong>Chế độ cây phân cấp:</strong> Hiển thị toàn bộ cấu trúc danh mục ({{ searchModel.Pagination.Total }}
            mục) không có
            phân
            trang.
          </div>
        </div>
      </div>
    </div>

    <!-- Create/Edit Modal -->
    <LadaDialog :visible="showModal" variant="modal-lg">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title">
            {{ isEdit ? 'Chỉnh sửa danh mục doanh thu' : 'Thêm danh mục doanh thu' }}
          </h5>
          <button type="button" class="btn-close" @click="closeModal"></button>
        </div>
      </template>

      <template #body>
        <CategoryForm v-model="formData" :is-edit="isEdit" :is-submitting="isSubmitting" @submit="handleSubmit"
          @cancel="closeModal" />
      </template>
    </LadaDialog>

    <!-- Delete Confirmation Modal -->
    <LadaDialog :visible="showDeleteModal">
      <template #header>
        <div class="modal-header">
          <h5 class="modal-title">Xác nhận xóa</h5>
          <button type="button" class="btn-close" @click="closeDeleteModal"></button>
        </div>
      </template>

      <template #body>
        <p>Bạn có chắc chắn muốn xóa danh mục doanh thu <strong>{{ categoryToDelete?.Name }}</strong>?</p>
        <p class="text-muted">Hành động này không thể hoàn tác.</p>
      </template>

      <template #footer>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" @click="closeDeleteModal">
            Hủy
          </button>
          <button type="button" class="btn btn-danger" @click="handleDelete" :disabled="isDeleting">
            <span v-if="isDeleting" class="spinner-border spinner-border-sm me-2"></span>
            Xóa
          </button>
        </div>
      </template>
    </LadaDialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useToast } from 'vue-toastification'
import _ from 'lodash'
import incomeCategoryService from '@/services/incomeCategoryService'
import { CategoryForm, CategoryTreeNode } from './components'
import { Pager, Empty, LoadingOverlay } from '@/components'

// Toast
const toast = useToast()

// Data
const loading = ref(false)
const categories = reactive([])
const parentCategories = reactive([])
const searchModel = reactive(incomeCategoryService.createDefaultSearchModel())

// Pager ref
const ctrlPager = ref(null)

// Display Mode Options
const displayModeOptions = ref([
  { value: 'List', label: 'Danh sách (List)' },
  { value: 'Tree', label: 'Cây phân cấp (Tree)' }
])

// Computed
const isListMode = computed(() => searchModel.Search.PredicateObject.DisplayMode === 'List')
const isTreeMode = computed(() => searchModel.Search.PredicateObject.DisplayMode === 'Tree')

// Modal states
const showModal = ref(false)
const showDeleteModal = ref(false)
const isEdit = ref(false)
const isSubmitting = ref(false)
const isDeleting = ref(false)
const formData = ref({})
const categoryToDelete = ref(null)

// Temporary formatDate function
const formatDate = (dateString) => {
  if (!dateString) return '-'
  try {
    return new Date(dateString).toLocaleDateString('vi-VN')
  } catch {
    return '-'
  }
}

// Methods
const loadCategories = async () => {
  loading.value = true
  categories.splice(0, categories.length)
  const result = await incomeCategoryService.search(searchModel)
  if (result.Items != null && result.Items.length > 0) {
    result.Items.forEach(category => {
      categories.push(category)
    })
  }
  searchModel.Pagination.Total = result.TotalRecord
  loading.value = false
}

const handleSearch = () => {
  searchModel.Pagination.PageIndex = 1
  if (ctrlPager.value) {
    ctrlPager.value.Refresh()
  }
  loadCategories()
}

const handleReset = () => {
  Object.assign(searchModel, incomeCategoryService.createDefaultSearchModel())
  if (ctrlPager.value) {
    ctrlPager.value.Refresh()
  }
  loadCategories()
}

const handleDisplayModeChange = () => {
  // Reset pagination when switching to Tree mode
  if (searchModel.Search.PredicateObject.DisplayMode === 'Tree') {
    searchModel.Pagination.PageIndex = 1
    searchModel.Pagination.PageSize = 1000 // Large number to get all items
  } else {
    // Reset to default pagination for List mode
    searchModel.Pagination.PageSize = 25
    if (ctrlPager.value) {
      ctrlPager.value.Refresh()
      ctrlPager.value.updatePageSize(25)
    }
  }
  loadCategories()
}

const getParentCategories = async (keyword, loading) => {
  if (keyword.length) {
    loading(true)
    await getParentCategoriesDebounce(loading, keyword)
  }
}

// Flatten hierarchical data to flat array
const flattenCategories = (categories, level = 0) => {
  const result = []
  categories.forEach(category => {
    // Thêm category hiện tại với level
    result.push({
      ...category,
      Level: level
    })

    // Nếu có children, flatten chúng với level + 1
    if (category.Children && category.Children.length > 0) {
      const childrenFlattened = flattenCategories(category.Children, level + 1)
      result.push(...childrenFlattened)
    }
  })
  return result
}

let getParentCategoriesDebounce = _.debounce(async (loading, keyword) => {
  parentCategories.splice(0, parentCategories.length)

  try {
    const hierarchyResult = await incomeCategoryService.getHierarchy()
    if (hierarchyResult && hierarchyResult.length > 0) {
      // Flatten toàn bộ cây phân cấp thành mảng phẳng
      const flattenedCategories = flattenCategories(hierarchyResult)

      // Lọc theo keyword
      const filtered = flattenedCategories.filter(cat =>
        cat.Name.toLowerCase().includes(keyword.toLowerCase())
      )

      filtered.forEach(category => {
        parentCategories.push(category)
      })
    }
  } catch (error) {
    console.error('Error loading parent categories:', error)
  }

  loading(false)
}, 500)

const handlePageSizeChanged = (pageSize) => {
  searchModel.Pagination.PageSize = pageSize
  searchModel.Pagination.PageIndex = 1
  loadCategories()
}

const handlePageIndexChanged = (pageIndex) => {
  searchModel.Pagination.PageIndex = pageIndex
  loadCategories()
}

const openCreateModal = () => {
  formData.value = incomeCategoryService.createDefaultCategoryModel()
  isEdit.value = false
  showModal.value = true
}

const openEditModal = (category) => {
  formData.value = { ...category }
  isEdit.value = true
  showModal.value = true
}

const closeModal = () => {
  showModal.value = false
  formData.value = {}
  isEdit.value = false
}

const handleSubmit = async (data) => {
  try {
    isSubmitting.value = true
    const result = await incomeCategoryService.createOrUpdate(data)

    if (result.Result === 1) { // API trả về 1 cho success
      toast.success(result.Message || (isEdit.value ? 'Cập nhật thành công' : 'Tạo mới thành công'))
      closeModal()
      loadCategories()
    } else {
      toast.error(result.Message || 'Có lỗi xảy ra')
    }
  } catch (error) {
    console.error('Error submitting form:', error)
    toast.error('Có lỗi xảy ra khi lưu dữ liệu')
  } finally {
    isSubmitting.value = false
  }
}

const confirmDelete = (category) => {
  categoryToDelete.value = category
  showDeleteModal.value = true
}

const closeDeleteModal = () => {
  showDeleteModal.value = false
  categoryToDelete.value = null
}

const handleDelete = async () => {
  try {
    isDeleting.value = true

    // Kiểm tra có thể xóa không
    const result = await incomeCategoryService.delete(categoryToDelete.value.Id)

    if (result.Result === 1) { // API trả về 1 cho success
      toast.success(result.Message || 'Xóa thành công')
      closeDeleteModal()
      loadCategories()
    } else {
      toast.error(result.Message || 'Có lỗi xảy ra khi xóa')
    }


  } catch (error) {
    console.error('Error deleting category:', error)
    toast.error('Có lỗi xảy ra khi xóa danh mục doanh thu')
  } finally {
    isDeleting.value = false
  }
}

const toggleNode = () => {
  // Handle tree node toggle if needed
}

// Lifecycle
onMounted(() => {
  loadCategories()
})
</script>

<style scoped>
.income-categories-page {
  padding: 1rem;
}

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

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

.tree-mode-container {
  background-color: #f8f9fa;
  border-radius: 0.375rem;
  padding: 1rem;
  min-height: 400px;
}

.tree-view {
  background-color: white;
  border-radius: 0.375rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.tree-node:first-child .tree-node-content {
  border-top: 1px solid #e9ecef;
}

.alert-info {
  border-left: 4px solid #0dcaf0;
  background-color: rgba(13, 202, 240, 0.05);
}
</style>
