<template>
    <div class="settlement-form">
        <header class="form-header">
            <h2 class="form-title">
                {{ isEditing ? 'Edit Settlement' : 'Record Settlement' }}
            </h2>
            <p class="form-subtitle">
                {{ isEditing ? 'Update settlement details' : 'Record a payment between group members' }}
            </p>
        </header>

        <form @submit.prevent="handleSubmit" class="space-y-6">
            <!-- Amount -->
            <div class="form-group">
                <label for="amount" class="form-label">Amount</label>
                <div class="input-group">
                    <span class="input-prefix">$</span>
                    <Input id="amount" v-model="form.amount" type="number" step="0.01" min="0.01" placeholder="0.00"
                        required class="amount-input" />
                </div>
            </div>

            <!-- Payer -->
            <div class="form-group">
                <label for="payer" class="form-label">From (Who paid)</label>
                <select id="payer" v-model="form.paid_by_user_id" class="form-select" required>
                    <option value="">Select who paid...</option>
                    <option v-for="user in availableUsers" :key="user.id" :value="user.id">
                        {{ user.name ?? user.email }}
                    </option>
                </select>
            </div>

            <!-- Payee -->
            <div class="form-group">
                <label for="payee" class="form-label">To (Who received)</label>
                <select id="payee" v-model="form.paid_to_user_id" class="form-select" required>
                    <option value="">Select who received...</option>
                    <option v-for="user in availableUsers" :key="user.id" :value="user.id"
                        :disabled="user.id === form.paid_by_user_id">
                        {{ user.name ?? user.email }}
                    </option>
                </select>
            </div>

            <!-- Date -->
            <div class="form-group">
                <label for="date" class="form-label">Settlement Date</label>
                <Input id="date" v-model="form.settlement_date" type="date" required />
            </div>

            <!-- Description -->
            <div class="form-group">
                <label for="description" class="form-label">Description (optional)</label>
                <Textarea id="description" v-model="form.description" placeholder="Add a note about this settlement..."
                    :rows="3" />
            </div>

            <!-- Validation Errors -->
            <Alert v-if="validationError" type="error" :message="validationError" />

            <!-- Actions -->
            <div class="form-actions">
                <Button type="button" variant="outline" @click="$emit('close')" :disabled="submitting">
                    Cancel
                </Button>
                <Button type="submit" variant="solid" :loading="submitting" :disabled="!isFormValid">
                    {{ isEditing ? 'Update Settlement' : 'Record Settlement' }}
                </Button>
            </div>
        </form>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { Input, Textarea, Button, Alert } from '@/components/ui'
import { settlementService } from '@/services/settlementService'
import { useNotificationStore } from '@/stores/notifications'
import { useAuthStore } from '@/stores/auth'
import type { Settlement, SettlementCreate, SettlementUpdate } from '@/types/expense'
import type { UserPublic } from '@/types/user'
import { apiClient, API_ENDPOINTS } from '@/services/api'

const props = defineProps<{
    groupId?: number
    settlement?: Settlement | null
}>()

const emit = defineEmits<{
    (e: 'close'): void
    (e: 'saved', settlement: Settlement): void
}>()

const notifications = useNotificationStore()
const authStore = useAuthStore()

// State
const submitting = ref(false)
const validationError = ref<string | null>(null)
const availableUsers = ref<UserPublic[]>([])

const form = reactive({
    group_id: props.groupId || 0,
    paid_by_user_id: 0,
    paid_to_user_id: 0,
    amount: '',
    settlement_date: new Date().toISOString().split('T')[0],
    description: ''
})

// Computed
const isEditing = computed(() => !!props.settlement)

const isFormValid = computed(() => {
    return form.amount &&
        parseFloat(form.amount) > 0 &&
        form.paid_by_user_id > 0 &&
        form.paid_to_user_id > 0 &&
        form.paid_by_user_id !== form.paid_to_user_id &&
        form.settlement_date &&
        form.group_id > 0
})

// Methods
async function loadGroupMembers() {
    if (!props.groupId) return

    try {
        const response = await apiClient.get(`${API_ENDPOINTS.GROUPS.BASE}/${props.groupId}/members`)
        availableUsers.value = response.data
    } catch (error) {
        console.error('Failed to load group members:', error)
        notifications.addNotification({
            type: 'error',
            message: 'Failed to load group members'
        })
    }
}

async function handleSubmit() {
    if (!isFormValid.value || submitting.value) return

    // Validate that payer and payee are different
    if (form.paid_by_user_id === form.paid_to_user_id) {
        validationError.value = 'Payer and payee must be different people'
        return
    }

    submitting.value = true
    validationError.value = null

    try {
        let result: Settlement

        if (isEditing.value && props.settlement) {
            const updateData: SettlementUpdate = {
                description: form.description,
                settlement_date: form.settlement_date,
                version: props.settlement.version
            }
            result = await settlementService.updateSettlement(props.settlement.id, updateData)
        } else {
            const createData: SettlementCreate = {
                group_id: form.group_id,
                paid_by_user_id: form.paid_by_user_id,
                paid_to_user_id: form.paid_to_user_id,
                amount: form.amount,
                settlement_date: form.settlement_date,
                description: form.description || undefined
            }
            result = await settlementService.createSettlement(createData)
        }

        notifications.addNotification({
            type: 'success',
            message: isEditing.value ? 'Settlement updated successfully' : 'Settlement recorded successfully'
        })

        emit('saved', result)
    } catch (err: any) {
        validationError.value = err.response?.data?.detail || 'Failed to save settlement'
    } finally {
        submitting.value = false
    }
}

// Initialize form when editing
watch(() => props.settlement, (settlement) => {
    if (settlement) {
        form.group_id = settlement.group_id
        form.paid_by_user_id = settlement.paid_by_user_id
        form.paid_to_user_id = settlement.paid_to_user_id
        form.amount = settlement.amount
        form.settlement_date = settlement.settlement_date.split('T')[0]
        form.description = settlement.description || ''
    }
}, { immediate: true })

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

<style scoped>
.settlement-form {
    @apply p-6;
}

.form-header {
    @apply mb-6;
}

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

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

.form-group {
    @apply space-y-2;
}

.form-label {
    @apply block text-sm font-medium text-neutral-700 dark:text-neutral-300;
}

.input-group {
    @apply relative;
}

.input-prefix {
    @apply absolute left-3 top-1/2 transform -translate-y-1/2 text-neutral-500 dark:text-neutral-400;
}

.amount-input {
    @apply pl-8;
}

.form-select {
    @apply w-full px-3 py-2 border border-neutral-300 dark:border-neutral-600 rounded-md bg-white dark:bg-neutral-800 text-neutral-900 dark:text-neutral-100 focus:ring-2 focus:ring-primary focus:border-transparent disabled:bg-neutral-100 dark:disabled:bg-neutral-700 disabled:text-neutral-500;
}

.form-actions {
    @apply flex items-center justify-end gap-3 pt-4 border-t border-neutral-200 dark:border-neutral-700;
}
</style>