<template>
  <div class="expense-search-form">
    <div class="card">
      <div class="card-body">
        <div class="row">
          <!-- Từ khóa tìm kiếm -->
          <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.Keyword"
              placeholder="Tìm theo mô tả, ghi chú..." @keyup.enter="handleSearch" />
          </div>

          <!-- Danh mục chi phí -->
          <div class="col-md-3 mb-3">
            <label class="form-label">Danh mục chi phí</label>
            <v-select v-model="searchModel.Search.PredicateObject.ExpenseCategoryId" :reduce="(option) => option.Id"
              label="Name" :filterable="false" :options="categories" @search="getCategories"
              placeholder="Chọn danh mục..." :clearable="true">
              <template #no-options="{ search, searching, loading }">
                Gõ từ khóa để tìm danh mục....
              </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>

          <!-- Trạng thái -->
          <div class="col-md-2 mb-3">
            <label class="form-label">Trạng thái</label>
            <v-select v-model="searchModel.Search.PredicateObject.Status" :options="statusOptions"
              :reduce="(option) => option.value" label="label" placeholder="Chọn trạng thái..." :clearable="true" />
          </div>

          <!-- Ngày tạo -->
          <div class="col-md-3 mb-3">
            <label class="form-label">Ngày tạo</label>
            <VueDatePicker ref="createDatePicker" v-model="date" :enable-time-picker="false" range multi-calendars
              auto-apply :format="format" @update:model-value="handleDate" placeholder="Chọn khoảng ngày...">
              <template #left-sidebar>
                <DateRangeSidebar @change-date="onChangeDate"></DateRangeSidebar>
              </template>
            </VueDatePicker>
          </div>

          <!-- Nút tìm kiếm -->
          <div class="col-md-3 mb-3 d-flex align-items-end">
            <div class="d-flex gap-2 w-100">
              <button type="button" class="btn btn-primary flex-fill" @click="handleSearch">
                <i class="fe fe-search me-2"></i>Tìm kiếm
              </button>
              <button type="button" class="btn btn-outline-secondary flex-fill" @click="handleReset">
                <i class="fe fe-refresh-cw me-2"></i>Đặt lại
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import _ from 'lodash'
import expenseService from '@/services/expenseService'
import expenseCategoryService from '@/services/expenseCategoryService'
import DatepickerInstance from "@vuepic/vue-datepicker"
import { DateRangeSidebar } from '@/components/index'

const props = defineProps({
  searchModel: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['search', 'reset'])

// Data
const categories = reactive([])
const statusOptions = ref(expenseService.getExpenseStatuses().map(status => ({
  value: status.value,
  label: status.text
})))
const date = ref()
const createDatePicker = ref(DatepickerInstance)

// Methods
const getCategories = async (keyword, loading) => {
  if (keyword.length) {
    loading(true)
    await getCategoriesDebounce(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 getCategoriesDebounce = _.debounce(async (loading, keyword) => {
  categories.splice(0, categories.length)

  try {
    const hierarchyResult = await expenseCategoryService.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 => {
        categories.push(category)
      })
    }
  } catch (error) {
    console.error('Error loading expense categories:', error)
  }

  loading(false)
}, 500)

const handleSearch = () => {
  emit('search')
}

const handleReset = () => {
  date.value = null
  emit('reset')
}

// Date handling functions
const format = (dates) => {
  if (!dates || dates.length < 2) return ''
  let start = dates[0]
  let end = dates[1]
  const dayStart = start.getDate()
  const monthStart = start.getMonth() + 1
  const yearStart = start.getFullYear()
  const dayEnd = end.getDate()
  const monthEnd = end.getMonth() + 1
  const yearEnd = end.getFullYear()

  return `${dayStart}/${monthStart}/${yearStart} - ${dayEnd}/${monthEnd}/${yearEnd}`
}

const onChangeDate = async (newDates) => {
  date.value = newDates
  createDatePicker.value.closeMenu()
  handleDate(newDates)
}

const handleDate = (modelData) => {
  if (modelData != null && modelData.length >= 2) {
    props.searchModel.Search.PredicateObject.CreatedStart = modelData[0]
    props.searchModel.Search.PredicateObject.CreatedEnd = modelData[1]
  } else {
    props.searchModel.Search.PredicateObject.CreatedStart = null
    props.searchModel.Search.PredicateObject.CreatedEnd = null
  }
}
</script>

<style scoped>
.expense-search-form {
  margin-bottom: 1rem;
}

.form-label {
  font-weight: 500;
  margin-bottom: 0.5rem;
  color: #495057;
}

.btn {
  font-size: 0.875rem;
}

.flex-fill {
  flex: 1 1 auto;
}
</style>
