import React,{useState,useEffect} from "react";
import moment from "moment";
import { getDateDifferenceInDays } from "../../utils/dateUtils";
import { useNavigate } from "react-router-dom";
import {useProjectDetails} from "../../hooks/useProjects";
import ManageProjectInfo from "./ManageProjectInfo";
import ProjectRepository from "../../repositories/ProjectRepository";
import {cacheData, getCachedData} from "../../slices/apiDataManager";
import showToast from "../../services/toastService";
import {useHasUserPermission} from "../../hooks/useHasUserPermission";
import {MANAGE_PROJECT} from "../../utils/constants";



const ProjectCard = ( {projectData} ) =>
{
  
  const[projectInfo,setProjectInfo] = useState(projectData)
  const navigate = useNavigate()
  const {projects_Details, loading} = useProjectDetails( projectData.id )
  const [ showModal, setShowModal ] = useState( false );
  const ManageProject  = useHasUserPermission(MANAGE_PROJECT)
  
  const handleShow = () => setShowModal(true);
  const handleClose = () => setShowModal( false );
  
  const getProjectStatusName = (statusId) => {
    switch (statusId) {
      case 1:
        return "Active";
      case 2:
        return "On Hold";
      case 3:
        return "Suspended";
      case 4:
        return "Inactive";
      case 5:
        return "Completed";
    }
  };

  const getProjectStatusColor = (statusId) => {
    switch (statusId) {
      case 1:
        return "bg-label-success";
      case 2:
        return "bg-label-warning";
      case 3:
        return "bg-label-info";
      case 4:
        return "bg-label-secondary";
      case 5:
        return "bg-label-dark";
    }
  };

  const handleViewProject = (e) => {
    navigate(`/projects/${projectData.id}`)
  };


  
  const handleFormSubmit = ( updatedProject ) =>
    {
           if ( projectInfo?.id )
              {
                   ProjectRepository.updateProject(projectInfo.id,updatedProject).then( ( response ) =>
                   { 
                     const updatedProjectData = {
                       ...projectInfo, 
                       ...response.data, 
                       building:projects_Details.building, 
                     };
                     setProjectInfo( updatedProject )
                     if ( getCachedData( `projectinfo-${ projectInfo.id }` ) )
                     {
                     cacheData( `projectinfo-${ projectInfo.id }`, updatedProjectData );
                       
                     }
                     const projects_list = getCachedData( "projectslist" );
                     if ( projects_list )
                     {  
                      const updatedProjectsList = projects_list.map(project => 
                        project.id == projectInfo.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={projects_Details} 
            handleSubmitForm={handleFormSubmit}
            onClose={handleClose}
          ></ManageProjectInfo>
      </div>

    <div className="col-md-6 col-lg-4 col-xl-4 order-0 mb-4">
      <div className="card cursor-pointer">
        <div className="card-header pb-4">
          <div className="d-flex align-items-start">
            <div className="d-flex align-items-center">
              <div className="avatar me-4">
                <i
                  className="rounded-circle bx bx-building-house"
                  style={{ fontSize: "xx-large" }}
                ></i>
              </div>
              <div className="me-2">
                <h5 className="mb-0">
                  <a
                    className="stretched-link text-heading"
                  
                    onClick={handleViewProject}
                  >
                    {projectInfo.name}
                  </a>
                </h5>
                <div className="client-info text-body">
                  <span className="fw-medium">Client: </span>
                  <span>{projectInfo.contactPerson}</span>
                </div>
              </div>
            </div>
            <div className={`ms-auto ${!ManageProject && 'd-none'}`}>
              <div className="dropdown z-2">
                <button
                  type="button"
                  className="btn btn-icon btn-text-secondary rounded-pill dropdown-toggle hide-arrow p-0"
                  data-bs-toggle="dropdown"
                  aria-expanded="false"
                >
                  <i className="bx bx-dots-vertical-rounded bx-sm text-muted"></i>
                </button>
                <ul className="dropdown-menu dropdown-menu-end">
                  <li>
                    <a
                      aria-label="click to  View details"
                      className="dropdown-item"
                      onClick={handleViewProject}
                    >
                      <i className="bx bx-detail me-2"></i>
                      <span className="align-left">View details</span>
                    </a>
                  </li>
                  <li    data-bs-toggle="modal"
                          data-bs-target="#edit-project-modal"
                          onClick={handleShow}>
                    <a
                      className="dropdown-item"
                    >
                      <i className="bx bx-pencil me-2"></i>
                        <span className="align-left"
                       >Modify</span>
                    </a>
                  </li>

                  <li>
                    <a className="dropdown-item" >
                      <i className="bx bx-task me-2"></i>
                      <span className="align-left">Activities</span>
                    </a>
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </div>
        <div className="card-body pb-1">
          <div className="d-flex align-items-center flex-wrap">
            <div className="text-start mb-4">
              <p className="mb-1">
                <span className="text-heading fw-medium">Start Date: </span>
                {projectInfo.startDate
                  ? moment(projectInfo.startDate).format("DD-MMM-YYYY")
                  : "NA"}
              </p>
              <p className="mb-1">
                <span className="text-heading fw-medium">Deadline: </span>

                {projectInfo.endDate
                  ? moment(projectInfo.endDate).format("DD-MMM-YYYY")
                  : "NA"}
              </p>
          <p className="mb-0">{projectInfo.projectAddress}</p>

            </div>
            
          </div>
        </div>
        <div className="card-body border-top">
          <div className="d-flex align-items-center mb-4">
            <p className="mb-0">
              <span
                className={
                  `badge rounded-pill ` +
                  getProjectStatusColor(projectInfo.projectStatusId)
                }
              >
                {getProjectStatusName(projectInfo.projectStatusId)}
              </span>
            </p>{" "}
            <span className="badge bg-label-success ms-auto">
              {projectInfo.startDate &&
                projectInfo.endDate &&
                getDateDifferenceInDays(
                  projectInfo.startDate,
                  projectInfo.endDate
                )}{" "}
              Days left
            </span>
          </div>
          <div className="d-flex justify-content-between align-items-center mb-2">
            <small className="text-body">Task: 290/344</small>
            <small className="text-body">95% Completed</small>
          </div>
          <div className="progress mb-4 rounded" style={{ height: "8px" }}>
            <div
              className="progress-bar rounded"
              role="progressbar"
              style={{ width: "95%" }}
              aria-valuenow="95"
              aria-valuemin="0"
              aria-valuemax="100"
            ></div>
          </div>
          <div className="d-flex align-items-center">
            <div className="d-flex align-items-center">
            </div>
            <div className="ms-auto">
              <a
            
                className="text-muted d-flex align-items-center"
              >
                <i className="bx bx-chat me-1"></i> 15
              </a>
            </div>
          </div>
        </div>
      </div>
      </div>
      </>
  );
};

export default ProjectCard;
