'use client' import React, { useEffect, useState } from 'react' import { areasOfExpertise } from '@/app/expertForm/utils/listOfExpertise' import { listOfLanguages } from '@/app/expertForm/utils/listOfLanguages' import 'react-phone-number-input/style.css' import PhoneInput from 'react-phone-number-input' import { updateUser } from './action' import { useRouter } from 'next/navigation' import { countries } from '@/app/expertForm/utils/listOfCountries' import { ChevronUpIcon, ChevronDownIcon } from '@heroicons/react/24/outline' const ExpertProfileForm = ({ userInfo, profileImg }) => { const [biography, setBiography] = useState('') console.log({ userInfo }) const [formData, setFormData] = useState({ lastName: userInfo.lastName || '', firstName: userInfo.firstName || '', username: userInfo.userName || '', // Make sure to align the names (`username` in state vs `userName` in fetched userInfo) phone: userInfo.phone || '', state: userInfo.state || '', city: userInfo.city || '', role: userInfo.role, zipCode: userInfo.zipcode || '', // Ensure alignment of `zipCode` in state vs `zipcode` in fetched userInfo rate: userInfo.rate || '', countryOfResidence: userInfo.countryOfResidence, languagesSpoken: userInfo.languagesSpoken || [], // This needs to be an array. Adjust based on how languages are stored or fetched. occupation: userInfo.role || '', // Occupation isn't directly provided in fetched userInfo. Adjust accordingly. dateOfBirth: userInfo.dateOfBirth ? new Date(userInfo.dateOfBirth).toISOString().split('T')[0] : '', // Format date for input[type=date] photoUrl: null, // Photo handling depends on how you're managing images. Adjust accordingly. biography: userInfo.biography || biography, linkedInURL: userInfo.linkedInURL || '', instagramURL: userInfo.instagramURL || '', youtubeURL: userInfo.youtubeURL || '', spotifyURL: userInfo.spotifyURL || '', tiktokURL: userInfo.tiktokURL || '', twitterURL: userInfo.twitterURL || '', amazonURL: userInfo.amazonURL || '', websiteURL1: userInfo.websiteURL1 || '', websiteURL2: userInfo.websiteURL2 || '', }) const router = useRouter() const [imagePreview, setImagePreview] = useState('') const [selectedLanguage, setSelectedLanguage] = useState([]) const [validationErrors, setValidationErrors] = useState({}) const [showExperienceSection, setShowExperienceSection] = useState(false) // State to track the visibility of the experience section const [showEducationSection, setShowEducationSection] = useState(false) // State to track the visibility of the experience section const [showExpertiseSection, setShowExpertiseSection] = useState(false) // State to track the visibility of the experience section const [educations, setEducations] = useState([]) const [experiences, setExperiences] = useState([]) const [expertises, setExpertises] = useState([]) const maxCharCount = 380 // Example limit similar to a tweet const [newExpertise, setNewExpertise] = useState('') const [stateCode, setStateCode] = useState('') const [showCityInput, setShowCityInput] = useState(true) const [videoURLs, setVideoURLs] = useState([]) const [submited, setSubmited] = useState(false) const [loading, setLoading] = useState(false) useEffect(() => { console.log({ userInfo }) setBiography(userInfo.biography) setExperiences(userInfo.experiences) setEducations(userInfo.educations) }, []) useEffect(() => { console.log({ formData }) }, [formData]) const handleChange = (e) => { const { name, value } = e.target setFormData((prevFormData) => ({ ...prevFormData, [name]: value, })) } const calculateDuration = (startDate, endDate, isCurrent) => { console.log({ startDate }, { endDate }, { isCurrent }) if (!startDate) return '' const start = new Date(startDate) const end = isCurrent ? new Date() : new Date(endDate) if (isCurrent || end) { const diffInMonths = (end.getFullYear() - start.getFullYear()) * 12 + end.getMonth() - start.getMonth() const years = Math.floor(diffInMonths / 12) const months = diffInMonths % 12 let duration = '' if (years > 0) duration += `${years} year${years > 1 ? 's' : ''}` if (months > 0) duration += `${duration ? ', ' : ''}${months} month${ months > 1 ? 's' : '' }` return duration } return '' } const toggleExperienceSection = () => { setShowExperienceSection((prevShow) => !prevShow) } const toggleExpertiseSection = () => { setShowExpertiseSection((prevShow) => !prevShow) } const toggleEducationSection = () => { setShowEducationSection((prevShow) => !prevShow) } const handleExperienceChange = (index, event) => { const updatedExperiences = [...experiences] const { name, value, type, checked } = event.target // If "isCurrent" is checked, clear "endDate" for UI purposes if (name === 'isCurrent') { updatedExperiences[index] = { ...updatedExperiences[index], [name]: checked, endDate: checked ? 'Present' : updatedExperiences[index].endDate, // Keep this line if you wish to retain the previous endDate value in state } } else { updatedExperiences[index] = { ...updatedExperiences[index], [name]: value, } } // Recalculate duration anytime startDate, endDate, or isCurrent changes if (name === 'startDate' || name === 'endDate' || name === 'isCurrent') { const { startDate, endDate, isCurrent } = updatedExperiences[index] updatedExperiences[index].duration = calculateDuration( startDate, endDate, isCurrent ) } setExperiences(updatedExperiences) } const addExperience = () => { setShowExperienceSection(true) setExperiences([ ...experiences, { companyName: '', role: '', startDate: '', endDate: '', isCurrent: false, duration: '', description: '', }, ]) } const removeExperience = (index) => { const filteredExperiences = experiences.filter((_, i) => i !== index) setExperiences(filteredExperiences) } const handleAddLanguage = () => { if ( selectedLanguage && !formData.languagesSpoken.includes(selectedLanguage) ) { console.log('add a language', selectedLanguage) setFormData({ ...formData, languagesSpoken: [...formData.languagesSpoken, selectedLanguage], }) setSelectedLanguage('') // Reset the selected language } } const handleRemoveLanguage = (language) => { setFormData({ ...formData, languagesSpoken: formData.languagesSpoken.filter( (lang) => lang !== language ), }) } const handleKeyPress = (event) => { if (event.key === 'Enter') { event.preventDefault() handleAddLanguage() } } // handle education change const handleEducationChange = (index, event) => { const updatedEducations = [...educations] const { name, value, type, checked } = event.target if (type === 'checkbox' && name === 'isCurrent') { updatedEducations[index] = { ...updatedEducations[index], [name]: checked, endDate: 'Present', // Clear endDate if "isCurrent" is checked } } else { updatedEducations[index] = { ...updatedEducations[index], [name]: value, } } // Recalculate duration anytime startDate, endDate, or isCurrent changes if (name === 'startDate' || name === 'endDate' || name === 'isCurrent') { const { startDate, endDate, isCurrent } = updatedEducations[index] updatedEducations[index].duration = calculateDuration( startDate, endDate, isCurrent ) } setEducations(updatedEducations) } // Handle removing a specific skill const addEducation = () => { setShowEducationSection(true) setEducations([ ...educations, { institutionName: '', diplomaTitle: '', fieldOfStudy: '', startDate: '', endDate: '', isCurrent: false, duration: '', }, ]) } const removeEducation = (index) => { const filteredEducations = educations.filter((_, i) => i !== index) setEducations(filteredEducations) } // Expertise //handle Add Expertise const addExpertise = (index) => { setShowExpertiseSection(true) setExpertises([ ...expertises, { field: '', startDate: '', endDate: '', isCurrent: false, description: '', duration: '', duration: '', }, ]) } const handleExpertiseChange = (index, event) => { const updatedExpertises = [...expertises] const { name, value, type, checked } = event.target if (name === 'isCurrent') { updatedExpertises[index] = { ...updatedExpertises[index], [name]: checked, endDate: checked ? 'Present' : updatedExpertises[index].endDate, // Clear endDate if isCurrent is true } } else { updatedExpertises[index] = { ...updatedExpertises[index], [name]: value, } } // Update duration on date change or isCurrent toggle if (name === 'startDate' || name === 'endDate' || name === 'isCurrent') { const { startDate, endDate, isCurrent } = updatedExpertises[index] updatedExpertises[index].duration = calculateDuration( startDate, endDate, isCurrent ) } setExpertises(updatedExpertises) } const handleCustomFieldChange = (index, event) => { const updatedExpertises = [...expertises] updatedExpertises[index] = { ...updatedExpertises[index], customField: event.target.value, // Assuming you store the custom input in a separate attribute } setExpertises(updatedExpertises) } const removeExpertise = (index) => { const filteredExpertises = expertises.filter((_, i) => i !== index) setExpertises(filteredExpertises) } const handlePhoneChange = (phone) => { setFormData((prevFormData) => ({ ...prevFormData, phone: phone, })) } const validateForm = () => { const errors = {} // Validate photo if (!imagePreview) { // Assuming `imagePreview` is set when a photo is selected errors.photo = 'A profile photo is required.' console.log('photo') } if (!formData.firstName) { errors.firstName = 'First name is required' } if (!formData.lastName) { errors.lastName = 'Last name is required' } if (!formData.zipCode) { errors.zipCode = 'Zip name is required' } if (!formData.biography) { errors.bio = 'Biography is required' } if (formData.biography.length < 250) { errors.bioLength = 'Biography must be at least 250 charactére' } if (!formData.occupation) { errors.occupation = 'Occupation is required' } if (!formData.rate) { errors.rate = 'rate is required (you can change it later)' } // Validate experiences if (experiences.length === 0) { errors.experiences = 'At least one experience is required.' console.log('experience') } // Validate educations if (educations.length === 0) { errors.educations = 'At least one education is required.' console.log('education') } // Validate expertises if (expertises.length === 0) { errors.expertises = 'At least one expertise is required.' console.log('eexpertise') } // Validate languages if (formData.languagesSpoken.length < 1) { errors.languages = 'At least one language is required.' console.log('At least one language is required.') } setValidationErrors(errors) return Object.keys(errors).length === 0 } const handleSubmit = (e) => { e.preventDefault() // Prevent default form submission behavior setLoading(true) // if (validateForm()) { console.log('Form is valid. Submitting...') // Prepare data for submission, including formData, experiences, educations, expertises, and photo const submissionData = { ...formData, // Contains languagesSpoken,and other details experiences, educations, expertises, photo: formData.photo, // Ensure this correctly references the selected file } console.log(submissionData) let fileToUpload = formData.photo const data = new FormData() data.set('file', fileToUpload) try { console.log(0) let fileUrl fetch('/api/upload', { method: 'POST', body: data, // This is your request payload, for example, a FormData object }) .then((response) => { if (!response.ok) { throw new Error('Network response was not ok') } console.log({ response }) setLoading(false) return response.json() // Parses the response body as JSON }) .then((data) => { console.log(data) fileUrl = data.path // 'data' contains the parsed JSON object from the server response const fileName = data.fileName console.log(1) const expertData = { ...submissionData, // Include other form data here biography: biography, photoUrl: fileUrl, photoName: fileName, } console.log(2, { expertData }) const dataa = JSON.parse(JSON.stringify(expertData)) console.log(2, { dataa }) updateUser(userInfo.id, dataa) .then((expert) => { setLoading(false) console.log('Expert profile created:', expert) setSubmited(true) // Further actions upon successful creation }) .catch((error) => { setLoading(false) console.error('Error updating user profile:', error) }) }) .catch((error) => { setLoading(false) console.error('Error:', error) }) console.log(6) } catch (error) { setLoading(false) console.error('Error uploading file:', error) } // Submit the data here (API call or other means) // } else { // console.error("Form validation failed."); // } } console.log({ imagePreview }) const handleFileChange = (e) => { const file = e.target.files[0] if (file) { setFormData({ ...formData, photo: file }) setImagePreview(URL.createObjectURL(file)) } } const handleBiographyChange = (e) => { const inputText = e.target.value if (inputText.length <= maxCharCount) { setBiography(inputText) } } const handleAddVideoURL = (newURL) => { if (newURL && !videoURLs.includes(newURL)) { setVideoURLs((prevURLs) => [...prevURLs, newURL]) } } const handleRemoveVideoURL = (index) => { setVideoURLs((prevURLs) => prevURLs.filter((_, i) => i !== index)) } return (
) } export default ExpertProfileForm