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


const ProjectBanner = ( {project_data} ) =>
{
  const [showModal, setShowModal] = useState(false);
  const manageProject =  useHasUserPermission(MANAGE_PROJECT)
  const [ CurrentProject, setCurrentProject ] = useState( project_data )
  if (project_data == null) {
    return <span>incomplete project information</span>;
  }
  
  const handleShow = () => setShowModal(true);
  const handleClose = () => setShowModal(false);
 
  const handleFormSubmit = ( updatedProject ) =>
  {
   
         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" );
                    
                     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>
      {/* -------------------- */}
      <div className="col-12">
        <div className="card mb-6 pb-0">
          <div className="user-profile-header d-flex flex-column flex-lg-row text-sm-start text-center mb-2 ">
            <div className="flex-shrink-0 mt-1 mx-sm-0 px-2  mx-auto">
            
              <img
                src="../../assets/icons/civil-engineering.svg"
                alt="user image"
                className="d-block h-auto ms-0 ms-sm-6 rounded-3 user-profile-img project-banner-icon"
              ></img>
            </div>
            <div className="flex-grow-1 mt-1 mt-lg-1">
              <div className="d-flex align-items-md-end align-items-sm-start align-items-center justify-content-md-between justify-content-start mx-5 flex-md-row flex-column gap-4">
                <div className="user-profile-info">
                  <h4 className="mb-2 mt-lg-1">
                    {CurrentProject.name ? CurrentProject.name : "N/A"}
                  </h4>
                  <h6 className="mb-1 mt-lg-1">
                    Address:{" "}
                    {CurrentProject.projectAddress ? CurrentProject.projectAddress : "N/A"}
                  </h6>
                  <h6 className="mb-1 mt-lg-1">
                    Contact:{" "}
                    {CurrentProject.contactPerson ? CurrentProject.contactPerson : "N/A"}
                  </h6>
                  <h6 className="mb-1 mt-lg-1">
                    <span>
                      {" "}
                      Start Date:{" "}
                      {CurrentProject.startDate
                                         ? moment(CurrentProject.startDate).format("DD-MMM-YYYY")
                                         : "N/A"}
                    </span>
                    <span className="ms-5">
                      End Date:{" "}
                      {CurrentProject.endDate
                                         ? moment(CurrentProject.endDate).format("DD-MMM-YYYY")
                                         : "N/A"}
                    </span>
                  </h6>
                </div>
                <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
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default ProjectBanner;
