import React, { useEffect, useState } from "react";
import moment from "moment";
import { getProjectStatusName } from "../../utils/projectStatus";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { MANAGE_PROJECT } from "../../utils/constants";
import { cacheData, getCachedData } from "../../slices/apiDataManager";
import ManageProjectInfo from "./ManageProjectInfo";
import ProjectRepository from "../../repositories/ProjectRepository";
import showToast from "../../services/toastService";

const AboutProject = ({ data }) => {
  const [CurrentProject, setCurrentProject] = useState(data);
  const [showModal, setShowModal] = useState(false);

  useEffect(() => {
    setCurrentProject(data);
  }, [data]);

  const manageProject = useHasUserPermission(MANAGE_PROJECT);

  const handleShow = () => setShowModal(true);
  const handleClose = () => setShowModal(false);
  const handleFormSubmit = (updatedProject, setLoading) => {
    if ( CurrentProject?.id )
    {
      
      ProjectRepository.updateProject(CurrentProject.id, updatedProject)
        .then((response) => {
          const updatedProjectData = {
            ...CurrentProject,
            ...response.data,
            building: CurrentProject.building,
          };
          setCurrentProject(updatedProject);

          cacheData(`projectinfo-${CurrentProject.id}`, updatedProjectData);
          const projects_list = getCachedData("projectslist");
          if (projects_list) {
            const updatedProjectsList = projects_list.map((project) =>
              project.id === CurrentProject.id
                ? {
                    ...project,
                    ...response.data,
                    //  tenant:project.tenant
                  }
                : project
            );

            cacheData("projectslist", updatedProjectsList);
          }

          showToast( "Project updated successfully.", "success" );
          setLoading(false);
          setShowModal(false);
        })
        .catch((error) => {
          showToast(error.message, "error");
        });
    }
  };
  return (
    <>
      <div
        className={`modal fade ${showModal ? "show" : ""}`}
        tabIndex="-1"
        role="dialog"
        style={{ display: showModal ? "block" : "none" }}
        aria-hidden={!showModal}
      >
        <ManageProjectInfo
          project={CurrentProject}
          handleSubmitForm={handleFormSubmit}
          onClose={handleClose}
        ></ManageProjectInfo>
      </div>
      {data && (
        <div className="card mb-6">
          <div className="card-header text-start">
            <h6 className="card-action-title mb-0">
              {" "}
              <i className="fa fa-building rounded-circle text-primary"></i>
              <span className="ms-2">Project Profile</span>
            </h6>
          </div>
          <div className="card-body">
            <ul className="list-unstyled my-3 ps-2">
              <li className="d-flex align-items-center mb-3">
                <i className="bx bx-cog"></i>
                <span className="fw-medium mx-2">Name:</span>{" "}
                <span>{data.name}</span>
              </li>
              <li className="d-flex align-items-center mb-3">
                <i className="bx bx-fingerprint"></i>
                <span className="fw-medium mx-2">Nick Name:</span>{" "}
                <span> {data.shortName} </span>
              </li>
              <li className="d-flex align-items-center mb-3">
                <i className="bx bx-check"></i>
                <span className="fw-medium mx-2">Start Date:</span>{" "}
                <span>
                  {data.startDate
                    ? moment(data.startDate).format("DD-MMM-YYYY")
                    : "N/A"}
                </span>
              </li>
              <li className="d-flex align-items-center mb-3">
                <i className="bx bx-stop-circle"></i>{" "}
                <span className="fw-medium mx-2">End Date:</span>{" "}
                <span>
                  {data.endDate
                    ? moment(data.endDate).format("DD-MMM-YYYY")
                    : "N/A"}
                </span>
              </li>
              <li className="d-flex align-items-center mb-3">
                <i className="bx bx-trophy"></i>
                <span className="fw-medium mx-2">Status:</span>{" "}
                <span>{getProjectStatusName(data.projectStatusId)}</span>
              </li>
              <li className="d-flex align-items-center mb-3">
                <i className="bx bx-user"></i>
                <span className="fw-medium mx-2">Contact:</span>{" "}
                <span>{data.contactPerson}</span>
              </li>
              <li className="d-flex flex-column align-items-start mb-3">
                <div className="d-flex align-items-center">
                  <i className="bx bx-flag"></i>
                  <span className="fw-medium mx-2">Address:</span>
                  {data.projectAddress?.length <= 20 && (
                    <span>{data.projectAddress}</span>
                  )}
                </div>
                {data.projectAddress?.length > 20 && (
                  <div className="ms-4 text-start">{data.projectAddress}</div>
                )}
              </li>

              <li className="d-flex justify-content-center mb-3">
                {manageProject && (
                  <button
                    type="button"
                    className={`btn btn-sm btn-primary ${
                      !manageProject && "d-none"
                    }`}
                    data-bs-toggle="modal"
                    data-bs-target="#edit-project-modal"
                    onClick={handleShow}
                  >
                    Modify Details
                  </button>
                )}
              </li>
            </ul>
          </div>
        </div>
      )}

      {!data && <span>loading...</span>}
    </>
  );
};

export default AboutProject;
