import React from 'react';
import AgeContainer from './partials/age.jsx';
import ContactPersonContainer from './partials/contactperson.jsx';
import PersonalDataContainer from './partials/personaldata.jsx';
import SolidarityRegistrationContainer from './partials/registration-solidarity.jsx';
import GroupSelectionContainer from './partials/registration-groupbased.jsx';
import ArrivalContainer from './partials/arrival.jsx';
import AddonsContainer from "./partials/addons.jsx";
import PhotopermissionsContainer from "./partials/photopermissions.jsx";
import AllergiesContainer from "./partials/allergies.jsx";
import SummaryContainer from "./partials/summary.jsx";
import { FinalValidator } from '../../../assets/javascripts/registration-validator.js'
import { SelectedAddons } from '../../../assets/javascripts/registration-validator.js'
import SuccessContainer from "./after-submit/success.jsx";
import ReactDOM from "react-dom/client";
import AlreadyExistsContainer from "./after-submit/alreadyexist.jsx";
import { __ } from '../../../assets/javascripts/library.js';

const { configuration, labels, participant_data, event_data, local_groups } = window.solea_data;

function showStep(step) {
    var steps = [
        'step_1',   // Age-Selector
        'step_2',   // Children only: Contact data
        'step_3',   // Personal data
        'step_4',   // Participation group
        'step_5',   // Arival & Departure
        'step_6',   // Addon information
        'step_7',   // Photo-Permissions
        'step_8',   // Allergies & Intolerances
        'step_9'    // Summary
    ];

    for (var idx = 0; idx < steps.length; idx++) {
        var currentElement = steps[idx];
        document.getElementById(currentElement).classList.add('container_hidden');
        document.getElementById(currentElement).classList.remove('container_visible');
    }

    document.getElementById('step_' + step).classList.remove('container_hidden');
    document.getElementById('step_' + step).classList.add('container_visible');

    document.getElementById('summary_loading').classList.remove('container_hidden');
    document.getElementById('summary_loading').classList.add('container_visible');
    document.getElementById('summary_content').classList.add('container_hidden');
    document.getElementById('summary_content').classList.remove('container_visible');

    if (step === 9) {
        var [ayear, amonth, aday] = document.getElementById('anreise').value.split('-');
        var [dyear, dmonth, dday] = document.getElementById('abreise').value.split('-');

        document.getElementById('summary_eventname').innerHTML= event_data.event_name;
        document.getElementById('summary_arrival').innerHTML=`${aday}.${amonth}.${ayear}`;
        document.getElementById('summary_departure').innerHTML=`${dday}.${dmonth}.${dyear}`;

        const response = fetch("/wp-json/solea/signup/preview_amount", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                anreise: document.getElementById('anreise').value,
                abreise: document.getElementById('abreise').value,
                event_id: event_data.id,
                participation_group: document.querySelector('input[name="participant_group"]:checked').value,
                selected_amount: document.querySelector('input[name="beitrag"]:checked').value,
                addons: SelectedAddons(),
            }),
        })
            .then((res) => res.json())
            .then((data) => {
                document.getElementById('payment_information_label').innerHTML = data.amount
                document.getElementById('summary_loading').classList.add('container_hidden');
                document.getElementById('summary_loading').classList.remove('container_visible');

                document.getElementById('summary_content').classList.add('container_visible');
                document.getElementById('summary_content').classList.remove('container_hidden');
            });
    }
}

