<template>
  <div class="expense-list">
    <!-- Show loading state -->
    <div v-if="loading" class="loading-state">
      <div class="spinner-border" role="status">
        <span class="visually-hidden">Loading...</span>
      </div>
    </div>

    <!-- Show error message -->
    <div v-else-if="error" class="alert alert-danger">
      {{ error }}
    </div>

    <!-- Show empty state -->
    <div v-else-if="!expenses.length" class="empty-state">
      No expenses found
    </div>

    <!-- Show expenses -->
    <template v-else>
      <div v-for="expense in expenses" :key="expense.id" class="expense-item">
        <div class="expense-header">
          <h3>{{ expense.description }}</h3>
          <div class="expense-actions">
            <button
              @click="$emit('edit', expense)"
              class="btn btn-sm btn-outline-primary"
              :disabled="loading"
            >
              Edit
            </button>
            <button
              @click="handleDelete(expense.id)"
              class="btn btn-sm btn-outline-danger"
              :disabled="loading"
            >
              Delete
            </button>
          </div>
        </div>

        <div class="expense-details">
          <div class="amount">
            <span class="currency">{{ expense.currency }}</span>
            <span class="value">{{ formatAmount(expense.total_amount) }}</span>
          </div>

          <!-- Recurring expense indicator -->
          <div v-if="expense.isRecurring" class="recurring-indicator">
            <i class="fas fa-sync-alt"></i>
            <span>Recurring</span>
            <div class="recurrence-details" v-if="expense.recurrencePattern">
              {{ formatRecurrencePattern(expense.recurrencePattern) }}
            </div>
          </div>

          <div class="split-info">
            <span class="split-type">{{ formatSplitType(expense.split_type) }}</span>
            <span class="participants">{{ expense.splits.length }} participants</span>
          </div>
        </div>
      </div>
    </template>
  </div>
</template>

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

const props = defineProps<{
  expenses: Expense[]
}>()

const emit = defineEmits<{
  (e: 'edit', expense: Expense): void
  (e: 'delete', id: string): void
}>()

const { deleteExpense, loading, error } = useExpenses()

const formatAmount = (amount: string) => {
  return parseFloat(amount).toFixed(2)
}

const formatSplitType = (type: string) => {
  return type.split('_').map(word =>
    word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
  ).join(' ')
}

const formatRecurrencePattern = (pattern: RecurrencePattern) => {
  const parts = []

  // Format the type and interval
  parts.push(`${pattern.interval} ${pattern.type}`)

  // Add days of week for weekly recurrence
  if (pattern.type === 'weekly' && pattern.daysOfWeek?.length) {
    const days = pattern.daysOfWeek.map(day => {
      const dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
      return dayNames[day]
    }).join(', ')
    parts.push(`on ${days}`)
  }

  // Add end conditions
  if (pattern.endDate) {
    parts.push(`until ${new Date(pattern.endDate).toLocaleDateString()}`)
  } else if (pattern.maxOccurrences) {
    parts.push(`for ${pattern.maxOccurrences} occurrences`)
  }

  return parts.join(' ')
}

const handleDelete = async (id: number) => {
  if (confirm('Are you sure you want to delete this expense?')) {
    try {
      await deleteExpense(id)
      emit('delete', id.toString())
    } catch (err) {
      // Error is already handled by the composable
      console.error('Failed to delete expense:', err)
    }
  }
}
</script>

<style scoped>
.expense-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.expense-item {
  background: white;
  border-radius: 8px;
  padding: 1rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.expense-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 0.5rem;
}

.expense-header h3 {
  margin: 0;
  font-size: 1.1rem;
}

.expense-actions {
  display: flex;
  gap: 0.5rem;
}

.expense-details {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  align-items: center;
}

.amount {
  display: flex;
  align-items: baseline;
  gap: 0.25rem;
}

.currency {
  font-size: 0.9rem;
  color: #666;
}

.value {
  font-size: 1.2rem;
  font-weight: 500;
}

.recurring-indicator {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: #007bff;
  font-size: 0.9rem;
}

.recurrence-details {
  font-size: 0.8rem;
  color: #666;
}

.split-info {
  display: flex;
  gap: 0.5rem;
  font-size: 0.9rem;
  color: #666;
}

.btn {
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  border: 1px solid;
  cursor: pointer;
  font-size: 0.9rem;
}

.btn-sm {
  padding: 0.2rem 0.4rem;
  font-size: 0.8rem;
}

.btn-outline-primary {
  color: #007bff;
  border-color: #007bff;
  background: transparent;
}

.btn-outline-danger {
  color: #dc3545;
  border-color: #dc3545;
  background: transparent;
}

.btn:hover {
  opacity: 0.8;
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 2rem;
}

.empty-state {
  text-align: center;
  padding: 2rem;
  color: #666;
  font-style: italic;
}

.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: 2rem;
  height: 2rem;
  vertical-align: text-bottom;
  border: 0.25em solid currentColor;
  border-right-color: transparent;
  border-radius: 50%;
  animation: spinner-border 0.75s linear infinite;
}

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