'use client'

import { countries } from '@/app/expertForm/utils/listOfCountries'
import { areasOfExpertise } from '@/app/expertForm/utils/listOfExpertise'
import { listOfLanguages } from '@/app/expertForm/utils/listOfLanguages'
import { calculateDuration, calculateProfileCompletion, determineProgressBarColor } from '@/lib/utils'
import { ChevronDownIcon, ChevronUpIcon } from '@heroicons/react/24/outline'
import ProgressBar from '@ramonak/react-progress-bar'
import { useEffect, useState } from 'react'
import { SubmitHandler, useFieldArray, useForm } from "react-hook-form"
import PhoneInput from 'react-phone-number-input'
import 'react-phone-number-input/style.css'
import { updateUser } from './action'
import { AccountInfo, UserInfoType } from './types'
import { CitySelect, CountrySelect, StateSelect } from "react-country-state-city";
import "react-country-state-city/dist/react-country-state-city.css";
import VerificationBadge from '@/components/verification-badge'

const ExpertProfileForm = ({ userInfo }: { userInfo: UserInfoType }) => {

  // states 
  const [submitted, setSubmitted] = useState(false)
  const [loading, setLoading] = useState(false)

  // country-state-city selector
  const [currentCountry, setCurrentCountry] = useState<any>(null);
  const [currentState, setCurrentState] = useState<any>(null);
  const [currentCity, setCurrentCity] = useState<any>(null);
  const [hasCities, setHasCities] = useState(true);

  // casting the startDate and endDate to undefined to solve type mismatch
  const undfExperiences = userInfo.experiences.map(exp => ({ ...exp, startDate: exp.startDate?.toISOString().split('T')[0] ?? undefined, endDate: exp.endDate?.toISOString().split('T')[0] ?? undefined }))
  const undfExpertises = userInfo.expertises.map(exp => ({ ...exp, startDate: exp.startDate?.toISOString().split('T')[0] ?? undefined, endDate: exp.endDate?.toISOString().split('T')[0] ?? undefined }))
  const undfEducation = userInfo.educations.map(exp => ({ ...exp, startDate: exp.startDate?.toISOString().split('T')[0] ?? undefined, endDate: exp.endDate?.toISOString().split('T')[0] ?? undefined }))

  const {
    register,
    handleSubmit,
    watch,
    setValue,
    getValues,
    control,
    formState: { errors },
  } = useForm<AccountInfo>({
    defaultValues: {
      email: userInfo.email,
      lastName: userInfo.lastName ?? '',
      firstName: userInfo.firstName ?? '',
      username: userInfo.userName ?? '',
      phone: userInfo.phone ?? '',
      state: userInfo.state ?? '',
      city: userInfo.city ?? '',
      role: userInfo.role ?? "",
      zipCode: userInfo.zipcode ?? '',
      rate: userInfo.rate ?? '',
      countryOfResidence: userInfo.countryOfResidence ?? "",
      languagesSpoken: userInfo.languagesSpoken ?? [],
      expertises: undfExpertises ?? [],
      occupation: userInfo.role ?? '',
      dateOfBirth: userInfo.dateOfBirth?.toISOString().split('T')[0] ?? undefined,
      photoUrl: null,
      biography: userInfo.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 ?? '',
      experiences: undfExperiences ?? [],
      educations: undfEducation ?? [],
      videos: userInfo.videos ?? [],
    }
  })

  // array fields
  const { fields: experiencesFields, append: appendExperience, remove: removeExperience } = useFieldArray({
    control,
    name: "experiences",
  });

  const { fields: educationFields, append: appendEducation, remove: removeEducation } = useFieldArray({
    control,
    name: "educations",
  });

  const { fields: expertisesFields, append: appendExpertise, remove: removeExpertise } = useFieldArray({
    control,
    name: "expertises",
  });

  const onSubmit: SubmitHandler<AccountInfo> = async (data) => {
    setSubmitted(false);
    setLoading(true);

    const fileToUpload = getValues("photo");

    if (fileToUpload && fileToUpload instanceof File) {
      const imageData = new FormData();
      imageData.append("file", fileToUpload);

      try {
        const response = await fetch("/api/upload", {
          method: "POST",
          body: imageData, // Use the correct FormData object
        });

        const result = await response.json();
        if (result.success) {
          console.log("File uploaded successfully:", result.path);

          // Attach the uploaded file path to the user data
          data.photo = result.path;
          data.imageName = result.fileName;
          setValue("imageName", result.path);
        } else {
          console.error("File upload failed");
        }
      } catch (error) {
        console.error("Error uploading file:", error);
      }
    }

    // reset the photo property
    setValue('photo', undefined)

    // formate all the dates properly
    const formatDate = (date?: string | Date) =>
      date ? new Date(date) : undefined;

    const formattedData = {
      ...data,
      dateOfBirth: formatDate(data.dateOfBirth),
      experiences: data.experiences?.map((experience) => ({
        ...experience,
        startDate: formatDate(experience.startDate),
        endDate: formatDate(experience.endDate),
      })),
      expertises: data.expertises?.map((expertise) => ({
        ...expertise,
        startDate: formatDate(expertise.startDate),
        endDate: formatDate(expertise.endDate),
      })),
      educations: data.educations?.map((education) => ({
        ...education,
        startDate: formatDate(education.startDate),
        endDate: formatDate(education.endDate),
      })),
    };

    try {
      console.log("formattedData")
      console.log(formattedData)
      await updateUser(userInfo.id, formattedData);
      setLoading(false)
      setSubmitted(true)
    } catch (error) {
      console.error(error);
    }
  };


  const [imagePreview, setImagePreview] = useState('')
  const [selectedLanguage, setSelectedLanguage] = useState<{ name: string }>()

  const [showExperienceSection, setShowExperienceSection] = useState(true) // State to track the visibility of the experience section
  const [showEducationSection, setShowEducationSection] = useState(true) // State to track the visibility of the experience section
  const [showExpertiseSection, setShowExpertiseSection] = useState(true) // State to track the visibility of the experience section

  const maxCharCount = 380 // Example limit similar to a tweet  const [newExpertise, setNewExpertise] = useState('')

  const profileCompletion = calculateProfileCompletion(userInfo)

  const toggleExperienceSection = () => {
    setShowExperienceSection((prevShow) => !prevShow)
  }

  const toggleExpertiseSection = () => {
    setShowExpertiseSection((prevShow) => !prevShow)
  }

  const toggleEducationSection = () => {
    setShowEducationSection((prevShow) => !prevShow)
  }

  const getImage = () => {
    let imageUrl;

    if (imagePreview) {
      imageUrl = imagePreview;
    } else if (userInfo.imageName) {
      imageUrl = `${process.env.NEXT_PUBLIC_WEBSITE_URL}/api/serveFiles?filename=${encodeURIComponent(userInfo.imageName)}`;
    } else {
      imageUrl = userInfo?.imageUrl;
    }

    return imageUrl;
  }

  const handleFileChange = (e) => {
    const file = e.target.files[0]
    if (file) {
      setValue("photo", file);
      setValue("photoUrl", URL.createObjectURL(file));
      setImagePreview(URL.createObjectURL(file))
    }
  }


  const uploadFile = async (file: File) => {
    const formData = new FormData();
    formData.append('file', file);

    const response = await fetch('/api/upload', {
      method: 'POST',
      body: formData,
    });

    const data = await response.json();
    if (!data.success) throw new Error('Upload failed');
    return data;
  };

  const languagesSpokenList = watch("languagesSpoken");
  const videos = watch("videos");


  // set the currency country / state / city
  useEffect(() => {
    setCurrentCountry({ name: userInfo.countryOfResidence })
    setCurrentState({ name: userInfo.state })
    setCurrentCity({ name: userInfo.city })
  }, [])

  return (
    <form
      onSubmit={handleSubmit(onSubmit)}
      className="space-y-6 p-8  shadow rounded-lg max-w-4xl mx-auto   bg-blue-50 "
    >
      <p className="w-full text-center text-lg font-semibold mb-4 ">
        Profile completion
      </p>
      <ProgressBar
        completed={profileCompletion}
        bgColor={determineProgressBarColor(profileCompletion)}
        baseBgColor="#e0e0de"
        height="30px"
        width="70%"
        margin="auto"
        borderRadius="5px"
        labelColor="#ffffff"
      />

      <div>
        {userInfo.isExpert && !userInfo.imageName && (
          <p className="font-semibold text-red-500">
            - You need a profile picture to
            {userInfo.isExpert
              ? 'start accepting calls'
              : 'start making calls'}{' '}
          </p>
        )}
        {!userInfo.firstName && (
          <p className="font-semibold text-red-500">
            - You need to complete your first name to
            {userInfo.isExpert
              ? ' start accepting calls'
              : ' start making calls'}
          </p>
        )}
        {!userInfo.lastName && (
          <p className="font-semibold text-red-500">
            - You need complete your last name to
            {userInfo.isExpert
              ? ' start accepting calls'
              : ' start making calls'}
          </p>
        )}
        {userInfo.isExpert && !userInfo.phone && (
          <p className="font-semibold text-red-500">
            - You need add a phone number to start accepting calls
          </p>
        )}
        {!userInfo.countryOfResidence && (
          <p className="font-semibold text-red-500">
            - You need to add a country of residence to
            {userInfo.isExpert
              ? ' start accepting calls'
              : ' start making calls'}
          </p>
        )}

        {!userInfo.role && (
          <p className="font-semibold text-red-500">
            - You need to add your current occupation to
            {userInfo.isExpert
              ? ' start accepting calls'
              : ' start making calls'}
          </p>
        )}
        {userInfo.isExpert && !userInfo.biography && (
          <p className="font-semibold text-red-500">
            - You need add a biography to start accepting calls
          </p>
        )}
        {!(userInfo.languagesSpoken.length > 0) && (
          <p className="font-semibold text-red-500">
            - You need to add at least one language to
            {userInfo.isExpert
              ? ' start accepting calls'
              : ' start making calls'}
          </p>
        )}
        {userInfo.isExpert && !(userInfo.experiences.length > 0) && (
          <p className="font-semibold text-red-500">
            - You need at least one Experience to start accepting calls
          </p>
        )}
        {userInfo.isExpert && !(userInfo.educations.length > 0) && (
          <p className="font-semibold text-red-500">
            - You need at least one Education to start accepting calls
          </p>
        )}

        {userInfo.isExpert && !(userInfo.expertises.length > 0) && (
          <p className="font-semibold text-red-500">
            - You need at least one Expertise to start accepting calls
          </p>
        )}
      </div>

      <div className="!mt-16">
        <label
          htmlFor="profilePicture"
          className="block text-lg font-medium text-gray-700"
        >
          Profile Picture *
        </label>
        {/* {validationErrors.photo && (
          <p className="text-red-500 text-xs italic">
            {validationErrors.photo}
          </p>
        )} */}
        <div className="mt-4 flex items-center justify-center">
          <div className="inline-block relative h-24 w-24 rounded-full bg-gray-100">
            {imagePreview || userInfo.imageName || userInfo.imageUrl ? (
              <img
                src={getImage()}
                alt="Profile Preview"
                className="h-full w-full text-gray-300"
              />
            ) : (
              <svg
                className="h-full w-full text-gray-300"
                fill="currentColor"
                viewBox="0 0 24 24"
              >
                <path d="M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z" />
              </svg>
            )}
            <VerificationBadge status={userInfo.idVerified ? "verified" : "unverified"} />
          </div>
          <input
            id="profilePicture"
            name="profilePicture"
            type="file"
            className="hidden"
            onChange={handleFileChange}
          />
          <label
            htmlFor='profilePicture'
            className="cursor-pointer ml-5 bg-blue-500 hover:bg-blue-700 text-white font-medium py-2 px-4 rounded"
          >
            {imagePreview ? 'Change' : 'Upload'}
          </label>
        </div>
      </div>



      {/* Name Field */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6 px-2 py-2 rounded-md">
        <div className="">
          <label
            htmlFor="firstName"
            className="block text-lg font-semibold text-gray-700  "
          >
            First Name *
          </label>
          <input
            type="text"
            id="firstName"
            placeholder="First name"
            required
            {...register("firstName")}
            className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-blue-500 focus:border-blue-500"
          />
        </div>
        <div>
          <label
            htmlFor="lastName"
            className="block text-lg font-semibold text-gray-700"
          >
            Last Name *
          </label>
          <input
            type="text"
            {...register("lastName")}
            id="lastName"
            placeholder="Last name"
            required
            className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-blue-500 focus:border-blue-500"
          />
        </div>
      </div>


      {/* additional field */}
      {/* Username Field */}
      <div className="grid grid-cols-1 md:grid-cols-2 gap-6  px-2 py-2 rounded-md">
        <div>
          <label
            htmlFor="username"
            className="block text-lg font-semibold text-gray-700"
          >
            Username
          </label>
          <input
            type="text"
            {...register("username")}
            id="username"
            className="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-blue-500 focus:border-blue-500"
            placeholder="Your Username"
          />
        </div>
        <div>
          <label
            htmlFor="phone"
            className="block text-lg font-semibold text-gray-700"
          >
            Phone *
          </label>
          <div className="mt-1 relative rounded-md shadow-sm">
            <PhoneInput
              placeholder="Enter phone number"
              className="block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-blue-500 focus:border-blue-500"
              // @ts-ignore
              value={watch("phone")}
              onChange={(phone) => { setValue("phone", phone) }}
            />
          </div>
        </div>
      </div>

      {/* Email */}
      <div className="space-y-6   px-2 py-4 rounded-md ">
        <div>
          <label
            htmlFor="email"
            className="block text-lg font-semibold text-gray-700"
          >
            Email *
          </label>
          <input
            type="text"
            {...register("email")}
            id="email"
            className="mt-1 block py-1 px-2 w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-500 focus:ring-opacity-50"
            required
          />
        </div>

      </div>

      {/* Date of Birth Field */}
      <div>
        <label
          htmlFor="dateOfBirth"
          className="block text-lg font-semibold text-gray-700"
        >
          Date of Birth
        </label>

        <input
          {...register("dateOfBirth", { valueAsDate: true })}
          type="date"
          id="dateOfBirth"
          className="mt-1 block py-1 px-2 w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-500 focus:ring-opacity-50"
        />
      </div>


      {/* Country of Residence Field */}
      <div>
        <label
          htmlFor="countryOfResidence"
          className="block text-lg font-semibold text-gray-700"
        >
          Country of Residence *
        </label>

        <CountrySelect
          containerClassName="form-group"
          inputClassName="mt-1  py-1 px-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-500 focus:ring-opacity-50"
          onChange={(_country) => {
            setValue("countryOfResidence", _country?.name)
            setCurrentCountry(_country);
            setCurrentState({ name: "" });
            setCurrentCity({ name: "" });
          }}
          defaultValue={currentCountry}
          placeHolder="Select Country"
        />
      </div>

      {/* State Input */}
      <div>
        <label
          htmlFor="state"
          className="block text-lg font-semibold text-gray-700"
        >
          State
        </label>
        <StateSelect
          countryid={currentCountry?.id}
          containerClassName="form-group"
          inputClassName="mt-1  py-1 px-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-500 focus:ring-opacity-50"
          onChange={(_state) => {
            setCurrentState(_state)
            setHasCities(_state?.hasCities);
            setValue("state", _state?.name);
          }}
          defaultValue={currentState}
          placeHolder="Select State"
        />
      </div>

      {/* City Input */}
      <div>
        <label
          htmlFor="city"
          className="block text-lg font-semibold text-gray-700"
        >
          City *
        </label>
        <CitySelect
          countryid={currentCountry?.id}
          stateid={currentState?.id}
          disabled={!hasCities}
          containerClassName="form-group"
          inputClassName="mt-1  py-1 px-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-500 focus:ring-opacity-50"
          onChange={(_city) => {
            setCurrentCity(_city)
            setValue("city", _city?.name);
          }}
          defaultValue={currentCity}
          placeHolder="Select City"
        />
      </div>
      {/* Zip Code Input */}
      <div>
        <label
          htmlFor="zipCode"
          className="block text-lg font-semibold text-gray-700"
        >
          Zip Code
        </label>
        <input
          type="text"
          {...register("zipCode")}
          id="zipCode"
          className="mt-1  py-1 px-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-500 focus:ring-opacity-50"
        />
      </div>

      {/* Languages Spoken Field */}
      <div className="space-y-6 px-2 py-4 rounded-md">
        {/* Languages Spoken Field */}
        <div className="md:col-span-2">
          <label
            htmlFor="languagesSpoken"
            className="block text-lg font-semibold text-gray-700"
          >
            Languages Spoken *
          </label>
          <div className="mt-1  py-1 px-2 flex flex-wrap items-center border border-gray-300 rounded-md p-2">
            {languagesSpokenList?.map((language, index) => (
              <div
                key={index}
                className="flex items-center m-1 bg-blue-100 rounded px-2 py-1 text-sm"
              >
                {
                  language.name
                }
                <button
                  type="button"
                  onClick={() => {
                    const newList = languagesSpokenList.filter(item => item.name != language.name)
                    setValue("languagesSpoken", [...newList]);
                  }
                  }
                  className="ml-2 text-blue-500 hover:text-blue-700"
                >
                  &times;
                </button>
              </div>
            ))}
            <select
              value={selectedLanguage?.name}
              onChange={(e) => {
                setSelectedLanguage({ name: e.target.value })
                setValue("languagesSpoken", [...languagesSpokenList, { name: e.target.value }]);
              }}
              className="mt-1  py-1 px-2 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-500 focus:ring-opacity-50"
            >
              <option value="">Select a language...</option>
              {listOfLanguages.map((language, index) => (
                <option key={index} value={language.name}>
                  {language.name}
                </option>
              ))}
            </select>
          </div>
          {/* <button
            type="button"
            onClick={() => {
              if (selectedLanguage) setValue("languagesSpoken", [...languagesSpokenList, selectedLanguage])
            }}
            className="ml-2 text-sm text-white bg-blue-500 hover:bg-blue-700 rounded px-2"
            disabled={!selectedLanguage}
          >
            Add
          </button> */}
        </div>

        {/* Occupation Field */}
        <div>
          <label
            htmlFor="occupation"
            className="block text-lg font-semibold text-gray-700"
          >
            Occupation (Your Job Title) *
          </label>
          <input
            type="text"
            {...register("occupation")}
            id="occupation"
            required
            className="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring focus:ring-blue-500 focus:ring-opacity-50"
          />
        </div>

        {/* Rate Field (Conditional Rendering for Experts) */}
        {userInfo.isExpert && (
          <div>
            <label
              htmlFor="rate"
              className="block text-lg font-semibold text-gray-700"
            >
              Rate {userInfo?.isExpert && '*'} (how much would you charge in
              euro / 45 minutes)
            </label>
            <input
              type="text"
              {...register("rate")}
              id="rate"
              required={userInfo?.isExpert}
              className="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring focus:ring-blue-500 focus:ring-opacity-50"
              placeholder="$ / 45 min"
            />
          </div>
        )}
      </div>
      {/* Biography Field */}
      <div className="md:col-span-2 px-2 py-4 rounded-md">
        <div className="bg-white shadow rounded-lg p-2 ">
          <label
            htmlFor="biography"
            className="block text-lg font-semibold text-gray-700"
          >
            Biography {userInfo?.isExpert && '*'} (250 charachtere minimum)
            <span className="block text-right text-xs font-semibold text-black">
              {/* {watch("biography").length}/{maxCharCount} characters */}
            </span>
          </label>
          <textarea
            {...register("biography")}
            id="biography"
            required={userInfo?.isExpert}
            rows={4}
            className="mt-2 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring focus:ring-blue-500 focus:ring-opacity-50"
            placeholder="Tell us more about yourself..."
          ></textarea>
        </div>
      </div>

      {/*  Experiences */}
      <div className="md:col-span-2 shadow rounded-lg  py-3 px-2 mb-6 ">
        <div className="flex justify-between items-center">
          <h3 className="text-lg font-semibold text-blue-600 mb-4">
            Experiences {userInfo?.isExpert && '*'}
          </h3>
          <button
            type="button"
            onClick={toggleExperienceSection}
            className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
          >
            {showExperienceSection ? (
              <ChevronUpIcon className="w-4 h-4" />
            ) : (
              <ChevronDownIcon className="w-4 h-4" />
            )}{' '}
          </button>
        </div>
        {showExperienceSection && (
          <>
            {experiencesFields.map((field, index) => {
              const isCurrentValue = watch(`experiences.${index}.isCurrent`);
              const startDateValue = watch(`experiences.${index}.startDate`) as Date;
              const endDateValue = watch(`experiences.${index}.endDate`) as Date;

              return (
                <div
                  key={field.id}
                  className="mb-5 p-4 border border-blue-200 rounded-lg"
                >
                  <div className="grid grid-cols-1 gap-4 mb-4">
                    <input
                      type="text"
                      {...register(`experiences.${index}.companyName`)}
                      placeholder="Company Name"
                      className="p-2 border rounded-md w-full"
                    />
                    <input
                      type="text"
                      {...register(`experiences.${index}.role`)}
                      placeholder="Role"
                      className="p-2 border rounded-md w-full"
                    />
                    <div className="flex gap-4">
                      <div className="flex flex-col">
                        <label htmlFor="startDate">Start Date</label>
                        <input
                          type="date"
                          {...register(`experiences.${index}.startDate`, { valueAsDate: true })}
                          className="p-2 border rounded-md w-full"
                        />
                      </div>

                      <div className="flex flex-col">
                        <label htmlFor="endDate">End Date</label>
                        <input
                          type="date"
                          {...register(`experiences.${index}.endDate`, { valueAsDate: true })}
                          className="p-2 border rounded-md w-full"
                          disabled={isCurrentValue}
                        />
                      </div>
                    </div>
                  </div>

                  <label className="flex items-center mb-4">
                    <input
                      type="checkbox"
                      {...register(`experiences.${index}.isCurrent`)}
                      onChange={(e) => {
                        setValue(`experiences.${index}.isCurrent`, e.target.checked);
                        if (e.target.checked) {
                          setValue(`experiences.${index}.endDate`, undefined);
                        }
                      }}
                      className="mr-2"
                    />
                    I am currently working in this role
                  </label>
                  <input
                    type="text"
                    readOnly
                    value={calculateDuration(startDateValue, endDateValue, isCurrentValue) || 'Duration'}
                    className="p-2 border rounded-md w-full bg-gray-100"
                  />

                  <textarea
                    placeholder="Description"
                    {...register(`experiences.${index}.description`)}
                    className="p-2 border rounded-md w-full mt-4"
                    rows={3}
                  ></textarea>

                  <button
                    type="button"
                    onClick={() => removeExperience(index)}
                    className="mt-4 text-red-500 hover:text-red-700 text-sm"
                  >
                    Remove
                  </button>
                </div>
              )
            })}
          </>
        )}
        <button
          onClick={() => {
            appendExperience({
              companyName: '',
              role: '',
              startDate: undefined,
              endDate: undefined,
              isCurrent: false,
              description: '',
            })
          }}
          type="button"
          className="mt-4 bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
        >
          Add Experiencesss
        </button>
      </div>

      {/* Education Section */}
      <div className="md:col-span-2 shadow rounded-lg  py-3 px-2 mb-6 mt-8">
        <div className="flex justify-between items-center">
          <h3 className="text-lg font-semibold text-blue-600 mb-4">
            Education {userInfo?.isExpert && '*'}
          </h3>
          <button
            type="button"
            onClick={toggleEducationSection}
            className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
          >
            {showEducationSection ? (
              <ChevronUpIcon className="w-4 h-4" />
            ) : (
              <ChevronDownIcon className="w-4 h-4" />
            )}
          </button>
        </div>

        {showEducationSection && (
          <>
            {/* Map over educations to display them */}
            {educationFields.map((field, index) => {
              const isCurrentValue = watch(`educations.${index}.isCurrent`);
              const startDateValue = watch(`educations.${index}.startDate`) as Date;
              const endDateValue = watch(`educations.${index}.endDate`) as Date;
              return (
                <div
                  key={field.id}
                  className="mb-5 p-4 border border-blue-200 rounded-lg"
                >
                  <div className="grid grid-cols-1 gap-4 mb-4">
                    <input
                      type="text"
                      {...register(`educations.${index}.institutionName`)}
                      placeholder="Institution Name"
                      className="p-2 border rounded-md w-full"
                    />
                    <input
                      type="text"
                      {...register(`educations.${index}.diplomaTitle`)}
                      placeholder="Diploma Title"
                      className="p-2 border rounded-md w-full"
                    />
                    <input
                      type="text"
                      placeholder="Field of Study"
                      {...register(`educations.${index}.fieldOfStudy`)}
                      className="p-2 border rounded-md w-full"
                    />
                    <div className="flex gap-4">
                      <input
                        type="date"
                        {...register(`educations.${index}.startDate`, { valueAsDate: true })}
                        className="p-2 border rounded-md w-full"
                      />
                      <input
                        type="date"
                        {...register(`educations.${index}.endDate`, { valueAsDate: true })}
                        className="p-2 border rounded-md w-full"
                        disabled={isCurrentValue}
                      />
                    </div>
                  </div>

                  <label className="flex items-center mb-4">
                    <input
                      type="checkbox"
                      onChange={(e) => {
                        setValue(`educations.${index}.isCurrent`, e.target.checked);
                        if (e.target.checked) {
                          setValue(`educations.${index}.endDate`, undefined);
                        }
                      }}
                      className="mr-2"
                    />
                    Currently enrolled
                  </label>

                  <input
                    type="text"
                    readOnly
                    value={calculateDuration(startDateValue, endDateValue, isCurrentValue) || 'Duration'}
                    className="p-2 border rounded-md w-full bg-gray-100"
                  />

                  <button
                    onClick={() => removeEducation(index)}
                    type="button"
                    className="mt-4 text-red-500 hover:text-red-700 text-sm"
                  >
                    Remove
                  </button>
                </div>
              )
            })}
          </>
        )}
        <button
          onClick={() => {
            appendEducation({
              institutionName: '',
              diplomaTitle: '',
              fieldOfStudy: '',
              startDate: undefined,
              endDate: undefined,
              isCurrent: false,
            })
          }}
          type="button"
          className="mt-4 bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
        >
          Add Education
        </button>
      </div>

      {/* Expertise Section */}
      {userInfo.isExpert && (
        <div className="md:col-span-2 shadow rounded-lg py-3 px-2 mb-6">
          <div className="flex justify-between items-center">
            <h3 className="text-lg font-semibold text-blue-600 mb-4">
              Expertise {userInfo?.isExpert && '*'}
            </h3>
            <button
              type="button"
              onClick={toggleExpertiseSection} // Ensure you have a function to toggle the visibility of the expertise section
              className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
            >
              {showExpertiseSection ? (
                <ChevronUpIcon className="w-4 h-4" />
              ) : (
                <ChevronDownIcon className="w-4 h-4" />
              )}{' '}
            </button>
          </div>

          {showExpertiseSection && (
            <>
              {expertisesFields?.map((expertise, index) => {
                const isCurrentValue = watch(`expertises.${index}.isCurrent`);
                const startDateValue = watch(`expertises.${index}.startDate`) as Date;
                const endDateValue = watch(`expertises.${index}.endDate`) as Date;

                return (
                  <div
                    key={index}
                    className="mb-5 p-4 border border-blue-200 rounded-lg"
                  >
                    <select
                      {...register(`expertises.${index}.field`)}
                      className="p-2 border rounded-md w-full mb-4"
                    >
                      <option value="">Select your expertise</option>
                      {areasOfExpertise.map((area) => (
                        <option key={area.name} value={area.name}>
                          {area.name}
                        </option>
                      ))}
                      <option value="Other">Other</option>
                    </select>

                    {expertise.field === 'Other' && (
                      <input
                        type="text"
                        placeholder="Please specify"
                        {...register(`expertises.${index}.customField`)}
                        className="p-2 border rounded-md w-full mb-4"
                      />
                    )}

                    <div className="flex gap-4">
                      <input
                        type="date"
                        {...register(`expertises.${index}.startDate`, { valueAsDate: true })}
                        className="p-2 border rounded-md w-full"
                      />
                      <input
                        type="date"
                        disabled={isCurrentValue}
                        {...register(`expertises.${index}.endDate`, { valueAsDate: true })}
                        className="p-2 border rounded-md w-full"
                      />
                    </div>

                    <label className="flex items-center mb-4">
                      <input
                        type="checkbox"
                        {...register(`expertises.${index}.isCurrent`)}
                        onChange={(e) => {
                          setValue(`expertises.${index}.isCurrent`, e.target.checked);
                          if (e.target.checked) {
                            setValue(`expertises.${index}.endDate`, undefined);
                          }
                        }}
                        className="mr-2"
                      />
                      Currently here
                    </label>

                    <input
                      type="text"
                      readOnly
                      value={calculateDuration(startDateValue, endDateValue, isCurrentValue) || 'Duration'}
                      className="p-2 border rounded-md w-full bg-gray-100 mb-4"
                    />

                    <textarea
                      {...register(`expertises.${index}.description`)}
                      placeholder="Description"
                      className="p-2 border rounded-md w-full"
                      rows={3}
                    ></textarea>

                    <button
                      onClick={() => removeExpertise(index)}
                      type="button"
                      className="mt-4 text-red-500 hover:text-red-700 text-sm"
                    >
                      Remove
                    </button>
                  </div>
                )
              }
              )}
            </>
          )
          }
          <button
            type="button"
            onClick={() => {
              appendExpertise({
                field: '',
                startDate: undefined,
                endDate: undefined,
                isCurrent: false,
                description: '',
              })
            }}
            className="mt-4 bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
          >
            Add Expertise
          </button>
        </div>
      )}

      {/* Social Media URLs */}
      <div className="md:col-span-2 shadow rounded-lg px-2 py-3 mb-6 !mt-14 ">
        <h3 className="text-xl font-semibold text-gray-900 mb-4">
          Social Links
        </h3>
        <div className="grid grid-cols-2 gap-4">
          <div>
            <label
              htmlFor="linkedInURL"
              className="block text-md font-semibold text-gray-700 mb-1"
            >
              LinkedIn Page URL {userInfo?.isExpert && '*'}
            </label>
            <input
              type="url"
              {...register("linkedInURL")}
              id="linkedInURL"
              required={userInfo?.isExpert}
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
            />
          </div>
          <div>
            <label
              htmlFor="youtubeURL"
              className="block text-md font-semibold text-gray-700 mb-1"
            >
              Youtube Page URL
            </label>
            <input
              type="url"
              id="youtubeURL"
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
              {...register("youtubeURL")}
            />
          </div>
          <div>
            <label
              htmlFor="instagramURL"
              className="block text-md font-semibold text-gray-700 mb-1"
            >
              Instagram Page URL
            </label>
            <input
              type="url"
              id="instagramURL"
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
              {...register("instagramURL")}
            />
          </div>
          <div>
            <label
              htmlFor="spotifyURL"
              className="block text-md font-semibold text-gray-700 mb-1"
            >
              Spotify Page URL
            </label>
            <input
              type="url"
              id="spotifyURL"
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
              {...register("spotifyURL")}
            />
          </div>

          <div>
            <label
              htmlFor="tiktokURL"
              className="block text-md font-semibold text-gray-700 mb-1"
            >
              TikTok Page URL
            </label>
            <input
              type="url"
              id="tiktokURL"
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
              {...register("tiktokURL")}
            />
          </div>
          <div>
            <label
              htmlFor="twitterURL"
              className="block text-md font-semibold text-gray-700 mb-1"
            >
              Twitter Page URL
            </label>
            <input
              type="url"
              id="twitterURL"
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
              {...register("twitterURL")}
            />
          </div>
          <div>
            <label
              htmlFor="amazonURL"
              className="block text-md font-semibold text-gray-700 mb-1"
            >
              Amazon Page URL
            </label>
            <input
              type="url"
              {...register("amazonURL")}
              id="amazonURL"
              className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
            />
          </div>
        </div>
      </div>
      <div className="md:col-span-2 shadow rounded-lg px-2 py-3 mb-6 !mt-14 ">
        <h3 className="text-xl font-semibold text-gray-900 mb-4">
          Other Links
        </h3>

        <div>
          <label
            htmlFor="websiteURL1"
            className="block text-md font-semibold text-gray-700 mb-1"
          >
            Website URL
          </label>
          <input
            type="url"
            {...register("websiteURL1")}
            id="websiteURL1"
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
          />
        </div>
        <div>
          <label
            htmlFor="websiteURL2"
            className="block text-md font-semibold text-gray-700 mb-1"
          >
            Additional Website URL
          </label>
          <input
            type="url"
            {...register("websiteURL2")}
            id="websiteURL2"
            className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-blue-500 focus:border-blue-500"
          />
        </div>
      </div>

      {/* video to be displayed on page */}
      <div>
        <label
          htmlFor="videoURL"
          className="block text-sm font-medium text-gray-700"
        >
          Add Video URL (videos to be displayed in your page)
        </label>
        <input
          type="url"
          id="videoURLInput"
          placeholder="https://"
          className="mt-1 block w-full px-4 py-2 border border-gray-300 rounded-t-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500"
          onKeyDown={(e) => e.key === 'Enter' && e.preventDefault()} // Prevent form submission on Enter
        />
        <button
          type="button"
          onClick={() => {
            const videoInput: HTMLInputElement = document.getElementById('videoURLInput') as HTMLInputElement;
            setValue("videos", [...videos ?? [], videoInput?.value])
            videoInput.value = '';
          }}
          className="mt-2 w-full inline-flex justify-center bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-b-md"
        >
          Add
        </button>
        {/* Displayed Video URLs with Remove Option */}
        <div className="mt-4">
          {videos?.map((url, index) => (
            <div
              key={index}
              className="bg-white shadow overflow-hidden rounded-md mt-2"
            >
              <div className="px-4 py-4 flex items-center justify-between sm:px-6">
                <div className="min-w-0 flex-1 sm:flex sm:items-center sm:justify-between">
                  <a
                    href={url}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="truncate hover:text-blue-600"
                  >
                    <span className="text-sm font-medium text-gray-500 truncate">
                      {url}
                    </span>
                  </a>
                </div>
                <div className="ml-4 flex-shrink-0">
                  <button
                    type="button"
                    onClick={() => {
                      const videos = getValues("videos") ?? []
                      setValue('videos', videos.filter((_, i) => i !== index))
                    }}
                    className="bg-red-500 hover:bg-red-700 text-white font-bold py-1 px-2 rounded"
                  >
                    Remove
                  </button>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Submit Button */}
      <div className="md:col-span-2 flex flex-col  items-end">
        {submitted && (
          <div className="text-green-500 text-base font-semibold">
            Updated Successfuly !!
          </div>
        )}

        <button
          type="submit"
          disabled={loading}
          style={{ backgroundColor: 'blue' }}
          className="  w-36 inline-flex bg-blue-700 justify-center mt-4 py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white  hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
        >
          {loading ? (
            <i className="icon-[tabler--loader-2] w-4 h-4 animate-spin duration-300 text-primary"></i>
          ) : (
            'Submit Profile'
          )}
        </button>
      </div>
    </form>
  )
}

export default ExpertProfileForm
