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 MhSwitcher from '../../../common/fields/MhSwitcher';
import MhTextArea from '../../../common/fields/MhTextArea';
import TimezoneList from '../../../common/fields/TimezoneList';
import MhDurationSelect from '../../../common/fields/MhDurationSelect';
import { generateRandomRoom } from '../../RandomRoomGenerator';
import { isProActive } from '../../../../Helpers';
import Editor from 'react-simple-wysiwyg';
import { toast } from 'react-toastify';
const { __ } = wp.i18n;
import ImageUploader from '../../../common/ImageUploader';
import moment from 'moment-timezone';
import { langString } from '../../../../Helpers';

const MsTeamsForm = ({ selectedPlatform }) => {
	const [errorMessage, setErrorMessage] = useState('');
	const [isSaving, setIsSaving] = useState(false);
	const navigate = useNavigate();
	const formRef = useRef(null);
	const hiddenSubmitRef = useRef(null);

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

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

	var mhub_msteams_settings = mhubMeetingsData.mhub_msteams_settings;
	const defaultTimezone = mhub_msteams_settings ? mhub_msteams_settings.meeting_timezone : mhubMeetingsData.mhub_timezone;

	const [formData, setFormData] = useState({
		title: generateRandomRoom(10),
		startDateTime: moment.tz(new Date(), defaultTimezone).format(),
		end_date_time: new Date(),
		join_before_host: mhub_msteams_settings ? mhub_msteams_settings.join_before_host : false,
		auto_record: isProActive() ? (mhub_msteams_settings ? mhub_msteams_settings.auto_record : false) : false,
		allow_attendee_camera: isProActive() ? (mhub_msteams_settings ? mhub_msteams_settings.allow_attendee_camera : true) : false,
		allow_attendee_mic: isProActive() ? (mhub_msteams_settings ? mhub_msteams_settings.allow_attendee_mic : true) : false,
		enable_lobby: mhub_msteams_settings ? mhub_msteams_settings.enable_lobby : true,
		meeting_timezone: mhub_msteams_settings ? mhub_msteams_settings.meeting_timezone : mhubMeetingsData.mhub_timezone,
		agenda: '',
		enable_recurring_meeting: mhub_msteams_settings ? mhub_msteams_settings.enable_recurring_meeting : false,
		duration_hours: 0,
		duration_minutes: 60,
		enable_should_register: mhub_msteams_settings ? mhub_msteams_settings.enable_should_register : false,
		hide_sidebar: mhub_msteams_settings ? mhub_msteams_settings.hide_sidebar : false,
		hide_header_footer: mhub_msteams_settings ? mhub_msteams_settings.hide_header_footer : false,
		display_time_user_zone: (mhub_msteams_settings && mhub_msteams_settings.display_time_user_zone !== undefined) ? mhub_msteams_settings.display_time_user_zone : 1,
	});

	useEffect(() => {
		if (formData.meeting_timezone) {
			setFormData((prev) => ({
				...prev,
				startDateTime: moment.tz(prev.startDateTime, prev.meeting_timezone).tz(formData.meeting_timezone).format(),
				end_date_time: moment.tz(prev.end_date_time, 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();
		}

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

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

		// Disable the button
		setIsSaving(true);

		console.log('MS Teams form submission started');
		console.log('Form data:', formData);
		console.log('Selected platform:', selectedPlatform);

		try {
			// Make an API request using wp.apiFetch
			const response = await wp.apiFetch({
				path: 'mhub/v1/meetings',
				method: 'POST',
				data: {
					title: formData.title,
					startDateTime: formData.startDateTime,
					join_before_host: formData.join_before_host,
					auto_record: formData.auto_record,
					allow_attendee_camera: formData.allow_attendee_camera,
					allow_attendee_mic: formData.allow_attendee_mic,
					enable_lobby: formData.enable_lobby,
					meeting_timezone: formData.meeting_timezone,
					agenda: formData.agenda,
					enable_recurring_meeting: formData.enable_recurring_meeting,
					duration_hours: formData.duration_hours,
					duration_minutes: formData.duration_minutes,
					enable_should_register: formData.enable_should_register,
					selected_platform: selectedPlatform,
					hide_sidebar: formData.hide_sidebar,
					hide_header_footer: formData.hide_header_footer,
					display_time_user_zone: formData.display_time_user_zone,
					meeting_description: JSON.stringify({ content: meetingDescription }),
					image_url: imageUrl,
					image_id: imageId,
				},
			});

			console.log('MS Teams API response:', response);

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

			if (response && (response.code || response.message || response.error)) {
				toast.error(langString('meeting_create_failed'));

				let errMsg = langString('error');

				if (response.message) {
					errMsg = response.message;
				} else if (response.error && response.error.message) {
					errMsg = response.error.message;
				} else if (typeof response.error === 'string') {
					errMsg = response.error;
				}

				if (errMsg === 'No privilege.') {
					errMsg = langString('no_permission_add_user');
				}

				setErrorMessage(errMsg);
			}
		} catch (error) {
			// Handle errors
			console.error('MS Teams form submission error:', error);
			console.error(langString('api_error'), error);
			toast.error('Error: ' + error.message);
			setErrorMessage(error.message || langString('error'));
		} finally {
			// Enable the button after API request is complete (success or error)
			setIsSaving(false);
		}
	};

	const Timezones = TimezoneList();

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

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

	useEffect(() => {
		if (!mhubMeetingsData.msteams_auth && mhubMeetingsData.is_admin) {
			setErrorMessage(
				'To enable Microsoft Teams, please set up its API settings. ' +
				`<a href="admin.php?page=meetinghub-settings#/msteams">Configure Microsoft Teams</a>.`
			);
		}
	}, [mhubMeetingsData.msteams_auth, mhubMeetingsData.is_admin]);

	return (
		<div>
			{errorMessage && (
				<div className="mhub_msteams_error error">
					<h3 dangerouslySetInnerHTML={{ __html: errorMessage }}></h3>
					<span className="close-icon" onClick={handleCloseError}>✕</span>
				</div>
			)}
			<div className="mhub-msteams-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('please_enter_the_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="Write agenda for your Microsoft Teams meeting"
								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={true}
								isUpcomming={true}
							/>
						</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">
							<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={true}
								isUpcomming={true}
							/>
						</div>

						<div className="mhub-col-lg-12">
							<MhSwitcher
								label="Enable Lobby"
								description="Enable lobby feature where attendees wait for host approval to join"
								checked={formData.enable_lobby}
								onChange={(name, value) => handleChange(name, value)}
								name="enable_lobby"
							/>
						</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>

						<div className="mhub-col-lg-12">
							<MhSwitcher
								label="Allow Attendee Camera"
								description="Allow meeting attendees to turn on their cameras"
								checked={formData.allow_attendee_camera}
								onChange={(name, value) => handleChange(name, value)}
								name="allow_attendee_camera"
								disabled={!isProActive()}
								isLocked={!isProActive()}
								isProActive={isProActive()}
							/>
						</div>

						<div className="mhub-col-lg-12">
							<MhSwitcher
								label="Allow Attendee Microphone"
								description="Allow meeting attendees to unmute their microphones"
								checked={formData.allow_attendee_mic}
								onChange={(name, value) => handleChange(name, value)}
								name="allow_attendee_mic"
								disabled={!isProActive()}
								isLocked={!isProActive()}
								isProActive={isProActive()}
							/>
						</div>

						<div className="mhub-col-lg-12">
							<MhSwitcher
								label={langString('auto_record')}
								description="Automatically record Microsoft Teams meetings when they start"
								checked={formData.auto_record}
								onChange={(name, value) => handleChange(name, value)}
								name="auto_record"
								disabled={!isProActive()}
								isLocked={!isProActive()}
								isProActive={isProActive()}
							/>
						</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>

						<div className="mhub-col-lg-12">
							<div className="mhub-form-actions">
								<button type="submit" className="save-meeting" disabled={isSaving}>
									{isSaving ? langString('creating') : langString('create_meeting')}
								</button>
								<button type="button" className="hidden-submit" ref={hiddenSubmitRef} style={{ display: 'none' }} onClick={handleSubmit}></button>
							</div>
						</div>
					</form>
				</div>
			</div>
		</div>
	);
};

export default MsTeamsForm;