import React, { useEffect, useState } from "react";
import moment from "moment";
import { formatNumber, getDateDifferenceInDays } from "../../utils/dateUtils";
import { useNavigate } from "react-router-dom";
import { useProjectDetails, useUpdateProject } 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";
import {
  getProjectStatusColor,
  getProjectStatusName,
} from "../../utils/projectStatus";
import GlobalModel from "../common/GlobalModel";
import { useDispatch } from "react-redux";
import { setProjectId } from "../../slices/localVariablesSlice";
import { useProjectContext } from "../../pages/project/ProjectPage";

const ProjectCard = ({ project }) => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const ManageProject = useHasUserPermission(MANAGE_PROJECT);
  const { setMangeProject } = useProjectContext();

  const getProgress = (planned, completed) => {
    return (completed * 100) / planned + "%";
  };
  const getProgressInNumber = (planned, completed) => {
    return (completed * 100) / planned;
  };

  const handleClose = () => setShowModal(false);

  const handleViewProject = () => {
    dispatch(setProjectId(project.id));
    navigate(`/projects/details`);
  };
  const handleViewActivities = () => {
    dispatch(setProjectId(project.id));
    navigate(`/activities/records?project=${project.id}`);
  };
  return (
    <>
      <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 stretched-link text-heading text-start"
                    onClick={handleViewProject}
                  >
                    {project?.shortName ? project?.shortName : project?.name}
                  </h5>
                  <div className="client-info text-body">
                    <span>{project?.shortName ? project?.name : ""}</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"
                      data-bs-toggle="tooltip"
                      data-bs-offset="0,8"
                      data-bs-placement="top"
                      data-bs-custom-class="tooltip-dark"
                      title="More Action"
                    ></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>
                      <a className="dropdown-item"   onClick={() =>
                          setMangeProject({
                            isOpen: true,
                            Project: project.id,
                          })
                        }>
                        <i className="bx bx-pencil me-2"></i>
                        <span className="align-left">Modify</span>
                      </a>
                    </li>
                    <li onClick={handleViewActivities}>
                      <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">
                    Contact Person:{" "}
                  </span>
                  {project?.contactPerson ? project.contactPerson : "NA"}
                </p>
                <p className="mb-1">
                  <span className="text-heading fw-medium">Start Date: </span>
                  {project.startDate
                    ? moment(project?.startDate).format("DD-MMM-YYYY")
                    : "NA"}
                </p>
                <p className="mb-1">
                  <span className="text-heading fw-medium">Deadline: </span>

                  {project?.endDate
                    ? moment(project?.endDate).format("DD-MMM-YYYY")
                    : "NA"}
                </p>
                <p className="mb-0">{project?.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(project?.projectStatusId)
                  }
                >
                  {getProjectStatusName(project?.projectStatusId)}
                </span>
              </p>{" "}
              {getDateDifferenceInDays(project?.endDate,new Date() ) >= 0 && (
                <span className="badge bg-label-success ms-auto">
                  {project?.endDate &&
                    getDateDifferenceInDays(project?.endDate, new Date())}{" "}
                  Days left
                </span>
              )}
              {getDateDifferenceInDays(project?.endDate, new Date()) < 0 && (
                <span className="badge bg-label-danger ms-auto">
                  {project?.endDate &&
                    getDateDifferenceInDays(project?.endDate, new  Date())}{" "}
                  Days overdue
                </span>
              )}
            </div>
            <div className="d-flex justify-content-between align-items-center mb-2">
              <small className="text-body">
                Task: {formatNumber(project?.completedWork)} /{" "}
                {formatNumber(project?.plannedWork)}
              </small>
              <small className="text-body">
                {Math.floor(
                  getProgressInNumber(
                    project?.plannedWork,
                    project?.completedWork
                  )
                ) || 0}{" "}
                % Completed
              </small>
            </div>
            <div className="progress mb-4 rounded" style={{ height: "8px" }}>
              <div
                className="progress-bar rounded"
                role="progressbar"
                style={{
                  width: getProgress(
                    project?.plannedWork,
                    project?.completedWork
                  ),
                }}
                aria-valuenow={project?.completedWork}
                aria-valuemin="0"
                aria-valuemax={project?.plannedWork}
              ></div>
            </div>
            <div className="d-flex align-items-center justify-content-between">
              <div>
                <a className="text-muted d-flex " alt="Active team size">
                  <i className="bx bx-group bx-sm me-1_5"></i>
                  {project?.teamSize} Members
                </a>
              </div>
              <div>
                <a className="text-muted d-flex align-items-center">
                  <i className="bx bx-chat me-1 "></i>{" "}
                  <span className="text-decoration-line-through">15</span>
                </a>
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default ProjectCard;
