<template>
  <div class="expense-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 chi phí' : 'Thêm chi phí' }}</h4>
          <p class="text-muted mb-0">{{ isEdit ? 'Cập nhật thông tin chi phí' : 'Tạo mới 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">
            <ExpenseForm
              :id="route.params.id || '0'"
              :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 expenseService from '@/services/expenseService'
import { ExpenseForm } from './components'
import Loader from '@/components/loader.vue'

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

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

// Computed
const isEdit = computed(() => {
  const id = route.params.id
  return id && id !== '0' && id !== '' && id !== 'null' && id !== 'undefined'
})

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

const handleSubmit = async (data) => {
  try {
    isSubmitting.value = true
    
    console.log('Submitting expense data:', data)
    console.log('Is edit mode:', isEdit.value)
    console.log('Route params id:', route.params.id)
    
    // Ensure proper data structure for API
    const submitData = {
      ...data,
      // Use Id from form data if available, otherwise use route params or default
      Id: data.Id || (isEdit.value ? route.params.id : "00000000-0000-0000-0000-000000000000")
    }
    
    console.log('Final submit data:', submitData)
    
    const result = await expenseService.createOrUpdate(submitData)
    
    if (result && result.Result === 1) {
      const message = isEdit.value ? 'Cập nhật thành công' : 'Tạo mới thành công'
      toast.success(result.Message || message)
      goBack()
    } else {
      const errorMessage = result?.Message || 'Có lỗi xảy ra khi lưu dữ liệu'
      toast.error(errorMessage)
      console.error('API Error:', result)
    }
  } catch (error) {
    console.error('Error submitting form:', error)
    const errorMessage = error.response?.data?.Message || error.message || 'Có lỗi xảy ra khi lưu dữ liệu'
    toast.error(errorMessage)
  } finally {
    isSubmitting.value = false
  }
}
</script>

<style scoped>
.expense-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>
