<template>
  <div class="expense-category-create-update-page">
    <!-- Header -->
    <div class="d-flex justify-content-between align-items-center mb-4">
      <div class="d-flex align-items-center">
        <button 
          type="button" 
          class="btn btn-outline-secondary me-3"
          @click="goBack"
        >
          <i class="fe fe-arrow-left me-2"></i>Quay lại
        </button>
        <div>
          <h4 class="mb-1">{{ isEdit ? 'Chỉnh sửa danh mục chi phí' : 'Thêm danh mục chi phí' }}</h4>
          <p class="text-muted mb-0">{{ isEdit ? 'Cập nhật thông tin danh mục chi phí' : 'Tạo mới danh mục chi phí trong hệ thống' }}</p>
        </div>
      </div>
    </div>

    <!-- Loading -->
    <div v-if="loading" class="text-center py-5">
      <Loader />
    </div>

    <!-- Error -->
    <div v-else-if="error" class="alert alert-danger">
      <i class="fe fe-alert-circle me-2"></i>{{ error }}
    </div>

    <!-- Form -->
    <div v-else class="row justify-content-center">
      <div class="col-lg-8">
        <div class="card">
          <div class="card-body">
            <CategoryForm
              v-model="formData"
              :is-edit="isEdit"
              :is-submitting="isSubmitting"
              @submit="handleSubmit"
              @cancel="goBack"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useToast } from 'vue-toastification'
import expenseCategoryService from '@/services/expenseCategoryService'
import { CategoryForm } from './components'

// Router & Toast
const route = useRoute()
const router = useRouter()
const toast = useToast()

// Data
const loading = ref(false)
const error = ref('')
const isSubmitting = ref(false)
const formData = ref({})

// Computed
const isEdit = computed(() => {
  return !!route.params.id
})

// Methods
const loadCategory = async () => {
  if (!isEdit.value) {
    formData.value = expenseCategoryService.createDefaultCategoryModel()
    return
  }

  try {
    loading.value = true
    error.value = ''
    
    const categoryId = route.params.id
    const result = await expenseCategoryService.getById(categoryId)
    
    if (result) {
      formData.value = { ...result }
    } else {
      error.value = 'Không tìm thấy danh mục chi phí'
    }
  } catch (err) {
    console.error('Error loading category:', err)
    error.value = 'Có lỗi xảy ra khi tải thông tin danh mục chi phí'
  } finally {
    loading.value = false
  }
}

const goBack = () => {
  router.push('/quan-ly-danh-muc-chi-phi')
}

const handleSubmit = async (data) => {
  try {
    isSubmitting.value = true
    let result
    
    if (isEdit.value) {
      result = await expenseCategoryService.update(data.Id, data)
    } else {
      result = await expenseCategoryService.create(data)
    }
    
    if (result.Result === 1) {
      toast.success(result.Message || (isEdit.value ? 'Cập nhật thành công' : 'Tạo mới thành công'))
      goBack()
    } 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
  }
}

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

<style scoped>
.expense-category-create-update-page {
  padding: 1rem;
}

.alert {
  padding: 0.75rem 1rem;
  margin-bottom: 1rem;
  border: 1px solid transparent;
  border-radius: 0.375rem;
}

.alert-danger {
  color: #721c24;
  background-color: #f8d7da;
  border-color: #f5c6cb;
}

.text-muted {
  color: #6c757d !important;
}
</style>
