text: import React, { useContext, useEffect, useState } from "react";
  import { Head, InputBox } from "Components";
  import { freelancerProjectPortfolioUpdate } from "../API/FreelancerApi";
  import { jobSeekerProjectPortfolioUpdate } from "../API/EmploymentAPI";
  import { CustomError } from "./Toasts";
  import { crossSvg } from "Assets";
  import { X, Plus } from "react-feather";
  import { getBase64 } from "Utils/common";
  import UserContext from "Context/UserContext";
  import { navigate } from "@reach/router";
  import Img from "react-cool-img";
  
  export default function EditProject({
    setIsEditProjectOpen,
    selectedProjectData,
  }) {
    const user = useContext(UserContext);
  
    const [projectName, setProjectName] = useState(
      selectedProjectData.ProjectName
    );
    const [projectDescription, setProjectDescription] = useState(
      selectedProjectData.ProjectDescription
    );
    const [fileString, setFileString] = useState(
      selectedProjectData.JobSeekerUploads != undefined
        ? selectedProjectData.JobSeekerUploads != null &&
          selectedProjectData.JobSeekerUploads.length > 0
          ? selectedProjectData.JobSeekerUploads
          : []
        : selectedProjectData.FreelancerUploads != null &&
          selectedProjectData.FreelancerUploads.length > 0
        ? selectedProjectData.FreelancerUploads
        : []
    );
  
    const [newSelectedImages, setNewSelectedImages] = useState(null);
    const [isLoading, setIsLoading] = useState(false);
  
    const uploadedImagesArray = async (data) => {
      let imageObjectArray = [...fileString];
      let base64Images = [];
      for (let index = 0; index < data.length; index++) {
        let imageFile = data[index];
        await getBase64(imageFile, (result) => {
          let newObject = {
            imageFile: imageFile,
            base64: result,
          };
          base64Images.push(newObject);
        });
      }
      setTimeout(() => {
        for (let index = 0; index < base64Images.length; index++) {
          const element = base64Images[index];
          if (user.Role.Title === "JobSekker") {
            imageObjectArray.push({
              JobSeekerId: user.JobSeekerId,
              JobSeekerPortfolioId: selectedProjectData.Id,
              Type: "Employement",
              JobSeekerPortfolio: "JobSeekerPortfolio",
              Id: 0,
              UploadFilePath: element.base64,
              url: URL.createObjectURL(element.imageFile),
            });
          } else {
            imageObjectArray.push({
              FreelancerId: user.FreelancerId,
              FreelancerPortfolioId: selectedProjectData.Id,
              Type: "Freelancer",
              FreelancerPortfolio: "FreelancerPortfolio",
              Id: 0,
              UploadFilePath: element.base64,
              url: URL.createObjectURL(element.imageFile),
            });
          }
        }
        setFileString(imageObjectArray);
      }, 1500);
    };
  
    const updateProject = () => {
      if (
        selectedProjectData.JobSeekerId != null &&
        selectedProjectData.JobSeekerId != undefined
      )
        updateJobSeekerProjectPortfolio();
      else updateFreelancerProjectPortfolio();
    };
  
    const updateJobSeekerProjectPortfolio = () => {
      setIsLoading(true);
      const found = fileString.find((element) => element.Id == 0);
      let data = {
        Id: selectedProjectData.Id,
        ProjectDescription: projectDescription,
        ProjectName: projectName,
        JobSeekerId: selectedProjectData.JobSeekerId,
        JobSeekerUploads: found != undefined ? [found] : [],
        JobSeeker: "JobSeeker",
      };
      jobSeekerProjectPortfolioUpdate(data)
        .then((data) => {
          //CustomSuccess("Project updated successfully.");
          setIsLoading(false);
          setIsEditProjectOpen(false);
          navigate("/home-professional/project");
          // window.location.href = "/home-professional/project";
        })
        .catch((err) => {
          setIsLoading(false);
          CustomError("Failed to update project");
        });
    };
  
    const updateFreelancerProjectPortfolio = () => {
      setIsLoading(true);
      const found = fileString.find((element) => element.Id == 0);
      let data = {
        Id: selectedProjectData.Id,
        ProjectDescription: projectDescription,
        ProjectName: projectName,
        FreelancerId: selectedProjectData.FreelancerId,
        FreelancerUploads: found != undefined ? [found] : [],
        Freelancer: "Freelancer",
        // CreatedOn: moment().format("YYYY-MM-DD HH:mm:ss"),
      };
  
      freelancerProjectPortfolioUpdate(data)
        .then((data) => {
          //CustomSuccess("Project updated successfully.");
          setIsLoading(false);
          setIsEditProjectOpen(false);
          navigate("/home-freelancer/project");
          // window.location.href = "/home-freelancer/project";
        })
        .catch((err) => {
          setIsLoading(false);
          CustomError("Failed to update project");
        });
    };
  
    const removeImage = (data, index) => {
      var array = [...fileString]; // make a separate copy of the array
      if (index !== -1) {
        array.splice(index, 1);
        setFileString(array);
      }
    };
  
    const showImages = (images) => {
      if (images.UploadFilePath.includes("api")) {
        return process.env.REACT_APP_BASEURL.concat(images.UploadFilePath);
      } else {
        return images.url;
      }
    };
    useEffect(() => {
      document.body.style.overflow = "hidden";
      return () => {
        document.body.style.overflow = "auto";
      };
    }, []);
    return (
      <>
        <Head title="AIDApro | Edit Project" description="Edit Project" />
        <div className="pupup__container">
          <div
            className="pupup__container__from animate__animated animate__slideInDown"
            style={{ maxWidth: 700 }}
          >
            <button
              className="pupup__container__from__button"
              type="button"
              onClick={() => {
                setIsEditProjectOpen(false);
              }}
              title="close popup"
            >
              {crossSvg}
            </button>
            <div className="pupup__container__from__wrapper">
              <div className="pupup__container__from__wrapper__header">
                <div className="pupup__container__from__wrapper__header__content">
                  <div className="pupup__container__from__wrapper__header__content__heading">
                    Edit Project
                  </div>
                </div>
              </div>
              <div className="pupup__container__from__wrapper__form__reverse">
                <div
                  className="pupup__container__from__wrapper__form__col"
                  style={{
                    flexDirection: "column",
                    alignItems: "flex-start",
                    width: "100%",
                  }}
                >
                  <InputBox
                    variant="simple"
                    placeholder="Project Name"
                    style={{ width: "100%" }}
                    value={projectName}
                    onChange={(e) => {
                      setProjectName(e.currentTarget.value);
                    }}
                  />
                  <InputBox
                    variant="textarea"
                    placeholder="Description"
                    value={projectDescription}
                    onChange={(e) => {
                      setProjectDescription(e);
                    }}
                    style={{
                      width: "100%",
                      maxWidth: "700px",
                      marginBottom: "1em",
                    }}
                  />
                </div>
                {/* <UploadImgInput
                  fileString={fileString}
                  uploadedImagesArray={uploadedImagesArray}
                /> */}
              </div>
              <div
                className="pupup__container__from__wrapper__form__col"
                style={{ marginBottom: "1em" }}
              >
                <div className="pupup__container__from__wrapper__form__col__image__uploader">
                  <input
                    type="file"
                    accept=".png, .jpg, .jpeg"
                    className="pupup__container__from__wrapper__form__col__image__uploader__input"
                    onClick={(event) => (event.target.value = null)}
                    onChange={(e) => uploadedImagesArray(e.currentTarget.files)}
                  />
                  <Plus size={30} color="currentColor" />
                </div>
                {fileString.length > 0
                  ? fileString.map((item, i) => (
                      <div
                        key={i}
                        className="pupup__container__from__wrapper__form__col__image__uploader__img__wrapper"
                      >
                        <button
                          className="pupup__container__from__wrapper__form__col__image__uploader__img__wrapper__button"
                          onClick={() => removeImage(item, i)}
                        >
                          <X size={20} color="currentColor" />
                        </button>
                        <Img
                          loading="lazy"
                          src={showImages(item)}
                          className="pupup__container__from__wrapper__form__col__image__uploader__img"
                        />
                      </div>
                    ))
                  : null}
              </div>
              <div className="pupup__container__from__wrapper__cta">
                <button
                  type="submit"
                  className="header__nav__btn btn__secondary"
                  style={{
                    height: "50px",
                    width: "180px",
                  }}
                  onClick={() => {
                    updateProject();
                  }}
                  title="edit project"
                >
                  Save Changes
                </button>
              </div>
            </div>
          </div>
        </div>
      </>
    );
  }
  