<template>
  <form @submit.prevent="handleSubmit" class="expense-form">
    <!-- Show error message if any -->
    <div v-if="error" class="alert alert-danger">
      {{ error }}
    </div>

    <!-- Existing form fields -->
    <div class="form-group">
      <label>Description</label>
      <input
        type="text"
        v-model="form.description"
        class="form-control"
        required
        :disabled="loading"
      >
    </div>

    <div class="form-group">
      <label>Amount</label>
      <div class="input-group">
        <span class="input-group-text">$</span>
        <input
          type="number"
          v-model.number="form.total_amount"
          class="form-control"
          step="0.01"
          min="0.01"
          required
          :disabled="loading"
        >
      </div>
    </div>

    <!-- Add recurring expense toggle -->
    <div class="form-group">
      <div class="form-check">
        <input
          type="checkbox"
          id="isRecurring"
          v-model="form.isRecurring"
          class="form-check-input"
          :disabled="loading"
        >
        <label for="isRecurring" class="form-check-label">
          This is a recurring expense
        </label>
      </div>
    </div>

    <!-- Show recurrence pattern form when isRecurring is true -->
    <RecurrencePatternForm
      v-if="form.isRecurring"
      v-model="form.recurrencePattern"
      :disabled="loading"
    />

    <!-- Rest of the existing form -->
    <div class="form-group">
      <label>Split Type</label>
      <select v-model="form.split_type" class="form-control" required :disabled="loading">
        <option value="EQUAL">Equal</option>
        <option value="EXACT_AMOUNTS">Exact Amounts</option>
        <option value="PERCENTAGE">Percentage</option>
        <option value="SHARES">Shares</option>
        <option value="ITEM_BASED">Item Based</option>
      </select>
    </div>

    <!-- Split configuration based on type -->
    <div v-if="showSplitConfiguration" class="split-configuration">
      <!-- Your existing split configuration UI -->
    </div>

    <div class="form-actions">
      <button
        type="submit"
        class="btn btn-primary"
        :disabled="loading"
      >
        <span v-if="loading" class="spinner-border spinner-border-sm me-2" role="status"></span>
        {{ isEditing ? 'Update' : 'Create' }} Expense
      </button>
      <button
        type="button"
        class="btn btn-secondary"
        @click="$emit('cancel')"
        :disabled="loading"
      >
        Cancel
      </button>
    </div>
  </form>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import type { Expense, RecurrencePattern } from '@/types/expense'
import RecurrencePatternForm from './RecurrencePatternForm.vue'
import { useExpenses } from '@/composables/useExpenses'

const props = defineProps<{
  expense?: Expense
  isEditing?: boolean
}>()

const emit = defineEmits<{
  (e: 'submit', expense: Partial<Expense>): void
  (e: 'cancel'): void
}>()

const { createExpense, updateExpense, loading, error } = useExpenses()

const form = ref({
  description: props.expense?.description || '',
  total_amount: props.expense?.total_amount || 0,
  currency: props.expense?.currency || 'USD',
  split_type: props.expense?.split_type || 'EQUAL',
  isRecurring: props.expense?.isRecurring || false,
  paid_by_user_id: props.expense?.paid_by_user_id || 0,
  recurrencePattern: props.expense?.recurrencePattern || {
    type: 'monthly' as const,
    interval: 1,
    daysOfWeek: [],
    endDate: undefined,
    maxOccurrences: undefined,
    id: 0,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString()
  } as RecurrencePattern,
  // Add other fields as needed
})

const showSplitConfiguration = computed(() => {
  return ['EXACT_AMOUNTS', 'PERCENTAGE', 'SHARES'].includes(form.value.split_type)
})

const handleSubmit = async () => {
  // Validate form
  if (form.value.isRecurring && !form.value.recurrencePattern) {
    alert('Please configure the recurrence pattern')
    return
  }

  try {
    const expenseData = {
      ...form.value,
      total_amount: form.value.total_amount.toString(),
    }

    if (props.isEditing && props.expense) {
      await updateExpense(props.expense.id, {
        ...expenseData,
        version: props.expense.version
      })
    } else {
      await createExpense(expenseData)
    }

    emit('submit', expenseData)
  } catch (err) {
    // Error is already handled by the composable
    console.error('Failed to save expense:', err)
  }
}
</script>

<style scoped>
.expense-form {
  max-width: 600px;
  margin: 0 auto;
  padding: 1rem;
}

.form-group {
  margin-bottom: 1rem;
}

.form-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
}

.input-group {
  display: flex;
  align-items: center;
}

.input-group-text {
  padding: 0.5rem;
  background-color: #f8f9fa;
  border: 1px solid #ced4da;
  border-right: none;
  border-radius: 4px 0 0 4px;
}

.form-check {
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.form-actions {
  display: flex;
  gap: 1rem;
  margin-top: 2rem;
}

.btn {
  padding: 0.5rem 1rem;
  border-radius: 4px;
  border: none;
  cursor: pointer;
}

.btn-primary {
  background-color: #007bff;
  color: white;
}

.btn-secondary {
  background-color: #6c757d;
  color: white;
}

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

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

.spinner-border {
  display: inline-block;
  width: 1rem;
  height: 1rem;
  vertical-align: text-bottom;
  border: 0.2em solid currentColor;
  border-right-color: transparent;
  border-radius: 50%;
  animation: spinner-border 0.75s linear infinite;
}

@keyframes spinner-border {
  to { transform: rotate(360deg); }
}
</style>
