import $ from 'jquery';
import 'jquery-ui-dist/jquery-ui.min.css';
import '../../../css/formeo.css';
import 'jquery-ui-dist/jquery-ui.min.js';
import 'intl-tel-input/build/css/intlTelInput.css';
import { Helpers } from '../../utils/helpers';
import { EbFormeo } from '../../utils/eb-formeo';
import './component/SingleAttendeeFormComponent.js';
import { Country, State } from 'country-state-city';
import { Config } from '../../../config.js';
import '../../../icon-fonts/style.css';
import '../../../css/form-control.css';
import './style.css';
import { Constants } from '../../utils/constants.js';


/*params
 * eventDetails: Event details json object
 * ticketData : Line Items of selected tickets
*/

function Checkout(data) {
    const eventDetails = data?.eventDetails;
    const ticketData = data?.ticketData;
    const orderPayloadCallback = data?.orderPayloadCallback;
    let isCouponApplied = false;
    let hasAgeRestriction = false;

    if (!eventDetails || !ticketData) return null;

    $('<script>').attr('src', `https://maps.googleapis.com/maps/api/js?key=AIzaSyDZU1iNQDWeXWw-m5YQqZLrIb8ghMgc_j4&libraries=places&v=weekly&callback=initAutocomplete`)
        .attr('async', true)
        .attr('defer', true)
        .appendTo('head');

    const $container = $('<div>', { class: 'eb-event-checkout-wrapper' });

    const $content = $(`
        <div class="eb-event-checkout-container">
            <div class="eb-event-checkout-content-wrap">
              
                <!--Terms and condition text modal -->
                <div class="eb-modal-wrapper eb-d-none" id="terms-modal">
                    <div class="eb-modal-wrap">
                        <div class="eb-modal-dialog">
                            <div class="eb-modal-content">
                                                        
                                <div class="eb-modal-header">
                                    <div class="eb-modal-title">
                                        <h3>Terms & conditions</h3>
                                    </div>
                                    <button type="button" class="terms-modal-close eb-modal-close"><i class="ebi-icon-close"></i></button>
                                </div>
                            
                                <div class="eb-modal-body">
                                   <div id="terms-text">Body</div>
                                </div>
    
                                <div class="eb-modal-footer">
                                    <span>&nbsp;</span>
                                    <div class="eb-gap-9">
                                         <button type="button" class="terms-modal-close eb-btn-close">Cancel</button>
                                         <button type="button" id="terms-accept" class="eb-btn-primary">Accept</button>
                                    </div>
                                </div>
                                
                            </div>
                        </div>
                    </div>
                </div>
    
                <div class="eb-checkout-page-title-wrap">
                    <div class="eb-back-btn">
                        <a id="backToEventDetails" href="#">
                            <i class="ebi-icon-left-arrow"></i>
                            <span>Back</span>
                        </a>
                    </div>
                    <div class="eb-checkout-title">
                        <h2>Checkout </h2>
                    </div>
                </div>
                <div class="eb-checkout-left-form-wrap">
                    <div class="eb-checkout-left-form-content">                    
                        <form id="updatebilling_form" enctype="multipart/form-data">
                            <div class="eb-form-row">
                                <div class="eb-col-6">
                                    <div class="eb-form-group">
                                        <label for="firstName">First Name <span class="text-red">*</span></label>
                                        <div class="eb-input-holder">
                                            <input type="text" id="firstName" name="first_name" class="eb-form-control" required maxlength="40">
                                            <span class="error" id="firstNameError"></span>
                                        </div>
                                    </div>
                                </div>
                
                                <div class="eb-col-6">
                                    <div class="eb-form-group">
                                        <label for="lastName">Last Name <span class="text-red">*</span></label>
                                        <div class="eb-input-holder">
                                            <input type="text" id="lastName" name="last_name" class="eb-form-control" required maxlength="40">
                                            <span class="error" id="lastNameError"></span>
                                        </div>
                                    </div>
                                </div>
                            
                                <div class="eb-col-6">
                                    <div class="eb-form-group">
                                        <label for="email">Email <span class="text-red">*</span></label>
                                        <div class="eb-input-holder">
                                            <input type="email" id="email" name="email" class="eb-form-control" required>
                                            <span class="error" id="emailError"></span>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="eb-col-6 group-company">
                                    <div class="eb-form-group">
                                        <label for="company">Company Name <span class="text-red company-optional-mandatory-icon">*</span></label>
                                        <div class="eb-input-holder">
                                            <input type="text" id="company" name="company" class="eb-form-control">
                                            <span class="error" id="companyError"></span>
                                        </div>
                                    </div>
                                </div>

                                <div class="eb-col-6 group-address">
                                    <div class="eb-form-group">
                                        <label for="address">Address <span class="text-red optional-mandatory-icon">*</span></label>
                                        <div class="eb-input-holder">
                                            <input type="text" id="address" name="address_line_1" class="eb-form-control" maxlength="70">
                                            <span class="error" id="addressError"></span>
                                        </div>
                                    </div>
                                </div>
                    
                                <div class="eb-col-6 group-address">
                                    <div class="eb-form-group">
                                        <label for="country">Country <span class="text-red optional-mandatory-icon">*</span></label>
                                        <div class="eb-select-picker-holder">
                                            <div class="select2-main-wrap">
                                                <select class="select2Picker" id="country" name="country">
                                                  <option value="">Select a country</option>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                                    
                                <div class="eb-col-6 group-address">
                                    <div class="eb-form-group">
                                        <label for="state">State <span class="text-red optional-mandatory-icon">*</span></label>
                                        <div class="eb-select-picker-holder">
                                            <div class="select2-main-wrap" id="state_wrap">
                                                <select class="select2Picker" id="state" name="state">
                                                    <option value="">Select a state</option>
                                                </select>
                                            </div>
                                            <div class="eb-form-group" id="stateInput">
                                                <div class="eb-input-holder">
                                                    <input type="text" name="state-input" placeholder="Enter state" class="eb-form-control" style="display:hidden;">
                                                </div>
                                            </div>
                                            
                                        </div>
                                    </div>
                                </div>
                                    
                                <div class="eb-col-6 group-address">
                                    <div class="eb-form-group">
                                        <label for="city">City <span class="text-red optional-mandatory-icon">*</span></label>
                                        <div class="eb-input-holder">
                                            <input type="text" id="city" name="city" placeholder="Enter city" class="eb-form-control">
                                        </div>
                                    </div>
                                </div>
                                    
                                <div class="eb-col-6 group-address">
                                    <div class="eb-form-group">
                                        <label for="postcode">ZIP/Postal Code <span class="text-red optional-mandatory-icon">*</span></label>
                                        <div class="eb-input-holder">
                                            <input type="text" id="postcode" name="postcode" placeholder="Enter ZIP/Postal Code" class="eb-form-control">
                                        </div>
                                    </div>
                                </div>
                            </div>
    
                            <div id="buyer_editor_form_render_wrapper">
                              <div id="buyer_editor_form" class="eb-checkout-formeo-editor-render eb-formeo-controls"></div>
                            </div>
                        </form>
                    </div>
    
                    <div class="eb-checkout-left-attendee-form-content" id="each-attendee-form">
                        <div class="eb-attendee-title">
                            <h3>Attendee Details</h3>
                        </div>
                        <div class="eb-checkout-left-form-content eb-formeo-controls">
                            <form id="attendeeInfo_form" enctype="multipart/form-data">
                            
                            </form>
                        </div>
                    </div>
                </div>
                
                
                <!--Right sidebar-->
                <div class="eb-checkout-right-sidebar-wrap">
                    <div class="eb-summery-toggle-btn">
                        <button id="eb-toggle-checkout-summery" class="eb-btn">
                            <i class="ebi-icon-down-angle"></i> <span id="showMore">Show More</span>
                        </button>
                    </div>
                    <div class="eb-checkout-summery-wrap" id="eb-checkout-summery-box">
                        <div class="eb-checkout-sidebar-head">
                            <div class="eb-sidebar-event-thumb">
                                <img id="summary-event-image" alt="Event thumb">
                            </div>
                            <div class="eb-sidebar-event-data">
                                <h4 id="summary-event-name"></h4>
                                <div class="eb-sidebar-event-date-time" id="summary-event-date"></div>
                                <div class="eb-sidebar-event-location" id="summary-event-location"></div>
                            </div>
                        </div>
                        
                        <div class="eb-checkout-sidebar-order-summery">
                            <h4>Order Summary</h4>
                            <div class="eb-order-summery-table-wrap">
                                <table id="order-summary-ticket-table">
                                    
                                </table>
                            </div>
                            
                            <div class="eb-order-summery-total-wrap">
                                <div class="total-left">Total</div>
                                <div class="total-price" id="total-price"></div>
                            </div>
                        </div>
                        
                        <!-- Coupon -->
                        <div id="applyCouponFormWrapper">
                            <div class="eb-coupon-checkbox-wrap">
                                <label class="eb-checkbox-radio">
                                    <span>I have a coupon code</span>
                                    <input type="checkbox" name="has_coupon" value="1" id="has_coupon" autocomplete="off">     
                                    <div class="b-input"></div>
                                </label>
                            </div>
                        
                            <!-- Coupon Fields (Hidden by Default) -->
                            <div class="eb-form-group eb-form-group-coupon" style="display: none;">
                                <div class="eb-coupon-label-wrap eb-coupon-label-wrap-coupon">
                                    <label>Coupon Code <span class="text-red">*</span></label>
                                    <span class="eb-btn eb-coupon-remove-btn eb-coupon-remove-btn-coupon" style="display: none;">Remove</span>
                                </div>
                                <div class="eb-input-holder eb-input-holder-coupon">
                                    <div class="eb-input-group-wrap eb-input-group-wrap-coupon">
                                        <input type="input" name="code" required="required" class="eb-form-control cuopon-input cuopon-input-coupon" placeholder="Enter coupon code" autocomplete="off" id="coupon-code" value=""> 
                                        <div class="eb-coupon-btn-wrap eb-coupon-btn-wrap-coupon">
                                            <input type="button" id="apply_coupon" class="eb-btn-primary eb-coupon-btn eb-coupon-btn-coupon" value="Apply">
                                        </div>
                                    </div>
                                    <span class="error-msg error-msg-coupon" id="apply_coupon_error"></span>
                                    <span class="success-msg success-msg-coupon" style="display: none;"></span>
                                </div>
                            </div>    
                        </div>
        
                        <div class="eb-event-checkout-restriction eb-event-checkout-terms" id="restriction-container">
                            <label class="eb-checkbox-radio">
                                <span id="restriction-text"></span>
                                <input type="checkbox" id="restriction-checkbox" value="1">     
                                <div class="b-input"></div>
                            </label>
                        </div>
                        
                        
                        <div class="eb-event-checkout-terms" id="termsContainer">
                            <label class="eb-checkbox-radio">
                                <span> I've read and agreed to the event's <a href="#" id="terms-link">Terms and Conditions</a></span>
                                <input type="checkbox" id="termsCheckbox" value="1">     
                                <div class="b-input"></div>
                            </label>
                        </div>
                    </div>
                    
                    
                    <div class="eb-event-total-price-sm" id="total-price-sm"></div>
                    
                    <div class="eb-checkout-btn-wrap">
                        <button id="eb-book-btn" class="eb-book-btn" type="submit">Proceed to Payment</button>
                    </div>
                </div>
                <!--End Right sidebar-->
                
            </div>
          </div>
      </div>
    `);

    // try {
    //     let autocomplete;
    //     window.initAutocomplete = function () {
    //         autocomplete = new google.maps.places.Autocomplete(
    //             document.getElementById('address'), { types: ['geocode'] }
    //         );
    //     }
    // } catch (err) { }

    // Order form get API
    async function fetchOrderFormData(link) {
        try {
            const response = await $.ajax({
                url: link,
                type: 'GET',
            });
            return response;
        } catch (error) {
            console.error('Error:', error);
            throw error;
        }
    }

    const createBuyerAdditionalDetails = (obj) => {
        const additionalDetails = { attributes: [] };

        for (let key in obj) {
            if (obj.hasOwnProperty(key) && key.startsWith('f-')) {
                let value = obj[key];
                additionalDetails.attributes.push({
                    name: key,
                    value: value
                });
            }
        }

        return additionalDetails;
    };

    const createAttendeeAdditionalDetails = (payload) => {
        let result = {};

        for (let key in payload) {
            let match = key.match(/\[(\d+)\]/);
            let index = match ? parseInt(match[1]) : 0;
            let cleanKey = key.replace(/\[\d*\]|\[\]/g, '');

            if (!result[index]) {
                result[index] = {};
            }

            if (result[index][cleanKey]) {
                result[index][cleanKey] += `,${payload[key]}`;
            } else {
                result[index][cleanKey] = payload[key];
            }
        }


        let addDetails = Object.values(result).map(group => {
            let attendeeStateInputValue = null;
            let hasAttendeeState = false;

            let processedEntries = Object.entries(group).map(([key, value]) => {
                if (key === 'attendee_state' && value?.length) {
                    hasAttendeeState = true;
                }
                if (key === 'attendee_state_input' && value?.length) {
                    attendeeStateInputValue = value;
                }
                return { key, value }
            });



            if (!hasAttendeeState && attendeeStateInputValue) {
                let replaced = false;
                processedEntries = processedEntries.map(entry => {
                    if (entry.key === 'attendee_state') {
                        replaced = true;
                        return { key: 'attendee_state', value: attendeeStateInputValue };
                    }
                    return entry;
                });
                if (!replaced) {
                    processedEntries.push({ key: 'attendee_state', value: attendeeStateInputValue });
                }
            }

            return processedEntries;
        });




        return groupAttendeeByTicketSlug(addDetails);
    };

    const groupAttendeeByTicketSlug = (data) => {
        let groupedResult = {};

        data.forEach((group) => {
            let slugEntry = group.find(entry => entry.key === "formeo_ticket_slug");

            if (slugEntry) {
                let slugValue = slugEntry.value;

                if (!groupedResult[slugValue]) {
                    groupedResult[slugValue] = [];
                }

                let attributes = group.map(({ key, value }) => {
                    if (key !== "formeo_ticket_slug") {
                        return { name: key, value };
                    }
                }).filter(Boolean);

                groupedResult[slugValue].push({ ticket_slug: slugValue, attributes });
            }
        });

        return Object.values(groupedResult);
    };

    const addAddDetailsToAttendeeTickets = (lineItems, groupedAttributes) => {
        return lineItems.map(ticket => {
            // Find the group corresponding to the current ticket's slug
            const slugGroup = groupedAttributes.find(group => group[0].ticket_slug === ticket.formeo_ticket_slug);

            if (slugGroup) {
                // Prepare new additional details
                const newAttributes = slugGroup.map(group => ({
                    attributes: group?.attributes
                }));

                // Ensure ticket.attributes exists
                if (!ticket.attributes) {
                    ticket.attributes = { additional_details: [] };
                }

                // Concatenate existing additional_details with new attributes
                ticket.attributes.additional_details = [
                    ...(ticket.attributes.additional_details || []),
                    ...newAttributes
                ];
            }

            // Return the updated ticket object
            return ticket;
        });
    };



    const createFormData = (obj, formData = new FormData(), parentKey = "") => {
        for (let key in obj) {
            if (obj.hasOwnProperty(key)) {
                const value = obj[key];
                const newKey = parentKey ? `${parentKey}[${key}]` : key;

                if (value instanceof File || value instanceof Blob) {
                    formData.append(newKey, value);
                } else if (Array.isArray(value)) {
                    value.forEach((item, index) => {
                        createFormData(item, formData, `${newKey}[${index}]`);
                    });
                } else if (typeof value === "object" && value !== null) {
                    createFormData(value, formData, newKey);
                } else {
                    formData.append(newKey, value);
                }
            }
        }
        return formData;
    };


    const generateOrderPayload = (buyerFormData, attendeeFormData, coupon = {}) => {

        const additionalDetails = createBuyerAdditionalDetails(buyerFormData);
        if (Object.keys(attendeeFormData ?? {})?.length > 0) {
            const attendeeAdditionalDetails = createAttendeeAdditionalDetails(attendeeFormData);
            const lineItems = ticketData?.line_items;
            const lineItemsWithAddDetails = addAddDetailsToAttendeeTickets(lineItems, attendeeAdditionalDetails);
            ticketData.line_items = lineItemsWithAddDetails;
        }
        let couponCode = $("#coupon-code").val().trim();


        const orderPayload = {
            "order": {
                "customer": {
                    "first_name": buyerFormData?.first_name,
                    "last_name": buyerFormData?.last_name,
                    "email": buyerFormData?.email,
                    "phone": buyerFormData?.phone ?? '',
                    "billing_address": {
                        "address_line1": buyerFormData?.address_line_1,
                        "address_line2": buyerFormData?.address_line_1,
                        "country": buyerFormData?.country,
                        "state": buyerFormData?.state,
                        "city": buyerFormData?.city,
                        "post_code": buyerFormData?.postcode,
                        "company_name": buyerFormData?.company,
                    },
                    "shipping_address": {
                        "address_line1": buyerFormData?.address_line_1,
                        "address_line2": buyerFormData?.address_line_1,
                        "country": buyerFormData?.country,
                        "state": buyerFormData?.state,
                        "city": buyerFormData?.city,
                        "post_code": buyerFormData?.postcode
                    }
                },
                ...{ accept_terms_and_condition: $("#termsCheckbox").prop("checked") },
                ...(additionalDetails?.attributes?.length > 0 ? { 'additional_details': additionalDetails } : {}),
                ...ticketData,
                ...(isCouponApplied ? {
                    'coupons': [
                        {
                            code: couponCode
                        }
                    ]
                } : {})
            }
        };

        const formDataPayload = createFormData(orderPayload);

        console.log({ orderPayload });

        return formDataPayload;
    }

    const renderOrderForm = (formeoDataJson, hasFormeoJson) => {
    
        const formeoBuyersData = EbFormeo.getEditorJsonByCollectionType(formeoDataJson, 'from-buyers-only');
        const formeoAttendeesData = EbFormeo.getEditorJsonByCollectionType(formeoDataJson, 'from-each-attendees');

        if (hasFormeoJson && Object.entries(formeoAttendeesData?.fields ?? {}).length <= 0) {
            $('#each-attendee-form').hide();
        }

        if (Object.entries(formeoBuyersData?.fields ?? {}).length > 0 && hasFormeoJson) {
            var buyerRenderer = new FormeoRenderer({
                renderContainer: '#buyer_editor_form',
            });
            buyerRenderer.render(formeoBuyersData);
        }

        if (Object.entries(formeoAttendeesData?.fields ?? {}).length > 0 || (!hasFormeoJson && Object.entries(formeoDataJson).length > 0)) {
            // Ticket list
            const lineItems = ticketData?.line_items ?? [];

            const attendeeFormList = Helpers.getAttendeeFormList(eventDetails?.tickets?.levels ?? [], lineItems);


            // Loop through attendees and append forms
            attendeeFormList.forEach((attendee, index) => {
                $("#attendeeInfo_form").append(window.singleAttendeeFormComponent(formeoDataJson, attendee, index, EbFormeo));
                Helpers.initializeSelect2Picker();
                handleCountryState('attendee_state_' + index, 'attendee_state_' + index + '_input', 'attendee_country_' + index);
                handleCountryState('null', 'null', `attendee_nationality_${index}`);
                if (hasFormeoJson) {
                    EbFormeo.renderAttendeeBuilderFields(formeoDataJson, true);
                }

                $(".date_of_birth").datepicker({
                    changeMonth: true,
                    changeYear: true
                });
                $('.select2picker2').select2();
            });
        }

        EbFormeo.attendeeFormeoFormRequiredActionsAfterFormRender();

    }

    const updateEventInfo = () => {
        const venue = Helpers.getEventVenue(eventDetails);

        let venueAddress = '';

        if (venue?.length > 0 || Object?.entries(venue)?.length > 0) {
            const addressParts = [
                venue?.name,
                venue?.address?.address_line1,
                venue?.address?.city,
                venue?.address?.state,
                venue?.address?.post_code,
                venue?.address?.country
            ];
            venueAddress = addressParts.filter(part => part).join(', ');
        }

        $('#summary-event-name').text(`${eventDetails?.display_name}`);
        $('#summary-event-location').html(`${venueAddress}`);
        $('#summary-event-date').text(`${Helpers.getEventStartForCheckoutSummary(eventDetails, ticketData)}`);
        $('#summary-event-image').attr('src', Helpers.getEventBannerImage(eventDetails));

    }


    const initialiseOrderSummary = (couponAmount, newSubtotal) => {
        const lineItems = ticketData?.line_items ?? [];

        const orderTicketList = Helpers.getOrderTicketDetails(lineItems, eventDetails?.tickets?.levels, eventDetails?.merchandise?.products ?? {}, ticketData);

        const orderTotalAmount = Helpers.orderTicketTotalPriceFromFormattedList(orderTicketList);

        let table = $('#order-summary-ticket-table');


        // Clear existing table rows, except for total rows
        table.find('tr').not('tr:last-child').remove();

        // Loop through the data and create rows dynamically
        orderTicketList.forEach(item => {
            let row = `<tr>
                            <td>${item.quantity * Number(item?.quantityIncluded ?? 1)} x ${item.ticketName}</td>
                            <td>${Constants.SupportedCurrencySigns[eventDetails?.currency]}${(item.quantity * item.price).toFixed(2)} ${eventDetails?.currency}</td>
                        </tr>`;
            table.append(row);

        });

        $(".coupon-applied-row").remove();
        if (couponAmount) {
            // Append coupon discount row
            table.append(`<tr class="coupon-applied-row">
                                <td>Coupon Applied</td>
                                <td>-${Constants.SupportedCurrencySigns[eventDetails?.currency]}${couponAmount.toFixed(2)} ${eventDetails?.currency}</td>
                            </tr>`);

        }

        // Append Sub Total and Total rows
        $('.eb-summery-sub-total-row').remove();
        table.append(`<tr class="eb-summery-sub-total-row">
                        <td>Sub Total</td>
                        <td>${Constants.SupportedCurrencySigns[eventDetails?.currency]}${newSubtotal ?? orderTotalAmount.toFixed(2)} ${eventDetails?.currency}</td>
                      </tr>`);


        $("#total-price").text(`${Constants.SupportedCurrencySigns[eventDetails?.currency]}${newSubtotal ?? orderTotalAmount.toFixed(2)} ${eventDetails?.currency}`);
        $("#total-price-sm").text(`${Constants.SupportedCurrencySigns[eventDetails?.currency]}${newSubtotal ?? orderTotalAmount.toFixed(2)} ${eventDetails?.currency}`);
        if (newSubtotal != null) {
            if (newSubtotal == 0) {
                $('#eb-book-btn').text('Confirm Order');
            } else {
                $('#eb-book-btn').text('Proceed to Payment');
            }
        } else {
            if (orderTotalAmount == 0) {
                $('#eb-book-btn').text('Confirm Order');
            } else {
                $('#eb-book-btn').text('Proceed to Payment');
            }
        }
    }

    const handleCountryState = (stateId = 'state', stateInputId = 'stateInput', countryId = 'country') => {
        let countries = Country.getAllCountries();

        const updateStateFields = (selectedCountry) => {
            let countryCode = countries.filter((country) => country?.name == selectedCountry)?.[0]?.isoCode ?? null;
            let states = countryCode ? State.getStatesOfCountry(countryCode) : [];

            if (states.length > 0) {
                $(`#${stateId}`).empty().append($('<option>', { value: '', text: 'Select a state' }));
                states.forEach(state => {
                    $(`#${stateId}`).append($('<option>', { value: state?.name, text: state?.name }));
                });
                $(`#${stateId}_wrap`).show();
                $(`#${stateInputId}`).hide();
            } else {
                $(`#${stateId}_wrap`).hide();
                $(`#${stateInputId}`).show();
            }
        }

        $.each(countries, function (index) {
            $(`#${countryId}`).append($('<option>', { value: countries[index]?.name, text: countries[index]?.name, selected: countries[index]?.name === "Australia" }));
        });

        $(`#${stateId}`).empty().append($('<option>', { value: '', text: 'Select a state' }));

        $(`#${countryId}`).change(function () {
            let selectedCountry = $(this).val() ?? "Australia";
            console.log('change country ' + selectedCountry);
            updateStateFields(selectedCountry);
        });

        setTimeout(function () {
            $(`#${countryId}`).trigger('change');
        }, 0);

    }

    function validateFormeoDate() {
        $.validator.addMethod("date_picker", function (value, element, params) {
            if (!value) {
                return true;
            }

            let regex = /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/;
            let date_format = element.getAttribute("date-format");
            if (date_format === 'mm/dd/yy') {
                regex = /^(0[1-9]|1[0-2])\/((0|[1-2])[0-9]|3[0-1])\/[0-9]{4}$/;
            }
            else if (date_format === 'dd/mm/yy') {
                regex = /^((0|[1-2])[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/[0-9]{4}$/;
            }
            else if (date_format === 'yy/mm/dd') {
                regex = /^[0-9]{4}\/(0[1-9]|1[0-2])\/((0|[1-2])[0-9]|3[0-1])$/;
            }
            else if (date_format === 'mm/yy') {
                regex = /^(0[1-9]|1[0-2])\/[0-9]{4}$/;
            }

            if (regex.test(value)) {
                return true;
            }
            $.validator.messages.date_picker = `Invalid date`;
            return false
        }, $.validator.messages.date_picker);

        $.validator.addClassRules({
            date_picker: {
                date_picker: true
            }
        });
    }

    function checkIfFormeoHasRequiredField($selector) {
        var hasRequired = false;
        /*$selector.find(".f-field-group[required='true']").each(function (index, element) {
            hasRequired = true;
        });*/
        $selector.find(".f-field-group").each(function (index, element) {
            var $element = $(element).children();
            $element.each(function (index, elem) {
                var $elem = $(elem);

                //TODO: order form validation issue fix
                //if ($elem.hasAttr('required')) {
                if ($elem?.hasAttr('required') && $elem?.val() === '' && typeof $elem?.attr('name') !== "undefined") {
                    hasRequired = true;
                }
            });
        });
        return hasRequired;
    }

    function formeoRadioCheckboxValidation($selector) {
        $selector.find(".f-field-group[required='true']").each(function (index, element) {
            var $element = $(element);
            var radio = $element.find("input[type='radio']").last();
            if (radio.length > 0) {
                radio.rules('add', {
                    required: true
                });
            }

            var checkbox = $element.find("input[type='checkbox']").last();
            if (checkbox.length > 0) {
                checkbox.rules('add', {
                    required: true
                });
            }
        });
    }

    function validateAttandeeData() {

        var error = '<small class="error-msg">This field is required.</small>';
        var isValid = true;
        var hasRequiredField = false;

        validateFormeoDate();

        $("#updatebilling_form").validate({
            errorPlacement: function (error, element) {
                if (element.attr('type') === 'radio' && element.closest(".f-field-group") && element.closest(".f-field-group").length > 0) {
                    error.insertAfter(element.closest(".f-field-group"));
                } else if (element.attr('type') === 'checkbox' && element.closest(".f-field-group") && element.closest(".f-field-group").length > 0) {
                    error.insertAfter(element.closest(".f-field-group"));
                } else {
                    error.insertAfter(element);
                }
            }
        });
        if (!$("#updatebilling_form").valid()) {
            isValid = false;
        }

        var $updatebilling_form = $("#updatebilling_form");
        $updatebilling_form.validate({
            errorPlacement: function (error, element) {
                if (element.attr('type') === 'radio' && element.closest(".f-field-group") && element.closest(".f-field-group").length > 0) {
                    error.insertAfter(element.closest(".f-field-group"));
                } else if (element.attr('type') === 'checkbox' && element.closest(".f-field-group") && element.closest(".f-field-group").length > 0) {
                    error.insertAfter(element.closest(".f-field-group"));
                } else {
                    error.insertAfter(element);
                }
            }
        });

        var $attendee_info_form = $("#attendeeInfo_form");
        $attendee_info_form.validate({
            errorPlacement: function (error, element) {
                if (element.attr('type') === 'radio' && element.closest(".f-field-group") && element.closest(".f-field-group").length > 0) {
                    error.insertAfter(element.closest(".f-field-group"));
                } else if (element.attr('type') === 'checkbox' && element.closest(".f-field-group") && element.closest(".f-field-group").length > 0) {
                    error.insertAfter(element.closest(".f-field-group"));
                } else if (element.hasClass("select2-hidden-accessible")) {
                    // Find the Select2 container and append error after it
                    error.insertAfter(element.next(".select2-container"));
                }
                else {
                    error.insertAfter(element);
                }
            }
        });
        formeoRadioCheckboxValidation($updatebilling_form);
        formeoRadioCheckboxValidation($attendee_info_form);

        const checkBillingFormValidation = $("#updatebilling_form").valid();
        const checkAttendeeFormValidation = $("#attendeeInfo_form").valid();

        if (!checkBillingFormValidation || !checkAttendeeFormValidation) {
            isValid = false;
        }
        // var formeoRequiredField = checkIfFormeoHasRequiredField($attendee_info_form);

        return [isValid, hasRequiredField];
    }

    const handleCouponSection = () => {

        if (!eventDetails?.settings?.coupon?.enabled) {
            $('#applyCouponFormWrapper').hide();
            return;
        }

        $(".eb-form-group-coupon").hide();
        $(".eb-coupon-remove-btn-coupon").hide();

        // Show/hide coupon input when checkbox is clicked
        $("#has_coupon").change(function () {
            if ($(this).is(":checked")) {
                $(".eb-form-group-coupon").slideDown(); // Show coupon input fields
            } else {
                if (!$(".eb-coupon-remove-btn-coupon").is(":visible")) {
                    $(".eb-form-group-coupon").slideUp();
                    resetCouponForm();
                }
            }
        });

        // Apply coupon button click
        $("#apply_coupon").click(function () {
            let couponCode = $("#coupon-code").val().trim();

            if (couponCode === "") {
                $("#apply_coupon_error").text("Please enter a coupon code.");
                return;
            }

            $("#apply_coupon_error").text("");

            const orderPayload = {
                order: {
                    customer: {
                        email: ''
                    },
                    ...ticketData,
                    has_coupon: true,
                    coupons: [
                        {
                            code: couponCode
                        }
                    ]

                }
            };

            $.ajax({
                url: Config.EB_API_URL + "/orders",
                type: "POST",
                headers: {
                    'x-api-key': Config.EB_API_KEY
                },
                data: orderPayload,
                beforeSend: function () {
                    $("#apply_coupon").val("Applying...").prop("disabled", true);
                },
                success: function (response) {
                    console.log({ response });
                    if (response?.result?.status === "success") {
                        $("#apply_coupon_error").text("");
                        isCouponApplied = true;
                        let orderSummary = response?.order?.tmp_order.summary ?? {};
                        let couponAmount = orderSummary?.coupons?.amount;
                        let newSubtotal = orderSummary?.subtotal - couponAmount;

                        initialiseOrderSummary(couponAmount, newSubtotal);

                        $(".success-msg-coupon").text("Coupon applied successfully!").show();
                        $(".eb-coupon-remove-btn-coupon").show();
                        $(".cuopon-input-coupon").prop("disabled", true);
                        $("#apply_coupon").prop("disabled", true);
                        $(".eb-coupon-checkbox-wrap").hide();
                    } else {
                        $("#apply_coupon").prop("disabled", false);
                    }
                },
                error: function (response) {
                   
                    const error = response?.responseJSON?.message?.order?.coupons;
                    const error2 = response?.responseJSON?.message?.order?.coupon;
                    const errorMessage = error ? error?.[0]?.code ?? 'Invalid Coupon' : error2 ?
                                             error2?.[0]?.code ?? 'Invalid coupon': 'Invalid Coupon';
                    
                    $("#apply_coupon_error").text(errorMessage);
                    $("#apply_coupon").prop("disabled", false);
                },
                complete: () => {
                    $("#apply_coupon").val("Apply");
                }
            });
        });

        // Remove coupon event
        $(".eb-coupon-remove-btn-coupon").click(function () {
            isCouponApplied = false;
            initialiseOrderSummary();
            resetCouponForm();
            $("#has_coupon").prop("checked", false);
            $(".eb-coupon-checkbox-wrap").show();
            $(".eb-form-group-coupon").slideUp();
        });

        function resetCouponForm() {
            $("#coupon-code").val("").prop("disabled", false);
            $("#apply_coupon").val("Apply").prop("disabled", false);
            $(".success-msg-coupon").hide();
            $(".eb-coupon-remove-btn-coupon").hide();
            $("#apply_coupon_error").text("");
        }
    }

    const isTermsAccepted = () => {

        let termsCheckbox = $("#termsCheckbox");

        if (!termsCheckbox.prop("checked")) {
            return false;
        }

        return true;
    }

    const isAgeRestrictionAccepted = () => {

        let termsCheckbox = $("#restriction-checkbox");

        if (!termsCheckbox.prop("checked")) {
            return false;
        }

        return true;
    }

    const handleTermsConditionSection = () => {
        if (eventDetails?.settings?.terms_and_condition?.enabled) {
            const termsType = eventDetails?.settings?.terms_and_condition?.type;
            const content = eventDetails?.settings?.terms_and_condition?.content;
            if (termsType !== 'text') {
                let formatContent = termsType == 'url' ?
                    content :
                    termsType == 'file_path' ?
                        Config.EB_BASE_URL + `/${content}` :
                        '';


                if (!formatContent.startsWith('https://')) {
                    formatContent = 'https://' + formatContent;
                }
                $('#terms-link').click(() => {
                    console.log({ formatContent });
                    const link = document.createElement('a');
                    link.href = formatContent;
                    link.target = '_blank';
                    link.click();
                });

            } else {
                $('#terms-text').html(content);
                $('#terms-link').click(() => {
                    console.log('conte', { content });
                    Helpers.openModal('#terms-modal');
                });
                $('#terms-accept').click(() => {
                    $("#termsCheckbox").prop('checked', true);
                    Helpers.closeModal('#terms-modal');
                });
            }

            $('#termsContainer').show();
            $('.terms-modal-close').click(() => {
                Helpers.closeModal('#terms-modal');
            });
        } else {
            $('#termsContainer').hide();
        }

    }

    const handleAgeRestrictionSection = () => {

        const checkTicketAgeRestriction = () => {
            const tickets = eventDetails?.tickets?.levels;
            const products = ticketData?.line_items;

            return tickets.some(t => t.settings?.restrictions?.some(r => r.type === "age" && r.enabled) &&
                products.some(p => p.product === t.uuid));;
        }

        let isEnabledAgeRestriction = false;
        let restrictionLevel = '';
        let condition = {};
        eventDetails?.settings?.restrictions?.map((val) => {
            if (val.type == 'age' && val?.enabled) {
                isEnabledAgeRestriction = true;
                restrictionLevel = val?.level;
                condition = val?.condition;

            }
        });

        console.log({ isEnabledAgeRestriction }, { restrictionLevel });
        if (isEnabledAgeRestriction) {
            let restrictionText = '';
            if (restrictionLevel == 'ticket') {
                if (checkTicketAgeRestriction()) {
                    restrictionText = 'Yes, I’m old enough to book these tickets. *';
                }
            } else {
                restrictionText = `Yes, all the attendees are ${condition?.max} years or above *`;
            }

            if (restrictionText.length > 0) {
                hasAgeRestriction = true;
                $('#restriction-container').show();
                $('#restriction-text').text(restrictionText);
            } else {
                hasAgeRestriction = false;
                $('#restriction-container').hide();
            }

        } else {
            $('#restriction-container').hide();
        }
    }


    function handleCollectAdditionalInfoFromBuyer(){
        const attributes =  eventDetails?.settings?.collect_additional_info_from_buyer?.attributes;

        const addressObj = attributes?.find(item => item.name === "collect_address");
        const addressEnabled = addressObj?.enabled ?? false;
        const addressMandatory = addressObj?.mandatory ?? false;
        const companyObj = attributes?.find(item => item.name === "collect_company_name");
        const companyNameEnabled = companyObj?.enabled ?? false;
        const companyNameRequired = companyObj?.mandatory ?? false;
        console.log({addressObj}, {companyObj});
        if(companyNameEnabled){
            $('.group-company').show();
            if(companyNameRequired){
                $('.company-optional-mandatory-icon').show();
                $('#company').attr('required', true);
            }else{
                $('.company-optional-mandatory-icon').hide();
                $('#company').removeAttr('required');
            }
        }else{
            $('.group-company').hide();
        }
        console.log({addressObj}, {addressEnabled});
        if(!addressEnabled){
            $('.group-address').hide();
        }else{
            $('.group-address').show();

            if (addressMandatory) {
                $('.optional-mandatory-icon').show();
                $('#address').attr('required', true);
                $('#city').attr('required', true);
                $('#postcode').attr('required', true);
        
                // Handle state (select or input version)
                $('#state').attr('required', true);
                $('input[name="state-input"]').attr('required', true);
            } else {
                $('.optional-mandatory-icon').hide()
                $('#address').removeAttr('required');
                $('#city').removeAttr('required');
                $('#postcode').removeAttr('required');
                $('#state').removeAttr('required');
                $('input[name="state-input"]').removeAttr('required');
            }
        }

        $('#state').on('change', function () {
            const value = $(this).val();
        
            if (value) {
                const $form = $("#attendeeInfo_form");
        
                $(this).removeClass('error');
                $(this).siblings('label.error').remove();
                $(this).next('.select2').removeClass('error');
                // Re-validate the field
                $form.validate().element(this);
            }
        });
        
    }



    $(function () {

        console.log('Ready Checkout ======');

        // Fetch order form and get order form data
        const orderFormLink = Helpers.getOrderFormLink(eventDetails);
        if (orderFormLink?.enable) {
            const formLink = orderFormLink?.link;
            fetchOrderFormData(formLink).then((response) => {
                console.log('Order form===', { response });
                if (Object.entries(response.result?.form_value)?.length > 0) {
                    const formeoData = response.result?.form_value ?? {}
                    if (formeoData) {
                        renderOrderForm(formeoData, response.result?.has_attendee_json);
                    } else {
                        $('#each-attendee-form').hide();
                    }
                }

            }).catch((err) => {
                console.log('Order form error===', { err });
                $('#each-attendee-form').hide();
            });
        } else {
            $('#each-attendee-form').hide();
        }

        // Country/State/City handle
        handleCountryState();

        Helpers.initializeSelect2Picker();

        // Order details right side initialise
        initialiseOrderSummary();
        updateEventInfo();

        // Coupon codes handle
        handleCouponSection();
        // Terms and conditions
        handleTermsConditionSection();
        // Age restriction
        handleAgeRestrictionSection();

        // collect_additional_info_from_buyer
        handleCollectAdditionalInfoFromBuyer();




        document.getElementById("eb-book-btn").addEventListener("click", function () {

            if (eventDetails?.settings?.terms_and_condition?.enabled) {
                const termsAccepted = isTermsAccepted();
                if (!termsAccepted) {
                    alert("You must agree to the Terms and Conditions.");
                    return;
                }

            }


            if (hasAgeRestriction) {
                const termsAccepted = isAgeRestrictionAccepted();
                if (!termsAccepted) {
                    alert("The organiser requires all the attendees to be old enough to book these tickets. Select the checkbox if you pass the age restrictions.");
                    return;
                }
            }

            var validationMap = validateAttandeeData();
            var isValid = validationMap[0];
            if (!isValid) {
                alert('Please fill up all required fields.');
                return;
            }

            // Form validate
            const formElement = document.getElementById("updatebilling_form");
            const formElementAttendee = document.getElementById("attendeeInfo_form");

            const formData = new FormData(formElement);
            const dataBuyer = {};

            formData.forEach((value, key) => {
                key = key.replace(/\[]/g, '')
                if (dataBuyer[key]) {
                    dataBuyer[key] = dataBuyer[key] + ',' + value;
                } else {
                    dataBuyer[key] = value;
                }
            });


            const formDataAttendee = new FormData(formElementAttendee);
            EbFormeo.appendFormeoAttendeePhoneFieldsValue(formDataAttendee);
            const dataAttendee = {};


            formDataAttendee.forEach((value, key) => {
                key = key.replace(/\[]/g, '')
                if (dataAttendee[key]) {
                    dataAttendee[key] = dataAttendee[key] + ',' + value;
                } else {
                    dataAttendee[key] = value;
                }

            });

            const formDataPayload = generateOrderPayload(dataBuyer, dataAttendee);
            orderPayloadCallback?.(formDataPayload);
        });

        document.getElementById("eb-toggle-checkout-summery").addEventListener("click", function() {
            let btnToggle = document.getElementById("eb-toggle-checkout-summery");
            let showMoreTxt = document.getElementById("showMore");

            document.getElementById("eb-checkout-summery-box").classList.toggle("active");
            this.classList.toggle("active");

            if (btnToggle.classList.contains("active")) {
                showMoreTxt.textContent = "Show Less";
            } else {
                showMoreTxt.textContent = "Show More";
            }
        });


    });

    $container.append($content);

    return $container[0];
}





export default Checkout;