function ParticipantSignup() {
    let RegistrationMode;

    switch (event_data.registration_mode) {
        case 'solidarity':
            RegistrationMode = SolidarityRegistrationContainer;
            break;

        case 'groupbased':
            RegistrationMode = GroupSelectionContainer;
            break;
    }

    const handleSubmit = (e) => {
        e.preventDefault();
        const form = e.target;
        const data = new FormData(form);

        if (!FinalValidator()) {
            return;
        }

        const formData = Object.fromEntries(data.entries());
        const response = fetch("/wp-json/solea/signup/do-register", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                addons: SelectedAddons(),
                registration_data: formData
                })
        })
        .then((res) => res.json())
        .then((data) => {
            const container = document.getElementById('solea_registration_form_frame');
            const root = ReactDOM.createRoot(container);

            if (data.already_exists === true) {
                root.render(<AlreadyExistsContainer participant_data={data.result} labels={labels} />);
            } else {
                root.render(<SuccessContainer participant_data={data.result} />);
            }
        });
    }

    return (
        <div className="solea-event-registration-container">
            <table class="solea-event-meta-data-table">
                <tr>
                    <td>{__('Event location', 'solea')}:</td>
                    <td>{event_data.postalcode} {event_data.location}</td>
                </tr>

                <tr>
                    <td>{__('Event duration', 'solea')}:</td>
                    <td>{event_data.date_begin_formatted} - {event_data.date_end_formatted}</td>
                </tr>

                <tr>
                    <td>{__('Regular registration until', 'solea')}:</td>
                    <td>{event_data.last_minute_begin_formatted}</td>
                </tr>

                <tr>
                    <td>
                        {__('Extended registration until', 'solea')}:
                    </td>
                    <td>
                        {event_data.registration_end_formatted}
                    </td>
                </tr>

                <tr>
                    <td>
                        {__('Cancellation', 'solea')}:
                    </td>
                    <td>
                        100% {__('until', 'solea')} {event_data.last_minute_begin_formatted} {__('available', 'solea')}<br />
                        {event_data.reduced_return}% {__('until', 'solea')} {event_data.registration_end_formatted} {__('available', 'solea')}<br />
                    </td>
                </tr>

                <tr>
                    <td colSpan="2">
                        { __('Do you have questions for registration? Please contact us by email:', 'solea') }&nbsp;
                        <a href={"mailto:" + event_data.event_email}>{event_data.event_email}</a>
                    </td>
                </tr>
            </table>

            <div id="solea_registration_form_frame">
                <form id="registration_form" onSubmit={handleSubmit}>
                    <input type="hidden" name="solea-user-id" value={participant_data.id} />
                    <input type="hidden" name="event-id" value={event_data.id} />
                    <div id="step_1" className="container_visible">
                        <AgeContainer
                            onStepClick={showStep}
                            labels={labels}
                            configuration={configuration}
                        />
                    </div>

                    <div id="step_2" className="container_hidden">
                        <ContactPersonContainer
                            onStepClick={showStep}
                            labels={labels}
                            participant_data={participant_data}
                        />
                    </div>

                    <div id="step_3" className="container_hidden">
                        <PersonalDataContainer
                            onStepClick={showStep}
                            labels={labels}
                            participant_data={participant_data}
                            local_groups={local_groups}
                        />
                    </div>

                    <div id="step_4" className="container_hidden">
                        <RegistrationMode
                            onStepClick={showStep}
                            labels={labels}
                            participant_data={participant_data}
                            local_groups={local_groups}
                            event_data={event_data}
                        />
                    </div>

                    <div id="step_5" className="container_hidden">
                        <ArrivalContainer
                            onStepClick={showStep}
                            labels={labels}
                            event_data={event_data}
                            local_groups={local_groups}
                        />
                    </div>

                    <div id="step_6" className="container_hidden">
                        <AddonsContainer
                            onStepClick={showStep}
                            labels={labels}
                            event_data={event_data}
                            local_groups={local_groups}
                        />
                    </div>

                    <div id="step_7" className="container_hidden">
                        <PhotopermissionsContainer
                            event_data={event_data}
                            onStepClick={showStep}
                            labels={labels}
                        />
                    </div>

                    <div id="step_8" className="container_hidden">
                        <AllergiesContainer
                            onStepClick={showStep}
                            labels={labels}
                            participant_data={participant_data}
                            event_data={event_data}
                        />
                    </div>

                    <div id="step_9" className="container_hidden">
                        <p id="summary_loading">Wird geladen</p>
                        <p id="summary_content" className="container_hidden">
                            <SummaryContainer
                                onStepClick={showStep}
                                labels={labels}
                                participant_data={participant_data}
                                event_data={event_data}
                            />
                            <input type="button" value={labels.common.go_back} onClick={() => showStep(8)} /> &nbsp;
                            <input className="acceptallbutton" type="submit" value={labels.common.confirm}/>
                        </p>
                    </div>
                </form>
            </div>
        </div>

    );
}

export default ParticipantSignup;