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 { 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 MsTeamsEditForm = ({ meetingId, meetingDetails }) => {
	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: '',
		startDateTime: moment.tz(new Date(), defaultTimezone).format(),
		end_date_time: new Date(),
		join_before_host: false,
		auto_record: false,
		allow_attendee_camera: true,
		allow_attendee_mic: true,
		enable_lobby: true,
		meeting_timezone: defaultTimezone,
		agenda: '',
		enable_recurring_meeting: false,
		duration_hours: 0,
		duration_minutes: 60,
		enable_should_register: false,
		hide_sidebar: false,
		hide_header_footer: false,
		display_time_user_zone: 1,
	});

	// Load meeting data on component mount
	useEffect(() => {
		if (meetingDetails) {
			const settings = typeof meetingDetails.settings === 'string' ? JSON.parse(meetingDetails.settings) : meetingDetails.settings;

			setFormData({
				title: meetingDetails.title || '',
				startDateTime: settings.startDateTime || moment.tz(new Date(), defaultTimezone).format(),
				join_before_host: settings.join_before_host || false,
				auto_record: isProActive() ? (settings.auto_record || false) : false,
				allow_attendee_camera: isProActive() ? (settings.allow_attendee_camera !== undefined ? settings.allow_attendee_camera : true) : false,
				allow_attendee_mic: isProActive() ? (settings.allow_attendee_mic !== undefined ? settings.allow_attendee_mic : true) : false,
				enable_lobby: settings.enable_lobby !== undefined ? settings.enable_lobby : true,
				meeting_timezone: settings.meeting_timezone || defaultTimezone,
				agenda: settings.agenda || '',
				enable_recurring_meeting: settings.enable_recurring_meeting || false,
				duration_hours: settings.duration_hours || 0,
				duration_minutes: settings.duration_minutes || 60,
				enable_should_register: settings.enable_should_register || false,
				hide_sidebar: settings.hide_sidebar || false,
				hide_header_footer: settings.hide_header_footer || false,
				display_time_user_zone: settings.display_time_user_zone !== undefined ? settings.display_time_user_zone : 1,
			});

			// Set meeting description
			if (meetingDetails.meeting_description) {
				setMeetingDescription(meetingDetails.meeting_description);
			}

			// Set image data
			if (settings.image_url) {
				setImageUrl(settings.image_url);
			}
			if (settings.image_id) {
				setImageID(settings.image_id);
			}
		}
	}, [meetingDetails]);

	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();
		}

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

	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/${meetingId}`,
				method: 'PUT',
				data: {
					title: formData.title,
					id: meetingId,
					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: 'msteams',
					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,
				},
			});

			if (response && !response.code && !response.error) {
				setErrorMessage('');
				toast.success('Microsoft Teams meeting updated successfully!');
				navigate('/');
			}

			if (response && (response.code || response.message || response.error)) {
				toast.error('Failed to update Microsoft Teams meeting');

				const errMsg = response.message || (response.error && response.error.message) || (typeof response.error === 'string' ? response.error : 'An error occurred while updating the meeting');
				setErrorMessage(errMsg);
			}
		} catch (error) {
			console.error('API Error:', error);
			toast.error('Failed to update meeting');
		} finally {
			setIsSaving(false);
		}
	};

	const Timezones = TimezoneList();

	const handleStickySaveClick = () => {
		hiddenSubmitRef.current.click();
	};

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



	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 ? 'Updating...' : 'Update 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 ? 'Updating...' : 'Update Meeting'}
								</button>
								<button type="button" className="hidden-submit" ref={hiddenSubmitRef} style={{ display: 'none' }} onClick={handleSubmit}></button>
							</div>
						</div>
					</form>
				</div>
			</div>
		</div>
	);
};

export default MsTeamsEditForm;