import {reactive, ref} from 'vue'
import axios from 'axios'
import {STEP_PAYMENT, STEP_SUMMARY} from './stepFlow.js'

export function useSignupForm(event, participantData) {
    const currentStep = ref(1)
    const submitting = ref(false)
    const summaryLoading = ref(false)
    const submitResult = ref(null) // null | { type: 'success'|'exists', data: {} }

    const selectedAddons = reactive({})

    // Für die Aktion freigeschaltete Zahlungsmethoden; ist genau eine aktiv, wird sie vorausgewählt.
    const activeMethods = (event.paymentMethods ?? []).filter(m => m.active)

    const formData = reactive({
        eatingHabit: 'EATING_HABIT_VEGAN',
        paymentMethod: activeMethods.length === 1 ? activeMethods[0].slug : null,
        paymentOptions: {},
        // Antworten auf die event-spezifischen Teilnahmeoptionen: { [question.key]: option.value }
        participationOptions: {},
        userId: participantData.id,
        eventId: event.id,
        vorname: participantData.firstname ?? '',
        nachname: participantData.lastname ?? '',
        pfadiname: participantData.nickname ?? '',
        localGroup: participantData.localGroup ?? '-1',
        geburtsdatum: participantData.birthday ?? '',
        address1: participantData.address_1 ?? '',
        address2: participantData.address_2 ?? '',
        plz: participantData.postcode ?? '',
        ort: participantData.city ?? '',
        telefon_1: participantData.phone ?? '',
        email_1: participantData.email ?? '',
        participationType: '',
        ansprechpartner: '',
        telefon_2: '',
        email_2: '',
        badeerlaubnis: '-1',
        sibling: '-1',
        first_aid: '-1',
        participant_group: '',
        beitrag: 'regular',
        arrival: event.arrivalDefault ?? '',
        departure: event.departureDefault ?? '',
        anreise_essen: '1',
        abreise_essen: '2',
        foto: { socialmedia: false, print: false, webseite: false, partner: false, intern: false },
        allergien: participantData.allergies ?? '',
        intolerances: participantData.intolerances ?? '',
        medikamente: participantData.medications ?? '',
        tetanusVaccination: participantData.tetanusVaccination ?? '',
        essgewohnheit: 'vegetarian',
        anmerkungen: '',
        summary_information_correct: false,
        summary_accept_terms: false,
        legal_accepted: false,
        payment: false,
    })

    const summaryAmount = ref('')
    const summaryAmountValue = ref(0)
    const summaryBaseAmount = ref('')
    const summaryAddonLines = ref([])

    const fetchAmount = async () => {
        summaryLoading.value = true
        try {
            const res = await axios.post('/api/v1/event/' + event.id + '/calculate-amount', {
                arrival: formData.arrival,
                departure: formData.departure,
                event_id: event.id,
                participation_group: formData.participant_group,
                selected_amount: formData.beitrag,
                addons: selectedAddons,
                participationType: formData.participationType,
                beitrag: formData.beitrag,
                sibling: formData.sibling,
            })
            summaryAmount.value = res.data.amount
            summaryAmountValue.value = Number(res.data.amountValue ?? 0)
            summaryBaseAmount.value = res.data.baseAmount ?? ''
            summaryAddonLines.value = res.data.addons ?? []
        } finally {
            summaryLoading.value = false
        }
    }

    const goToStep = async (step) => {
        if (step === STEP_PAYMENT) {
            // Betrag ermitteln: Bei 0 € wird die Zahlungsart-Auswahl übersprungen.
            await fetchAmount()
            if (summaryAmountValue.value <= 0) {
                formData.paymentMethod = null
                formData.paymentOptions = {}
                currentStep.value = STEP_SUMMARY
                return
            }
        } else if (step === STEP_SUMMARY) {
            await fetchAmount()
        }
        currentStep.value = step
    }

    const submit = async () => {
        // Zahlungs-Bestätigung wird im Summary-Schritt kontextabhängig erzwungen (nur bei Überweisung).
        if (!formData.summary_information_correct || !formData.summary_accept_terms || !formData.legal_accepted) {
            return
        }
        submitting.value = true
        try {
            const res = await axios.post('/api/v1/event/'+ event.id + '/signup', {
                addons: selectedAddons,
                registration_data: { ...formData },
            })
            submitResult.value = {
                status: res.data.status,
                participant: res.data.participant,
            }
        } finally {
            submitting.value = false
        }
    }

    return {
        currentStep,
        goToStep,
        formData,
        selectedAddons,
        submit,
        submitting,
        submitResult,
        summaryLoading,
        summaryAmount,
        summaryAmountValue,
        summaryBaseAmount,
        summaryAddonLines
    }
}
