<template>
  <div class="income-form">
    <Form @submit="onSubmit" :validation-schema="schema" :initial-values="initialFormData" v-slot="{ errors }" class="row">
      <!-- Mô tả doanh thu -->
      <div class="col-md-12 mb-3">
        <label class="form-label">Mô tả doanh thu <span class="text-danger">*</span></label>
        <Field name="Description" v-model="formData.Description" type="text" class="form-control"
          placeholder="Nhập mô tả doanh thu..." :class="{ 'is-invalid': errors.Description }" />
        <div class="invalid-feedback">{{ errors.Description }}</div>
      </div>

      <!-- Số tiền -->
      <div class="col-md-6 mb-3">
        <label class="form-label">Số tiền <span class="text-danger">*</span></label>
        <Field name="Amount" v-slot="{ field }">
          <VueNumberFormat 
            v-model:value="formData.Amount" 
            class="form-control"
            :options="{ precision: 0, prefix: '', suffix: ' VND', decimal: ',', thousand: '.', isInteger: true }"
            placeholder="Nhập số tiền..."
            :class="{ 'is-invalid': errors.Amount }"
            @update:modelValue="(value) => {
              // Convert formatted value to number for validation
              const numValue = value ? parseFloat(value.toString().replace(/[.,]/g, '').replace(' VND', '')) : null
              field.onInput(numValue)
            }" />
        </Field>
        <div class="invalid-feedback d-block" v-if="errors.Amount">{{ errors.Amount }}</div>
      </div>

      <!-- Danh mục doanh thu -->
      <div class="col-md-6 mb-3">
        <label class="form-label">Danh mục doanh thu <span class="text-danger">*</span></label>
        <v-select 
          v-model="formData.IncomeCategoryId"
          label="Name" 
          :options="categories"
          :reduce="(option) => option.Id"
          placeholder="Chọn danh mục..." 
          @search="getCategories">
          <template #no-options="{ search, searching }">
            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>
        <Field v-model="formData.IncomeCategoryId" name="IncomeCategoryId" type="hidden" />
        <ErrorMessage class="invalid-feedback d-block" name="IncomeCategoryId" />
      </div>

      <!-- Ghi chú -->
      <div class="col-md-12 mb-3">
        <label class="form-label">Ghi chú</label>
        <Field as="textarea" rows="3" name="Note" v-model="formData.Note" class="form-control"
          placeholder="Nhập ghi chú (tùy chọn)..." :class="{ 'is-invalid': errors.Note }" />
        <div class="invalid-feedback">{{ errors.Note }}</div>
      </div>

      <!-- Buttons -->
      <div class="col-12 d-flex justify-content-end gap-2">
        <button type="button" class="btn btn-secondary" @click="handleCancel" :disabled="isSubmitting">
          Hủy
        </button>
        <button type="submit" class="btn btn-primary" :disabled="isSubmitting">
          <span v-if="isSubmitting" class="spinner-border spinner-border-sm me-2"></span>
          {{ isEdit ? 'Cập nhật' : 'Tạo mới' }}
        </button>
      </div>
    </Form>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive, watch } from 'vue'
import { Form, Field, ErrorMessage } from 'vee-validate'
import * as Yup from 'yup'
import _ from 'lodash'
import incomeCategoryService from '@/services/incomeCategoryService'
import incomeService from '@/services/incomeService'

