<template>
    <Card class="suggested-settlements-card">
        <div class="header">
            <h3 class="title">Suggested Settlements</h3>
            <p class="subtitle">Optimal payments to settle all debts efficiently</p>
        </div>

        <div v-if="loading" class="loading-state">
            <Spinner label="Loading settlement suggestions..." />
        </div>

        <Alert v-else-if="error" type="error" :message="error" />

        <div v-else-if="suggestions.length === 0" class="empty-state">
            <BaseIcon name="heroicons:check-circle-solid" class="w-12 h-12 text-success-600 mx-auto mb-4" />
            <h4 class="empty-title">All Settled Up!</h4>
            <p class="empty-subtitle">
                No settlements needed. Everyone's balances are even.
            </p>
        </div>

        <div v-else class="suggestions-content">
            <div class="suggestions-header">
                <div class="suggestions-count">
                    {{ suggestions.length }} {{ suggestions.length === 1 ? 'settlement' : 'settlements' }} suggested
                </div>
                <div class="optimization-note">
                    Optimized to minimize the number of transactions
                </div>
            </div>

            <div class="suggestions-list">
                <div v-for="(suggestion, index) in suggestions" :key="index" class="suggestion-item">
                    <div class="suggestion-content">
                        <div class="payment-flow">
                            <div class="payer">
                                <BaseIcon name="heroicons:user-circle-solid" class="w-6 h-6 text-neutral-400" />
                                <span class="user-name">{{ suggestion.from_user_identifier }}</span>
                            </div>
                            <div class="arrow">
                                <BaseIcon name="heroicons:arrow-right" class="w-5 h-5 text-neutral-400" />
                            </div>
                            <div class="payee">
                                <BaseIcon name="heroicons:user-circle-solid" class="w-6 h-6 text-neutral-400" />
                                <span class="user-name">{{ suggestion.to_user_identifier }}</span>
                            </div>
                        </div>
                        <div class="amount">
                            {{ formatCurrency(parseFloat(suggestion.amount)) }}
                        </div>
                    </div>
                    <div class="suggestion-actions">
                        <Button variant="solid" size="sm" @click="$emit('settle', suggestion)" class="settle-button">
                            <BaseIcon name="heroicons:banknotes-solid" class="w-4 h-4 mr-1" />
                            Settle
                        </Button>
                    </div>
                </div>
            </div>

            <div class="summary-footer">
                <div class="total-settlements">
                    Total to be settled:
                    <span class="total-amount">
                        {{ formatCurrency(totalAmount) }}
                    </span>
                </div>
                <Button variant="outline" size="sm" @click="settleAll" :disabled="settling" class="settle-all-button">
                    <BaseIcon v-if="settling" name="heroicons:arrow-path" class="w-4 h-4 mr-1 animate-spin" />
                    <BaseIcon v-else name="heroicons:check-circle" class="w-4 h-4 mr-1" />
                    {{ settling ? 'Processing...' : 'Settle All' }}
                </Button>
            </div>
        </div>
    </Card>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { Card, Button, Spinner, Alert } from '@/components/ui'
import BaseIcon from '@/components/BaseIcon.vue'
import { costService } from '@/services/costService'
import { useNotificationStore } from '@/stores/notifications'
import type { GroupBalanceSummary } from '@/services/costService'

const props = defineProps<{
    groupId?: number
}>()

const emit = defineEmits<{
    (e: 'settle', suggestion: any): void
}>()

const notifications = useNotificationStore()

// State
const balanceSummary = ref<GroupBalanceSummary | null>(null)
const loading = ref(false)
const error = ref<string | null>(null)
const settling = ref(false)

// Computed
const suggestions = computed(() => {
    return balanceSummary.value?.suggested_settlements || []
})

const totalAmount = computed(() => {
    return suggestions.value.reduce((total, suggestion) => {
        return total + parseFloat(suggestion.amount)
    }, 0)
})

// Methods
function formatCurrency(amount: number) {
    try {
        return new Intl.NumberFormat(undefined, {
            style: 'currency',
            currency: 'USD'
        }).format(amount)
    } catch {
        return `$${amount.toFixed(2)}`
    }
}

async function loadSuggestions() {
    if (!props.groupId) return

    loading.value = true
    error.value = null

    try {
        balanceSummary.value = await costService.getGroupBalanceSummary(props.groupId)
    } catch (err: any) {
        error.value = err.response?.data?.detail || 'Failed to load settlement suggestions'
    } finally {
        loading.value = false
    }
}

async function settleAll() {
    if (suggestions.value.length === 0) return

    settling.value = true
    try {
        // Emit settle event for each suggestion
        for (const suggestion of suggestions.value) {
            emit('settle', suggestion)
        }

        notifications.addNotification({
            type: 'success',
            message: `${suggestions.value.length} settlements initiated`
        })

        // Reload suggestions after a short delay
        setTimeout(() => {
            loadSuggestions()
        }, 1000)
    } catch (err: any) {
        notifications.addNotification({
            type: 'error',
            message: 'Failed to process settlements'
        })
    } finally {
        settling.value = false
    }
}

// Lifecycle
onMounted(() => {
    loadSuggestions()
})

watch(() => props.groupId, () => {
    loadSuggestions()
})
</script>

<style scoped>
.suggested-settlements-card {
    @apply p-6;
}

.header {
    @apply mb-6;
}

.title {
    @apply text-lg font-semibold text-neutral-900 dark:text-neutral-100 mb-1;
}

.subtitle {
    @apply text-sm text-neutral-600 dark:text-neutral-400;
}

.loading-state {
    @apply py-8 text-center;
}

.empty-state {
    @apply py-12 text-center;
}

.empty-title {
    @apply text-lg font-semibold text-neutral-900 dark:text-neutral-100 mb-2;
}

.empty-subtitle {
    @apply text-sm text-neutral-600 dark:text-neutral-400;
}

.suggestions-content {
    @apply space-y-4;
}

.suggestions-header {
    @apply pb-4 border-b border-neutral-200 dark:border-neutral-700;
}

.suggestions-count {
    @apply text-sm font-medium text-neutral-900 dark:text-neutral-100;
}

.optimization-note {
    @apply text-xs text-neutral-500 dark:text-neutral-400 mt-1;
}

.suggestions-list {
    @apply space-y-3;
}

.suggestion-item {
    @apply flex items-center justify-between p-4 bg-neutral-50 dark:bg-neutral-800 rounded-lg hover:bg-neutral-100 dark:hover:bg-neutral-700 transition-colors;
}

.suggestion-content {
    @apply flex items-center gap-4 flex-1;
}

.payment-flow {
    @apply flex items-center gap-3;
}

.payer,
.payee {
    @apply flex items-center gap-2;
}

.user-name {
    @apply text-sm font-medium text-neutral-900 dark:text-neutral-100;
}

.arrow {
    @apply flex-shrink-0;
}

.amount {
    @apply text-lg font-semibold text-neutral-900 dark:text-neutral-100 ml-auto;
}

.suggestion-actions {
    @apply flex items-center;
}

.settle-button {
    @apply ml-4;
}

.summary-footer {
    @apply flex items-center justify-between pt-4 border-t border-neutral-200 dark:border-neutral-700;
}

.total-settlements {
    @apply text-sm text-neutral-600 dark:text-neutral-400;
}

.total-amount {
    @apply font-semibold text-neutral-900 dark:text-neutral-100;
}

.settle-all-button {
    @apply ml-4;
}
</style>