import { useEffect, useState, useContext } from 'react';
import { getCategory, getFormattedDate } from '../services/summary-page-utilities';
import { postUser } from '../services/post-user-details';
import { progressTrackerContext } from '../context/progressTrackerContext';
import { tokenContext } from '../context/tokenContext';
import StepTracker from './StepTracker';
import NextButton from "./navigation/NextButton";
import BackButton from "./navigation/BackButton";
import ListSkeleton from './skeleton/ListSkeleton';

const SummaryPage = () => {

	const [selectedCategories, setSelectedCategories] = useState([]);
	const [selectedServices, setSelectedServices] = useState([]);
	const [selectedTime, setSelectedTime] = useState('');
	const [selectedDate, setSelectedDate] = useState('');
	const [userName, setUserName] = useState('');
	const [formattedDate, setFormattedDate] = useState(null);
	const [userNotes, setuserNotes] = useState(null);
	const { tokenid, setTokenid } = useContext(tokenContext);
	const { currentStep, setCurrentStep } = useContext(progressTrackerContext);
	const [loadingCategories, setLoadingCategories] = useState(true);
	const [loading, setLoading] = useState(false);

	useEffect(() => {
		const fetchData = async () => {
			const userAppointment = JSON.parse(sessionStorage.getItem("userAppointment"));
			if (userAppointment?.categories) {
				const categories = await getCategory(userAppointment.categories, 'categories');
				setSelectedCategories(categories);
			}
			setLoadingCategories(false);

			if (userAppointment?.services) {
				const services = await getCategory(userAppointment.services, 'services');
				setSelectedServices(services);
			}

			if (userAppointment?.bookedDate) {
				setSelectedDate(userAppointment.bookedDate);
			}
			if (userAppointment?.bookedTime) {
				setSelectedTime(userAppointment.bookedTime);
			}
			if (userAppointment?.userDetail?.firstName) {
				const user = userAppointment.userDetail.firstName.concat(userAppointment.userDetail.lastName ? userAppointment.userDetail.lastName : '');
				setUserName(user);
			}
		};
		fetchData();
	}, []);

	useEffect(() => {
		setFormattedDate(getFormattedDate(selectedDate, selectedTime));
	}, [selectedDate, selectedTime])

	const disableNext = loadingCategories || !formattedDate;// to disable button.

	async function handleSubmit() {
		setLoading(true);

		try {
			const notes = userNotes;
			const userAppointment = JSON.parse(sessionStorage.getItem("userAppointment")) || {};

			userAppointment.userDetail = {
				...(userAppointment.userDetail || {}),
				notes,
			};

			delete userAppointment.getSelectedTime;

			sessionStorage.setItem(
				'userAppointment',
				JSON.stringify(userAppointment)
			);

			const response = await postUser();

			if (
				!response ||
				response === 'failed' ||
				!response.data?.token
			) {
				alert('Booking failed. Please try again.');
				return;
			}

			setTokenid(response.data.token);

			sessionStorage.removeItem('userAppointment');

			setCurrentStep(currentStep + 1);
		} catch (error) {
			console.error('Booking failed:', error);
			alert('Booking failed. Please try again.');
		} finally {
			setLoading(false);
		}
	}

	return (
		<div className='inner-booking-block'>
			<p className='booking-component-title'>Booking summary</p>
			<StepTracker />
			<p className='booking-user-description'>Dear <span>{userName},</span> </p>
			<p className='booking-user-description' >please review and confirm the details of your booking:</p>
			<div className='booking-step-wrapper'>
				<div className='summary-content'>
					<div className='book-an-appointment-block booking-summary-block'>
						<p className='booking-detail'>
							<span>
								{
									!formattedDate ? <ListSkeleton amount={1} /> : formattedDate
								}
							</span>
						</p>
						<p className='booking-summary-description'> Date and time booked </p>
						{Array.isArray(selectedCategories) && (
							<>
								<div className='booking-detail booking-categories'>
									{
										loadingCategories ? (
											<ListSkeleton amount={1} />
										) : (
											selectedCategories.map((category, index) => (
												<span key={index}>
													{category}<span> (Categories)</span><br />
												</span>
											))
										)
									}
									{Array.isArray(selectedServices) && (
										<>
											{
												loadingCategories ? (
													<ListSkeleton amount={1} />
												) : (
													selectedServices.map((service, index) => (
														<span key={`service-${index}`}>{service}<span> (Services)</span><br /></span>

													))
												)
											}
										</>
									)}
								</div>
								<p className='booking-summary-description'> Categories & Services </p>
							</>
						)}
					</div>
					<div className='booking-summary-notes-wrapper'>
						<label>Leave a message</label>
						<textarea rows="4" cols="75" name='usernotes' onChange={(e) => setuserNotes(e.target.value)} placeholder='Leave a message' />
					</div>
					<p className='booking-user-description' > <span>Complete Your Reservation</span> </p>
					<p className='booking-user-description'>Click on Next button</p>
					<div className='booking-terms'>
						<h5>Terms & Conditions</h5>
						<p>In case of delay we'll keep your booking for 30 minutes, after that you'll lose your priority. Please arrive a few minutes before your scheduled time.</p>
					</div>

				</div>
				<div className='booking-nav-buttons'>
					<NextButton styles={`booking-nav-next ${disableNext || loading ? 'disabled' : ''}`} onClick={handleSubmit} innerText={loading ? 'Loading...' : 'Next'} />
					<BackButton styles="booking-nav-back" onClick={() => setCurrentStep(currentStep - 1)} />
				</div>
			</div>
		</div>
	);
};

export default SummaryPage;
