import { useState, useContext, useEffect } from 'react';
import InputText from './inputs/InputText';
import { progressTrackerContext } from '../context/progressTrackerContext';
import StepTracker from './StepTracker';
import NextButton from './navigation/NextButton';
import BackButton from './navigation/BackButton';

const UserForm = () => {

	const [userDetails, setUserDetails] = useState({firstName: null, lastName: '', email: null,	mobileNumber: null, address: null })
	const [errorMessage, setErrorMessage] = useState({firstName: null, email: null,	mobileNumber: null, address: null })
	const { currentStep, setCurrentStep } = useContext(progressTrackerContext);
    const [disableNext, setDisableNext] = useState(true);

	useEffect(() => {
		if (
			userDetails.firstName &&
			userDetails.email &&
			userDetails.mobileNumber &&
			userDetails.address
		) {
			setDisableNext(false);
		} else {
			setDisableNext(true);
		}
	}, [userDetails]);

	useEffect(() => {
		const userAppointment = JSON.parse(sessionStorage.getItem("userAppointment"));
		if (userAppointment.userDetail) {
			setUserDetails({
				firstName: userAppointment.userDetail.firstName || null,
				lastName: userAppointment.userDetail.lastName || null,
				email: userAppointment.userDetail.email || null,
				mobileNumber: userAppointment.userDetail.mobileNumber || null,
				address: userAppointment.userDetail.address || null,
			})
		}
	},[])

	function handlechange(e, name) {
		const value = e.target.value;
		setUserDetails(prev => ({
			...prev,
			[name]: value
		}));
	}

	function handleValidation(e, type) {
		if(type === 'firstName') {
			if(!userDetails.firstName) {
				setErrorMessage(prev => ({ ...prev, firstName: 'Enter Your Name'}))
				return;
			}
			if ( !/^[a-zA-Z]+$/.test(userDetails.firstName)) {
				setErrorMessage(prev => ({ ...prev, firstName: 'use Valid Name'}))
				return
			} 
			setErrorMessage(prev => ({ ...prev, firstName: null}))
		}
		if(type === 'email') {
			if (!userDetails.email) {
				setErrorMessage(prev => ({  ...prev, email: 'Enter Your Email'}))
				return
			}
			if ( !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(userDetails.email)) {
				setErrorMessage(prev => ({  ...prev, email: 'use Valid Email ID'}))
				return
			} 
			setErrorMessage(prev => ({  ...prev, email: null}))
			return
		}
		if(type === 'mobileNumber') {
			if (!userDetails.mobileNumber) {
				setErrorMessage(prev => ({  ...prev, mobileNumber: 'Enter Mobile number'}))
				return
			}
			if (!/^\+?[1-9]\d{7,14}$/.test(userDetails.mobileNumber)) {
				setErrorMessage(prev => ({
					...prev,
					mobileNumber: 'Enter a valid international phone number'
				}));
				return;
			}
			setErrorMessage(prev => ({  ...prev, mobileNumber: null}))
			return
		}
		if(type === 'address') {
			if (!userDetails.address) {
				setErrorMessage(prev => ({  ...prev, address: 'Enter Your Address'}))
				return
			}
			setErrorMessage(prev => ({  ...prev, address: null}))
			return
		}
	}

	function handleSubmit(e) {
		e.preventDefault();
		const userAppointment = JSON.parse(sessionStorage.getItem("userAppointment"));
		userAppointment.userDetail = userDetails;
		sessionStorage.setItem('userAppointment', JSON.stringify(userAppointment));

		if (!errorMessage.firstName  && !errorMessage.email && !errorMessage.mobileNumber && !errorMessage.address) {
			setCurrentStep(currentStep + 1);
		}
	}

  return (
	<div className='user-form-block'>
		<p className='booking-component-title'>Returning customer?</p>
		<StepTracker />
		<form className='booking-step-wrapper' onSubmit={handleSubmit} >
			<div className='booking-form-input-fields'>
				<InputText  containerStyle="booking-field-container" inputType='text' labelTitle='First Name ' name='firstname' onChange={(e) => handlechange(e, 'firstName')} labelStyle="booking-form-label required" inputStyle="booking-input-field" errorMessage={errorMessage.firstName} onBlurFun={(e) => handleValidation(e, 'firstName')} value={userDetails.firstName} />
				<InputText  containerStyle="booking-field-container" inputType='text' labelTitle='Last Name ' name='lastname' onChange={(e) => handlechange(e, 'lastName')} labelStyle="booking-form-label" inputStyle="booking-input-field" errorMessage={errorMessage.lastName}  value={userDetails.lastName} />
				<InputText  containerStyle="booking-field-container" inputType='email' labelTitle='Email ' name='email'  onChange={(e) => handlechange(e, 'email')} labelStyle="booking-form-label required" inputStyle="booking-input-field" errorMessage={errorMessage.email} onBlurFun={(e) => handleValidation(e, 'email')} value={userDetails.email}  />
				<InputText  containerStyle="booking-field-container" inputType='text' labelTitle='Mobile Number ' name='mobilenumber' onChange={(e) => handlechange(e, 'mobileNumber')} labelStyle="booking-form-label required" inputStyle="booking-input-field" errorMessage={errorMessage.mobileNumber} onBlurFun={(e) => handleValidation(e, 'mobileNumber')} value={userDetails.mobileNumber}  />
				<InputText containerStyle="booking-field-container booking-address-field" inputType='text' labelTitle='Address ' name='address' onChange={(e) => handlechange(e, 'address')} labelStyle="booking-form-label required" inputStyle="booking-input-field" errorMessage={errorMessage.address} onBlurFun={(e) => handleValidation(e, 'address')} value={userDetails.address} />
			</div>
			<div className='booking-nav-buttons'>
				<NextButton type="submit" styles={`booking-nav-next ${disableNext ? 'disabled' : ''}`} innerText={"What's Next"}/>
				<BackButton styles="booking-nav-back" onClick={() => setCurrentStep(currentStep - 1)} />
			</div>
		</form>
	</div>
  )
}

export default UserForm ;