const props = defineProps({
  id: {
    type: [Number, String],
    default: '0'
  },
  isSubmitting: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['submit', 'cancel'])

// Data
const categories = reactive([])
const formData = reactive(incomeService.createDefaultIncomeModel())
const loading = ref(false)

// Computed
const isEdit = computed(() => {
  // Check if id is a valid GUID (not '0', null, undefined, or empty)
  const id = props.id?.toString()
  const result = id && id !== '0' && id !== '' && id !== 'null' && id !== 'undefined'
  return result
})

// Initial form data for vee-validate
const initialFormData = computed(() => {
  return {
    ...formData,
    IncomeCategoryId: formData?.IncomeCategoryId || null
  }
})

// Validation schema
const schema = Yup.object().shape({
  Description: Yup.string()
    .required('Mô tả doanh thu không được để trống')
    .max(256, 'Không vượt quá 256 ký tự'),
  Amount: Yup.number()
    .typeError('Số tiền không hợp lệ')
    .required('Số tiền không được để trống')
    .min(1, 'Số tiền phải lớn hơn 0'),
  IncomeCategoryId: Yup.number()
    .required('Danh mục doanh thu không được để trống')
    .min(1, 'Vui lòng chọn danh mục doanh thu'),
  Note: Yup.string()
    .nullable()
    .max(500, 'Không vượt quá 500 ký tự')
})

// Load categories function
const loadCategoriesForForm = async () => {
  try {
    categories.splice(0, categories.length)
    const hierarchyResult = await incomeCategoryService.getHierarchy()
    if (hierarchyResult && hierarchyResult.length > 0) {
      const flattenedCategories = flattenCategories(hierarchyResult)
      flattenedCategories.forEach(category => {
        categories.push(category)
      })
    }
  } catch (error) {
    console.error('Error loading categories:', error)
  }
}

const flattenCategories = (categories, level = 0) => {
  const result = []
  categories.forEach(category => {
    result.push({
      ...category,
      Level: level
    })
    if (category.Children && category.Children.length > 0) {
      const childrenFlattened = flattenCategories(category.Children, level + 1)
      result.push(...childrenFlattened)
    }
  })
  return result
}

const getCategories = async (keyword, loading) => {
  if (keyword && keyword.length) {
    loading(true)
    await getCategoriesDebounce(loading, keyword)
  }
}

let getCategoriesDebounce = _.debounce(async (loading, keyword) => {
  try {
    categories.splice(0, categories.length)
    const hierarchyResult = await incomeCategoryService.getHierarchy()
    if (hierarchyResult && hierarchyResult.length > 0) {
      const flattenedCategories = flattenCategories(hierarchyResult)
      const filtered = flattenedCategories.filter(cat =>
        cat.Name.toLowerCase().includes(keyword.toLowerCase())
      )
      filtered.forEach(category => {
        categories.push(category)
      })
    }
  } catch (error) {
    console.error('Error searching categories:', error)
  }
  loading(false)
}, 500)

// Load dữ liệu income nếu đang edit
const loadIncomeData = async () => {
  if (!isEdit.value) {
    // Tạo mới - khởi tạo dữ liệu mặc định
    const defaultData = incomeService.createDefaultIncomeModel()
    Object.assign(formData, defaultData)
    return
  }

  try {
    loading.value = true
    const income = await incomeService.getById(props.id)
    
    if (income) {
      Object.assign(formData, income)
    } else {
      const defaultData = incomeService.createDefaultIncomeModel()
      Object.assign(formData, defaultData)
    }
  } catch (error) {
    console.error('Error loading income data:', error)
    const defaultData = incomeService.createDefaultIncomeModel()
    Object.assign(formData, defaultData)
  } finally {
    loading.value = false
  }
}

const onSubmit = async (values, { setFieldError }) => {
  try {
    // Use values from Form and merge with formData to include Id
    const submitData = { 
      ...values,
      Id: formData.Id // Include Id from formData
    }
    
    // Ensure Amount is properly converted to number
    if (submitData.Amount) {
      if (typeof submitData.Amount === 'string') {
        submitData.Amount = parseFloat(submitData.Amount.toString().replace(/[.,]/g, '').replace(' VND', ''))
      }
      
      // Validate amount after conversion
      if (isNaN(submitData.Amount) || submitData.Amount <= 0) {
        setFieldError('Amount', 'Số tiền phải lớn hơn 0')
        return
      }
    }
    
    emit('submit', submitData)
  } catch (error) {
    console.error('Error in onSubmit:', error)
  }
}

const handleCancel = () => {
  emit('cancel')
}

// Lifecycle
onMounted(async () => {
  // Load danh sách danh mục doanh thu
  await loadCategoriesForForm()
  
  // Load dữ liệu income (nếu edit mode)
  await loadIncomeData()
})

// Watch for props.id changes to reload data
watch(() => props.id, async (newId, oldId) => {
  if (newId !== oldId) {
    await loadIncomeData()
  }
})
</script>

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

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

.text-danger {
  color: #dc3545 !important;
}

.is-invalid {
  border-color: #dc3545;
}

.invalid-feedback {
  display: block;
  color: #dc3545;
  font-size: 0.875rem;
  margin-top: 0.25rem;
}

.btn {
  font-size: 0.875rem;
}
</style>

