import React, { useState, useRef, useEffect } from 'react';
import Datetime from 'react-datetime';
import 'react-datetime/css/react-datetime.css';
import { useNavigate } from "react-router-dom";
import MhInput from '../../../common/fields/MhInput';
import MhSelect from '../../../common/fields/MhSelect';
import MhCheckbox from '../../../common/fields/MhCheckbox';
import MhSwitcher from '../../../common/fields/MhSwitcher';
import TimezoneList from '../../../common/fields/TimezoneList';
import MhDurationSelect from '../../../common/fields/MhDurationSelect';
import { generateRandomRoom } from '../../RandomRoomGenerator';
import MhTextArea from '../../../common/fields/MhTextArea';
import Editor from 'react-simple-wysiwyg';
import { isProActive } from '../../../../Helpers';
import { toast } from 'react-toastify';
const { __ } = wp.i18n;
import ImageUploader from '../../../common/ImageUploader';
import moment from 'moment-timezone';
import DatePicker from 'react-datepicker';
import 'react-datetime/css/react-datetime.css';
import { langString } from '../../../../Helpers';
import MhCreatableSelect from '../../../common/fields/MhCreatableSelect';

 const WebexForm = ({ selectedPlatform }) => {
	const [errorMessage, setErrorMessage] = useState('');
	const [isSaving, setIsSaving] = useState(false);
	const navigate = useNavigate();
	const hiddenSubmitRef = useRef(null);
	var mhub_webex_settings = mhubMeetingsData.mhub_webex_settings;
	const defaultTimezone = mhub_webex_settings ? mhub_webex_settings.meeting_timezone : mhubMeetingsData.mhub_timezone;

	const [meetingDescription, setMeetingDescription] = useState('');
	const [imageUrl, setImageUrl] = useState('');
	const [imageId, setImageID] = useState('');

	function handleMeetingDescription(e) {
		setMeetingDescription(e.target.value);
	}

	//Lock data
	const lockOptions = [
		{ value: '0', label: langString('0') },
		{ value: '5', label: langString('5') },
		{ value: '10', label: langString('10') },
		{ value: '15', label: langString('15') },
		{ value: '20', label: langString('20') },
	];

	// Join Before Host minute options
	const jbhMinuteOptions = [
		{ value: 0, label: langString('0') },
		{ value: 5, label: langString('5') },
		{ value: 10, label: langString('10') },
		{ value: 15, label: langString('15') },
		{ value: 20, label: langString('20') },
		{ value: 30, label: langString('30') },
		{ value: 60, label: langString('60') },
	];

	const [formData, setFormData] = useState({
		title: generateRandomRoom(10),
		startDateTime: moment.tz(new Date().setMinutes(new Date().getMinutes() + 10), defaultTimezone).format(),
		meeting_type: 'meeting',
		join_before_host: false,
		password: mhubMeetingsData.mhub_password,
		meeting_timezone: mhubMeetingsData.mhub_timezone,
		duration_hours: 0,
		duration_minutes: 40,
		hide_sidebar: mhub_webex_settings ? mhub_webex_settings.hide_sidebar : false,
		hide_header_footer: mhub_webex_settings ? mhub_webex_settings.hide_header_footer : false,
		agenda: '',
		auto_record: mhub_webex_settings ? mhub_webex_settings.auto_record : false,
		breakout_sessions: mhub_webex_settings ? mhub_webex_settings.breakout_sessions : false,
		automatic_lock: mhub_webex_settings ? mhub_webex_settings.automatic_lock : false,
		lock_minutes: mhub_webex_settings ? mhub_webex_settings.lock_minutes : 15,
		enable_should_register: mhub_webex_settings ? mhub_webex_settings.enable_should_register : false,
		enable_recurring_meeting: mhub_webex_settings ? mhub_webex_settings.enable_recurring_meeting : false,
		display_time_user_zone: 1,
		// Webinar-specific and invitees
		panelist_password: '',
		enabled_webcast_view: false,
		registration_auto_accept: false,
		registration_max_register_num: 0,
		invitees: [],
		send_invite_emails: false,

		// Attendee controls
		allow_host_to_unmute_participants: false,
		allow_attendee_to_unmute_self: false,
		mute_attendee_upon_entry: false,

		// Live stream
		enabled_live_stream: false,
		live_stream_rtmp_url: '',

		// Space meeting (adhoc)
		adhoc: false,
		room_id: '',

		// Join Before Host minutes and audio
		join_before_host_minutes: 0,
		enable_connect_audio_before_host: false,

		// Send host email
		send_host_email: false,

		// Recurrence builder defaults
		recurrence_option: 1, // 1: Daily, 2: Weekly, 3: Monthly
		end_type: 'never', // 'date' | 'occurrences' | 'never'
		set_number_of_occurrences: 1,
		repeat_day: 1,
		repeat_weekly: 1,
		repeat_monthly: 1,
		repeat_year: 1,
		weekdays: [],
		occurs_on_monthly: 'day', // 'day' | 'weekdays'
		set_month_order: 1, // 1,2,3,4,-1
		set_monthly_weekday: 'MO',
		set_month_day: moment.tz(new Date(), defaultTimezone).date(),



		// Daily occurs selector
		daily_occurs_on: 'day',

	});


	useEffect(() => {
		if (formData.meeting_timezone) {
			setFormData((prev) => ({
				...prev,
				startDateTime: moment.tz(prev.startDateTime, prev.meeting_timezone).tz(formData.meeting_timezone).format(),
			}));
		}
	}, [formData.meeting_timezone]);

	const handleChange = (name, value) => {
		let updatedValue = value;
		
		// Convert only `startDateTime` to the specified timezone
		if (name === 'startDateTime') {
			// Keep the same local time but assign the timezone
			updatedValue = moment.tz(value, formData.meeting_timezone).format();
			// Mark that the user manually edited the start date, so auto-align should not override
			setStartEditedByUser(true);
		}

		setFormData({ ...formData, [name]: updatedValue });
	};

    // Weekday options for weekly/monthly rules
    const weekdayOptions = [
        { label: langString('sunday'), value: 'SU', checked: false },
        { label: langString('monday'), value: 'MO', checked: false },
        { label: langString('tuesday'), value: 'TU', checked: false },
        { label: langString('wednesday'), value: 'WE', checked: false },
        { label: langString('thursday'), value: 'TH', checked: false },
        { label: langString('friday'), value: 'FR', checked: false },
        { label: langString('saturday'), value: 'SA', checked: false },
    ];

    // Recurrence Options (Webex)
    const recurrenceOptions = [
        { value: 1, label: langString('daily') },
        { value: 2, label: langString('weekly') },
        { value: 3, label: langString('monthly') },
    ];

    // set_month_order
    const monthOrder = [
        { value: 1, label: langString('first_week') },
        { value: 2, label: langString('second_week') },
        { value: 3, label: langString('third_week') },
        { value: 4, label: langString('fourth_week') },
        { value: -1, label: langString('last_week') },
    ];

    // set_monthly_weekday
    const monthlyWeekdays = [
        { value: 'MO', label: langString('monday') },
        { value: 'TU', label: langString('tuesday') },
        { value: 'WE', label: langString('wednesday') },
        { value: 'TH', label: langString('thursday') },
        { value: 'FR', label: langString('friday') },
        { value: 'SA', label: langString('saturday') },
        { value: 'SU', label: langString('sunday') },
    ];

    // Repeat monthly interval options
    const repeatMonthly = [];
    for (let i = 1; i <= 12; i++) {
        repeatMonthly.push({ value: i, label: String(i) });
    }

    // Repeat day interval options
    const repeatDay = [];
    for (let i = 1; i <= 31; i++) {
        repeatDay.push({ value: i, label: String(i) });
    }

    // Repeat year interval options
    const repeatYear = [];
    for (let i = 1; i <= 12; i++) {
        repeatYear.push({ value: i, label: String(i) });
    }

    // Number of occurrences options
    const numberOfOccurrences = [];
    for (let i = 1; i <= 20; i++) {
        numberOfOccurrences.push({ value: i, label: String(i) });
    }

    // End type options
    const endType = [
        { value: 'date', label: langString('by_date') },
        { value: 'occurrences', label: langString('by_occurrences') },
        { value: 'never', label: langString('never') },
    ];

    // Occurs monthly options
    const occursMonthly = [
        { value: 'day', label: langString('day') },
        { value: 'weekdays', label: langString('weekdays') },
    ];



    // Daily occurs options
    const dailyOccursOptions = [
        { value: 'day', label: langString('day') },
        { value: 'weekday', label: langString('weekdays') },
    ];

	// Repeat Weekly 
	const repeatWeekly = [];
	for (let i = 1; i <= 12; i++) {
		repeatWeekly.push({ value: String(i), label: String(i) });
	}


    useEffect(() => {
        if (!formData.weekdays || !formData.weekdays.length) {
            setFormData(prev => ({ ...prev, weekdays: weekdayOptions }));
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

    const handleWeekdaysChange = (updatedOptions) => {
        setFormData(prev => ({ ...prev, weekdays: updatedOptions }));
    };

    // Track manual edits and single-shot alignment
    const [startEditedByUser, setStartEditedByUser] = useState(false);
    const [didAutoAlign, setDidAutoAlign] = useState(false);

    // Helper: compute the Nth weekday date for a given month
    const computeNthWeekdayDate = (year, monthIndex, weekdayIndex, setpos) => {
        // monthIndex: 0-11, weekdayIndex: 0 (Sunday) - 6 (Saturday), setpos: 1..4 or -1 for last
        const firstOfMonth = moment.tz({ year, month: monthIndex, day: 1 }, formData.meeting_timezone || mhubMeetingsData.mhub_timezone);
        if (setpos === -1) {
            const lastOfMonth = firstOfMonth.clone().endOf('month');
            const delta = (lastOfMonth.day() - weekdayIndex + 7) % 7;
            return lastOfMonth.clone().subtract(delta, 'days');
        }
        const deltaToWeekday = (weekdayIndex - firstOfMonth.day() + 7) % 7;
        const firstWeekday = firstOfMonth.clone().add(deltaToWeekday, 'days');
        return firstWeekday.clone().add((setpos - 1) * 7, 'days');
    };

    // Auto-align start date once for Monthly Weekdays; never override user edits
    useEffect(() => {
        const option = parseInt(formData.recurrence_option, 10);
        if (option !== 3 || formData.occurs_on_monthly !== 'weekdays') return;
        if (startEditedByUser || didAutoAlign) return;

        const tz = formData.meeting_timezone || mhubMeetingsData.mhub_timezone;
        const start = moment.tz(formData.startDateTime, tz);
        const byDayMap = { 0: 'SU', 1: 'MO', 2: 'TU', 3: 'WE', 4: 'TH', 5: 'FR', 6: 'SA' };
        const invByDayMap = { 'SU': 0, 'MO': 1, 'TU': 2, 'WE': 3, 'TH': 4, 'FR': 5, 'SA': 6 };

        const setpos = parseInt(formData.set_month_order || 1, 10);
        const weekdayToken = formData.set_monthly_weekday || byDayMap[start.day()];
        const weekdayIndex = invByDayMap[weekdayToken] ?? start.day();

        const aligned = computeNthWeekdayDate(start.year(), start.month(), weekdayIndex, setpos);
        aligned.hour(start.hour()).minute(start.minute()).second(start.second()).millisecond(0);
        const alignedIso = aligned.tz(tz).format();
        if (alignedIso !== formData.startDateTime) {
            setFormData(prev => ({ ...prev, startDateTime: alignedIso }));
        }
        setDidAutoAlign(true);
    }, [formData.recurrence_option, formData.occurs_on_monthly, formData.set_month_order, formData.set_monthly_weekday, formData.meeting_timezone]);

    // Reset single-shot alignment when recurrence parameters change
    useEffect(() => {
        setDidAutoAlign(false);
    }, [formData.set_month_order, formData.set_monthly_weekday, formData.occurs_on_monthly, formData.recurrence_option]);

    // Build RFC 2445 RRULE from form state
    const buildRRule = () => {
        const parts = [];
        const option = parseInt(formData.recurrence_option, 10);
        const start = moment.tz(formData.startDateTime, formData.meeting_timezone || mhubMeetingsData.mhub_timezone);
        const byDayMap = {
            0: 'SU', 1: 'MO', 2: 'TU', 3: 'WE', 4: 'TH', 5: 'FR', 6: 'SA'
        };

        if (option === 1) {
            parts.push('FREQ=DAILY');
            parts.push(`INTERVAL=${parseInt(formData.repeat_day || 1, 10)}`);
            if (formData.daily_occurs_on === 'weekday') {
                let selectedDays = (formData.weekdays || []).filter(w => w.checked).map(w => w.value);
                if (!selectedDays.length) {
                    selectedDays = ['MO','TU','WE','TH','FR'];
                }
                parts.push(`BYDAY=${selectedDays.join(',')}`);
            }
        } else if (option === 2) {
            parts.push('FREQ=WEEKLY');
            parts.push(`INTERVAL=${parseInt(formData.repeat_weekly || 1, 10)}`);
            let selectedDays = (formData.weekdays || []).filter(w => w.checked).map(w => w.value);
            if (!selectedDays.length) {
                selectedDays = [byDayMap[start.day()]];
            }
            parts.push(`BYDAY=${selectedDays.join(',')}`);
        } else if (option === 3) {
            parts.push('FREQ=MONTHLY');
            parts.push(`INTERVAL=${parseInt(formData.repeat_monthly || 1, 10)}`);
            if (formData.occurs_on_monthly === 'weekdays') {
                const weekday = formData.set_monthly_weekday || byDayMap[start.day()];
                const setpos = parseInt(formData.set_month_order || 1, 10);
                parts.push(`BYDAY=${weekday}`);
                parts.push(`BYSETPOS=${setpos}`);
            } else {
                const byMonthDay = parseInt(formData.set_month_day || start.date(), 10);
                parts.push(`BYMONTHDAY=${byMonthDay}`);
            }
        }


        if (formData.end_type === 'occurrences') {
            parts.push(`COUNT=${parseInt(formData.set_number_of_occurrences || 1, 10)}`);
        } else if (formData.end_type === 'date' && formData.end_date_time) {
            const tz = formData.meeting_timezone || mhubMeetingsData.mhub_timezone;
            const untilUtc = moment.tz(formData.end_date_time, tz).endOf('day').utc().format('YYYYMMDD[T]HHmmss[Z]');
            parts.push(`UNTIL=${untilUtc}`);
        }
        return parts.join(';');
    };


	const handleSubmit = async (e) => {
		e.preventDefault();

		// Disable the button
		setIsSaving(true);

		try {
			// Make an API request using wp.apiFetch
            const response = await wp.apiFetch({
                path: 'mhub/v1/meetings',
                method: 'POST',
                data: {
                    title: formData.title,
                    selected_platform: selectedPlatform,
                    startDateTime: formData.startDateTime,
					join_before_host: formData.join_before_host,
					join_before_host_minutes: formData.join_before_host ? parseInt(formData.join_before_host_minutes || 0, 10) : 0,
					enable_connect_audio_before_host: formData.join_before_host ? !!formData.enable_connect_audio_before_host : false,
					meeting_timezone: formData.meeting_timezone,
					duration_hours: formData.duration_hours,
					duration_minutes: formData.duration_minutes,
					hide_sidebar: formData.hide_sidebar,
					hide_header_footer: formData.hide_header_footer,
					password: formData.password,
					agenda: formData.agenda,
					auto_record: formData.auto_record,
					breakout_sessions: formData.breakout_sessions,
					automatic_lock: formData.automatic_lock,
					lock_minutes: formData.lock_minutes,
					enable_should_register: formData.enable_should_register,
					enable_recurring_meeting: formData.enable_recurring_meeting,
					meeting_description: JSON.stringify({ content: meetingDescription }),
					image_url: imageUrl,
					image_id: imageId,
					display_time_user_zone: formData.display_time_user_zone,
					meeting_type: formData.meeting_type,
					panelist_password: formData.panelist_password,
					enabled_webcast_view: formData.enabled_webcast_view,
					registration_auto_accept: formData.registration_auto_accept,
					registration_max_register_num: parseInt(formData.registration_max_register_num || 0, 10),
					invitees: formData.invitees,
					send_invite_emails: formData.send_invite_emails,

					// Attendee controls
					allow_host_to_unmute_participants: !!formData.allow_host_to_unmute_participants,
					allow_attendee_to_unmute_self: !!formData.allow_attendee_to_unmute_self,
					mute_attendee_upon_entry: !!formData.mute_attendee_upon_entry,

					// Live stream
					enabled_live_stream: !!formData.enabled_live_stream,
					live_stream_rtmp_url: formData.enabled_live_stream ? (formData.live_stream_rtmp_url || '') : '',

					// Space meeting
					adhoc: !!formData.adhoc,
					room_id: formData.adhoc ? (formData.room_id || '') : '',

					// Top-level send email toggle
					send_host_email: !!formData.send_host_email,

                    // Recurrence
                    enable_recurring_meeting: !!formData.enable_recurring_meeting,
                    recurrence: formData.enable_recurring_meeting ? buildRRule() : '',
                    daily_occurs_on: parseInt(formData.recurrence_option, 10) === 1 ? formData.daily_occurs_on : '',
					recurrence_option: formData.recurrence_option,
					end_type: formData.end_type, 
					set_number_of_occurrences: formData.set_number_of_occurrences,
					repeat_day: formData.repeat_day,
					repeat_weekly: formData.repeat_weekly,
					repeat_monthly: formData.repeat_monthly,
					repeat_year: formData.repeat_year,
					weekdays: formData.weekdays,
					occurs_on_monthly: formData.occurs_on_monthly, 
					set_month_order: formData.set_month_order,
					set_monthly_weekday:formData.set_monthly_weekday,
					set_month_day: formData.set_month_day,

                },
            });

			if (response.hasOwnProperty("id")) {
				toast.success( langString('meeting_created'));
				setErrorMessage('');
				navigate('/');
			}

			if (response && (response.errors || response.message)) {
				toast.error(langString('failed_create_meeting'));
				setErrorMessage(response.errors[0].description);
			}

			if (!response) {
				toast.error(langString('failed_create_meeting'));
				setErrorMessage( langString('webex_settings_check') );
			}

		} catch (error) {
			// Handle errors
			console.error( langString('api_error') , error);
		} finally {
			// Enable the button after API request is complete (success or error)
			setIsSaving(false);
		}
	};

	const Timezones = TimezoneList();

	// Meeting type options for Webex
	const meetingTypeOptions = [
		{ value: 'meeting', label: langString('meeting') },
		{ value: 'webinar', label: langString('webinar') },
		{ value: 'personalRoomMeeting', label: langString('personal_room_meeting') },
	];

	const handleStickySaveClick = () => {
		// Trigger form submission by calling submit() method on the form
		hiddenSubmitRef.current.click();
	};

	const handleCloseError = () => {
		setErrorMessage('');
	};

	// Error message for Webex configuration
	useEffect(() => {
		if (!mhubMeetingsData.webex_auth && mhubMeetingsData.is_admin) {
			setErrorMessage(
				langString('webex_api_setup')  +
				`<a href="admin.php?page=meetinghub-settings#/webex">${langString('configure_webex')}</a>.`
			);
		}
	}, [mhubMeetingsData.webex_auth, mhubMeetingsData.is_admin]);

	return (
		<div>
			{errorMessage && (
				<div className="mhub_zoom_error error">
					<h3 dangerouslySetInnerHTML={{ __html: errorMessage }}></h3>
					<span className="close-icon" onClick={handleCloseError}>✕</span>
				</div>
			)}

			<div className="mhub-zoom-meeting-form">
				{ ! mhubMeetingsData.hide_floating_create_btn  && (
					<div className='mhub-col-lg-12'>
						<div className="mhub-form-actions sticky-save-btn">
							<button type="button" className="save-meeting" disabled={isSaving} onClick={handleStickySaveClick}>
								{isSaving ? langString('creating') : langString('create_meeting')}
							</button>
						</div>
					</div>
				) }

				<div className="form-wrapper">
					<form className="form" onSubmit={handleSubmit}>
						<div className="mhub-col-lg-12">
							<MhInput
								label={ langString('meeting_name') }
								description={langString('enter_meeting_name') }
								type="text"
								value={formData.title}
								onChange={(name, value) => handleChange(name, value)}
								name="title"
								required="yes"
							/>
						</div>

						<div className="mhub-col-lg-12">
							<div className="mhub-form-group">
								<label>{langString('meeting_description')}<small className="description">{langString('meeting_description_help')}</small></label>
								<div className="editor-wrapper">
									<Editor
										value={meetingDescription}
										onChange={handleMeetingDescription}
										containerProps={{ style: { resize: 'both' } }}
									/>
								</div>
							</div>
						</div>

						<div className="mhub-col-lg-12">
							<ImageUploader
								imageUrl={imageUrl}
								setImageUrl={setImageUrl}
								setImageID={setImageID}
								label={ langString('meeting_thumbnail') }
								description={langString('meeting_thumbnail_upload') }
							/>
						</div>

						<div className="mhub-col-lg-12">
							<MhTextArea
								label={langString('meeting_agenda') }
								description={langString('agenda_hint')}
								value={formData.agenda}
								onChange={(name, value) => handleChange(name, value)}
								name="agenda"
							/>
						</div>

						<div className="mhub-col-lg-12">
							<div className="mhub-form-group">
								<label>
									{langString('start_datetime') }
									<small className="description">{langString('start_datetime_help') }</small>
								</label>

								<div className="input-wrapper">
									<Datetime
										value={moment.tz(formData.startDateTime, formData.meeting_timezone)}
										onChange={(date) => handleChange('startDateTime', date)}
										isValidDate={(current) => {
											return current.isAfter(moment().subtract(1, 'day'), 'day');
										}}
									/>
								</div>
							</div>
						</div>

						<div className="mhub-col-lg-12">
							<MhDurationSelect
								label={langString('duration') }
								description={langString('select_duration') }
								hours={formData.duration_hours}
								minutes={formData.duration_minutes}
								onChangeHours={(value) => handleChange('duration_hours', value)}
								onChangeMinutes={(value) => handleChange('duration_minutes', value)}
							/>
						</div>

                        <div className="mhub-col-lg-12">
                            <MhSwitcher
                                label={langString('recurring_meeting') }
                                description={langString('enable_recurring') }
                                checked={formData.enable_recurring_meeting}
                                onChange={(name, value) => handleChange(name, value)}
                                name="enable_recurring_meeting"
                                disabled={!isProActive()}
                                isLocked={!isProActive()}
                                isProActive={isProActive()}
                            />
                        </div>

						{
							formData.enable_recurring_meeting && isProActive() && (
								<div className="mhub-col-lg-12">
									<MhSelect
										label={langString('recurrence')}
										description={langString('select_recurrence')}
										options={recurrenceOptions}
										value={formData.recurrence_option}
										onChange={(name, value) => handleChange(name, value)}
										name="recurrence_option"
									/>
								</div>
							)
						}


                        {
                            formData.enable_recurring_meeting && 1 == formData.recurrence_option && isProActive() && (
                                <div className="mhub-col-lg-12">
                                    <MhSelect
                                        label={langString('occurs_on') }
                                        description={langString('select_occurs_type')}
                                        options={dailyOccursOptions}
                                        value={formData.daily_occurs_on}
                                        onChange={(name, value) => handleChange(name, value)}
                                        name="daily_occurs_on"
                                    />
                                </div>
                            )
                        }

                    {
                        formData.enable_recurring_meeting && 1 == formData.recurrence_option && 'weekday' == formData.daily_occurs_on && isProActive() && (
                            <div className="mhub-col-lg-12">
                                <MhCheckbox
                                    label={langString('select_weekdays')}
                                    description={langString('select_weekdays')}
                                    options={formData.weekdays}
                                    onChange={handleWeekdaysChange}
                                />
                            </div>
                        )
                    }

                    {
                        formData.enable_recurring_meeting && 1 == formData.recurrence_option && 'day' == formData.daily_occurs_on && isProActive() && (
                            <div className="mhub-col-lg-12">
                                <MhSelect
                                    label={langString('repeat_every') }
                                    description={langString('repeat_every_help')}
								options={repeatDay}
								value={formData.repeat_day}
								onChange={(name, value) => handleChange(name, value)}
								name="repeat_day"
								SelectClass="zoom-recurrence-repeat"
								rightLabel="Day"
							/>
						</div>

						)
					}



						{
							formData.enable_recurring_meeting && 2 == formData.recurrence_option && isProActive() && (
								<div className="mhub-col-lg-12">
									<MhSelect
										label={langString('repeat_every')}
										description={langString('repeat_every_help')}
										options={repeatWeekly}
										value={formData.repeat_weekly}
										onChange={(name, value) => handleChange(name, value)}
										name="repeat_weekly"
										SelectClass="zoom-recurrence-repeat"
										rightLabel="Week"
									/>
								</div>

							)
						}

						{
							formData.enable_recurring_meeting && 3 == formData.recurrence_option && isProActive() && (
								<div className="mhub-col-lg-12">
									<MhSelect
										label={langString('repeat_every')}
										description={langString('repeat_every_help')}
										options={repeatMonthly}
										value={formData.repeat_monthly}
										onChange={(name, value) => handleChange(name, value)}
										name="repeat_monthly"
										SelectClass="zoom-recurrence-repeat"
										rightLabel="Month"
									/>
								</div>

							)
						}

                        {
                            formData.enable_recurring_meeting && 3 == formData.recurrence_option && isProActive() && (
                                <div className="mhub-col-lg-12">
                                    <MhSelect
                                        label={langString('occurs_on') }
                                        description={langString('select_occurs_type')}
                                        options={occursMonthly}
                                        value={formData.occurs_on_monthly}
                                        onChange={(name, value) => handleChange(name, value)}
                                        name="occurs_on_monthly"
                                    />
                                </div>
                            )
                        }

                        {
                            formData.enable_recurring_meeting && 3 == formData.recurrence_option && 'day' == formData.occurs_on_monthly && isProActive() && (
                                <div className="mhub-col-lg-12">
                                    <MhSelect
                                        label={langString('day')}
                                        description={langString('select_day')}
                                        options={repeatDay}
                                        value={formData.set_month_day}
                                        onChange={(name, value) => handleChange(name, value)}
                                        name="set_month_day"
                                    />
                                </div>
                            )
                        }


						{
							formData.enable_recurring_meeting && 3 == formData.recurrence_option && 'weekdays' == formData.occurs_on_monthly && isProActive() && (
								<div className="mhub-col-lg-12">
									<MhSelect
										label={langString('set_order')}
										description={langString('set_order_help')}
										options={monthOrder}
										value={formData.set_month_order}
										onChange={(name, value) => handleChange(name, value)}
										name="set_month_order"
									/>
								</div>
							)
						}

						{
							formData.enable_recurring_meeting && 3 == formData.recurrence_option && 'weekdays' == formData.occurs_on_monthly && isProActive() && (
								<div className="mhub-col-lg-12">
									<MhSelect
										label={langString('set_weekday') }
										description={langString('select_weekday')}
										options={monthlyWeekdays}
										value={formData.set_monthly_weekday}
										onChange={(name, value) => handleChange(name, value)}
										name="set_monthly_weekday"
									/>
								</div>
							)
						}

						{
							formData.enable_recurring_meeting && 2 == formData.recurrence_option && isProActive() && (
								<div className="mhub-col-lg-12">
									<MhCheckbox
										label={langString('occurs_on')}
										description={langString('select_weekdays')}
                                        options={formData.weekdays}
                                        onChange={handleWeekdaysChange}
									/>
								</div>

							)
						}


						{
							formData.enable_recurring_meeting && 5 != formData.recurrence_option && isProActive() && (
								<div className="mhub-col-lg-12">
									<MhSelect
										label={langString('ends')}
										description={langString('select_end_type')}
										options={endType}
										value={formData.end_type}
										onChange={(name, value) => handleChange(name, value)}
										name="end_type"
									/>
								</div>

							)
						}

						{
							formData.enable_recurring_meeting && 'occurrences' == formData.end_type && 5 != formData.recurrence_option && isProActive() && (

								<div className="mhub-col-lg-12">
									<MhSelect
										label={langString('set_num_occurrences')}
										description={langString('set_num_occurrences_help')}
										options={numberOfOccurrences}
										value={formData.set_number_of_occurrences}
										onChange={(name, value) => handleChange(name, value)}
										name="set_number_of_occurrences"
									/>
								</div>

							)
						}

						{
							formData.enable_recurring_meeting && 'date' == formData.end_type && 5 != formData.recurrence_option && isProActive() && (
								<div className="mhub-col-lg-12">
									<div className="mhub-form-group">
										<label>
											{langString('set_end_date')}
											<small className="description">{langString('set_end_date_help')}</small>
										</label>

										<div className="input-wrapper">
											<DatePicker
												selected={formData.end_date_time}
												onChange={(date) => handleChange('end_date_time', date)}
												dateFormat="MM/dd/yyyy"
												minDate={new Date()}
											/>
										</div>
									</div>
								</div>

							)
						}	

						<div className="mhub-col-lg-12">
							<MhSelect
								label={langString('timezone') }
								description={langString('meeting_timezone') }
								options={Timezones}
								value={formData.meeting_timezone}
								onChange={(name, value) => handleChange(name, value)}
								name="meeting_timezone"
							/>
						</div>

						<div className="mhub-col-lg-12">
							<MhSelect
								label={langString('meeting_type')}
								description={langString('meeting_type_hint')}
								options={meetingTypeOptions}
								value={formData.meeting_type}
								onChange={(name, value) => handleChange(name, value)}
								name="meeting_type"
								isNew={true}
							/>
						</div>

						{/* Webinar-only settings */}
						{formData.meeting_type === 'webinar' && (
							<>
								<div className="mhub-col-lg-12">
									<MhInput
										label={langString('panelist_password')}
										description={langString('only_for_webinars')}
										type="text"
										value={formData.panelist_password}
										onChange={(name, value) => handleChange(name, value)}
										name="panelist_password"
										required="no"
										isLocked={!isProActive()}
                                		isProActive={isProActive()}
										disabled={!isProActive()}
										isNew={true}
									/>
								</div>

								<div className="mhub-col-lg-12">
									<MhSwitcher
										label={langString('enable_webcast_view')}
										description={langString('allow_attendees_view_webcast')}
										checked={formData.enabled_webcast_view}
										onChange={(name, value) => handleChange(name, value)}
										name="enabled_webcast_view"
										isLocked={!isProActive()}
                                		isProActive={isProActive()}
										disabled={!isProActive()}
										isNew={true}
									/>
								</div>

								{formData.enable_should_register && (
									<div className="mhub-col-lg-12">
										<MhSwitcher
											label={langString('auto_approve_registrations')}
											description={langString('automatically_approve_registration_requests')}
											checked={formData.registration_auto_accept}
											onChange={(name, value) => handleChange(name, value)}
											name="registration_auto_accept"
											isLocked={!isProActive()}
                                			isProActive={isProActive()}
											disabled={!isProActive()}
											isNew={true}
										/>
									</div>
								)}
							</>
						)}

						{/* Invitees input */}
						<div className="mhub-col-lg-12">
							<MhCreatableSelect
								label={langString('invitees')}
								description={langString('add_emails_to_invite')}
								value={(formData.invitees || []).map(e => ({ value: e, label: e }))}
								onChange={(options) => handleChange('invitees', options ? options.map(o => o.value) : [])}
								placeholder={langString('type_email_press_enter')}
								disabled={!isProActive()}
								isLocked={!isProActive()}
								isNew={true}
								isMulti={true}
							/>
						</div>

						<div className="mhub-col-lg-12">
							<MhSwitcher
								label={langString('send_invite_emails')}
								description={langString('send_webex_invites_emails')}
								checked={formData.send_invite_emails}
								onChange={(name, value) => handleChange(name, value)}
								name="send_invite_emails"
								isLocked={!isProActive()}
                                isProActive={isProActive()}
								disabled={!isProActive()}
								isNew={true}
							/>
						</div>

						<div className="mhub-col-lg-12">
							<MhSwitcher
								label={langString('send_host_email')}
								description={langString('send_email_notification_host')}
								checked={formData.send_host_email}
								onChange={(name, value) => handleChange(name, value)}
								name="send_host_email"
								isLocked={!isProActive()}
                                isProActive={isProActive()}
								disabled={!isProActive()}
								isNew={true}
							/>
						</div>

						<div className="mhub-col-lg-12">
							<MhSwitcher
								label={langString('show_user_timezone')}
								description={langString('show_user_timezone_help') }
								checked={formData.display_time_user_zone}
								onChange={(name, value) => handleChange(name, value)}
								name="display_time_user_zone"
							/>
						</div>

						<div className="mhub-col-lg-12">
							<MhSwitcher
								label={langString('should_register') }
								description={langString('should_register_help')}
								checked={formData.enable_should_register}
								onChange={(name, value) => handleChange(name, value)}
								name="enable_should_register"
								disabled={!isProActive()}
								isLocked={!isProActive()}
								isProActive={isProActive()}
								isNew={true}
							/>
						</div>

						<div className="mhub-col-lg-12">
							<MhInput
								label={langString('password') }
								description={langString('password_help') }
								type="text"
								value={formData.password}
								onChange={(name, value) => handleChange(name, value)}
								name="password"
								required="no"
								maxLength={10}
							/>
						</div>

						<div className="mhub-col-lg-12">
							<MhSwitcher
								label={langString('join_before_host') }
								description={langString('join_before_host_hint') }
								checked={formData.join_before_host}
								onChange={(name, value) => handleChange(name, value)}
								name="join_before_host"
							/>
						</div>

						{formData.join_before_host && (
							<>
								<div className="mhub-col-lg-12">
									<MhSelect
										label={langString('join_before_host_minutes')}
										description={langString('allow_joining_minutes_before_host')}
										options={jbhMinuteOptions}
										value={formData.join_before_host_minutes}
										onChange={(name, value) => handleChange(name, value)}
										name="join_before_host_minutes"
									/>
								</div>

								<div className="mhub-col-lg-12">
									<MhSwitcher
										label={langString('enable_connect_audio_before_host')}
										description={langString('allow_participants_connect_audio_before_host')}
										checked={formData.enable_connect_audio_before_host}
										onChange={(name, value) => handleChange(name, value)}
										name="enable_connect_audio_before_host"
									/>
								</div>
							</>
						)}

						<div className="mhub-col-lg-12">
							<MhSwitcher
								label={langString('auto_record') }
								description={langString('auto_record_hint') }
								checked={formData.auto_record}
								onChange={(name, value) => handleChange(name, value)}
								name="auto_record"
							/>
						</div>

						<div className="mhub-col-lg-12">
							<MhSwitcher
								label={langString('enable_breakout') }
								description={langString('enable_breakout_hint') }
								checked={formData.breakout_sessions}
								onChange={(name, value) => handleChange(name, value)}
								name="breakout_sessions"
							/>
						</div>

						<div className="mhub-col-lg-12">
							<MhSwitcher
								label={langString('enable_auto_lock') }
								description={langString('enable_breakout_hint') }
								checked={formData.automatic_lock}
								onChange={(name, value) => handleChange(name, value)}
								name="automatic_lock"
							/>
						</div>

						{formData.automatic_lock && (
							<div className="mhub-col-lg-12">
								<MhSelect
									label={langString('lock_after')}
									description={langString('lock_after_hint') }
									options={lockOptions}
									value={formData.lock_minutes}
									onChange={(name, value) => handleChange(name, value)}
									name="lock_minutes"
								/>
							</div>
						)}

						{/* Attendee controls */}
						<div className="mhub-col-lg-12">
							<MhSwitcher
								label={langString('allow_host_unmute_participants')}
								description={langString('hosts_can_unmute_participants')}
								checked={formData.allow_host_to_unmute_participants}
								onChange={(name, value) => handleChange(name, value)}
								name="allow_host_to_unmute_participants"
							/>
						</div>

						<div className="mhub-col-lg-12">
							<MhSwitcher
								label={langString('allow_attendees_unmute_themselves')}
								description={langString('attendees_can_unmute_themselves')}
								checked={formData.allow_attendee_to_unmute_self}
								onChange={(name, value) => handleChange(name, value)}
								name="allow_attendee_to_unmute_self"
								isLocked={!isProActive()}
                                isProActive={isProActive()}
								disabled={!isProActive()}
								isNew={true}
							/>
						</div>

						<div className="mhub-col-lg-12">
							<MhSwitcher
								label={langString('mute_attendees_upon_entry')}
								description={langString('all_attendees_join_muted')}
								checked={formData.mute_attendee_upon_entry}
								onChange={(name, value) => handleChange(name, value)}
								name="mute_attendee_upon_entry"
								isLocked={!isProActive()}
                                isProActive={isProActive()}
								disabled={!isProActive()}
								isNew={true}
							/>
						</div>

						{/* Live stream settings */}
						<div className="mhub-col-lg-12">
							<MhSwitcher
								label={langString('enable_live_stream')}
								description={langString('enable_rtmp_live_stream')}
								checked={formData.enabled_live_stream}
								onChange={(name, value) => handleChange(name, value)}
								name="enabled_live_stream"
								isLocked={!isProActive()}
                                isProActive={isProActive()}
								disabled={!isProActive()}
								isNew={true}
							/>
						</div>

						{formData.enabled_live_stream && (
							<div className="mhub-col-lg-12">
								<MhInput
									label={langString('live_stream_rtmp_url')}
									description={langString('provide_rtmp_destination_url')}
									type="text"
									value={formData.live_stream_rtmp_url}
									onChange={(name, value) => handleChange(name, value)}
									name="live_stream_rtmp_url"
									isLocked={!isProActive()}
                                	isProActive={isProActive()}
									disabled={!isProActive()}
									isNew={true}
								/>
							</div>
						)}

						{/* Space meeting (Ad-hoc) */}
						<div className="mhub-col-lg-12">
							<MhSwitcher
								label={langString('create_adhoc_space_meeting')}
								description={langString('create_meeting_webex_space')}
								checked={formData.adhoc}
								onChange={(name, value) => handleChange(name, value)}
								name="adhoc"
								isLocked={!isProActive()}
                                isProActive={isProActive()}
								disabled={!isProActive()}
								isNew={true}
							/>
						</div>

						{formData.adhoc && (
							<div className="mhub-col-lg-12">
								<MhInput
									label={langString('space_room_id')}
									type="text"
									description={langString('enter_target_webex_space_id')}
									value={formData.room_id}
									onChange={(name, value) => handleChange(name, value)}
									name="room_id"
									isLocked={!isProActive()}
                                	isProActive={isProActive()}
									disabled={!isProActive()}
									isNew={true}
								/>
							</div>
						)}

						<div className="mhub-col-lg-12">
							<MhSwitcher
								label={langString('hide_sidebar')}
								description={langString('hide_sidebar_help') }
								name="hide_sidebar"
								checked={formData.hide_sidebar}
								onChange={(name, value) => handleChange(name, value)}
							/>
						</div>

						<div className="mhub-col-lg-12">
							<MhSwitcher
								label={langString('hide_header_footer') }
								description={langString('hide_header_footer_help') }
								name="hide_header_footer"
								checked={formData.hide_header_footer}
								onChange={(name, value) => handleChange(name, value)}
							/>
						</div>

						<button type="submit" style={{ display: 'none' }} ref={hiddenSubmitRef} />

						<div className="mhub-form-actions">
							<button type="submit" className="save-meeting" disabled={isSaving}>
								{isSaving ? langString('creating')  : langString('create_meeting') }
							</button>
						</div>
					</form>
				</div>
			</div>
		</div>
	);
};

export default WebexForm;
