import React, { useState, useEffect } from "react";
import moment from "moment";
import {
  useProjectDetails,
  useProjects,
  useUpdateProject,
} from "../../hooks/useProjects";
import {
  getProjectStatusName,
  getProjectStatusColor,
} from "../../utils/projectStatus";
import ProgressBar from "../../components/common/ProgressBar";
import { useNavigate } from "react-router-dom";
import ManageProject from "../../components/Project/ManageProject";
import ProjectRepository from "../../repositories/ProjectRepository";
import { MANAGE_PROJECT } from "../../utils/constants";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import ManageProjectInfo from "../../components/Project/ManageProjectInfo";
import showToast from "../../services/toastService";
import { getCachedData, cacheData } from "../../slices/apiDataManager";
import GlobalModel from "../../components/common/GlobalModel";
import {formatNumber} from "../../utils/dateUtils";
import { setProjectId } from "../../slices/localVariablesSlice";
import { useDispatch } from "react-redux";

const ProjectListView = ({ projectData, recall }) => {
  const [projectInfo, setProjectInfo] = useState(projectData);
    const dispatch = useDispatch()
  const { projects_Details, loading, error, refetch } = useProjectDetails(
    projectInfo?.id,false
  );
  const [showModal, setShowModal] = useState(false);
  const navigate = useNavigate();
  const ManageProject = useHasUserPermission(MANAGE_PROJECT);
  useEffect(() => {
    setProjectInfo(projectData);
  }, [projectData]);
 const {
  mutate: updateProject,
  isPending,
  isSuccess,
  isError,
} = useUpdateProject({
  onSuccessCallback: () => {
    setShowModal(false);
  },
})

  const handleShow = async () => {
    try {
      const { data } = await refetch();
      setShowModal(true);
    } catch (err) {
      showToast("Failed to load project details", "error");
    }
  };

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

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

  const handleViewProject = () => {
    navigate(`/projects/details`);
  };

  const handleFormSubmit = (updatedProject) => {
    if (projectInfo?.id) {
      updateProject({
        projectId: projectInfo.id,
        updatedData: updatedProject,
      });
    }
  };

  return (
    <>
      {showModal && projects_Details && (
        <GlobalModel isOpen={showModal} closeModal={handleClose}>   <ManageProjectInfo
              project={projects_Details}
              handleSubmitForm={handleFormSubmit}
             onClose={handleClose}
             isPending={isPending}
            /></GlobalModel>
      )}

      <tr className={`py-8 ${isPending ? "bg-light opacity-50 pointer-events-none" : ""} `}>
        <td className="text-start" colSpan={5}>
          <span
            className="text-primary cursor-pointer"
             onClick={() => {
              dispatch(setProjectId(projectInfo.id))
              navigate(`/projects/details`)
            }}
          >
            {projectInfo.shortName
              ? `${projectInfo.name} (${projectInfo.shortName})`
              : projectInfo.name}
          </span>
        </td>
        <td className="text-start small">{projectInfo.contactPerson}</td>
        <td className="small text-center">
          <small>
            {projectInfo.startDate
              ? moment(projectInfo.startDate).format("DD-MMM-YYYY")
              : "NA"}
          </small>
        </td>
        <td className="mx-2 text-center small">
          {projectInfo.endDate
            ? moment(projectInfo.endDate).format("DD-MMM-YYYY")
            : "NA"}
        </td>
        <td className="mx-2 text-center small">{formatNumber(projectInfo.plannedWork)}</td>
        <td className="py-6 mx-2 text-start small align-items-center">
          <ProgressBar
            plannedWork={projectInfo.plannedWork}
            completedWork={projectInfo.completedWork}
            className="mb-0"
            height="4px"
          />
        </td>

        <td className="mx-3">
          <p className="mb-0">
            <span
              className={`badge ${getProjectStatusColor(
                projectInfo.projectStatusId
              )}`}
            >
              {getProjectStatusName(projectInfo.projectStatusId)}
            </span>
          </p>
        </td>

        <td className={`mx-2 ${ManageProject ? "d-sm-table-cell" : "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"
            >
              {loading ? (
                <div
                  className="spinner-border spinner-border-sm text-secondary"
                  role="status"
                >
                  <span className="visually-hidden">Loading...</span>
                </div>
              ) : (
                <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={() => navigate(`/projects/details`)}
                >
                  <i className="bx bx-detail me-2"></i>
                  <span className="align-left">View details</span>
                </a>
              </li>

              <li onClick={handleShow}>
                <a className="dropdown-item">
                  <i className="bx bx-pencil me-2"></i>
                  <span className="align-left">Modify</span>
                </a>
              </li>
              <li
                onClick={() =>
                  navigate(`/activities/records?project=${projectInfo.id}`)
                }
              >
                <a className="dropdown-item">
                  <i className="bx bx-task me-2"></i>
                  <span className="align-left">Activities</span>
                </a>
              </li>
            </ul>
          </div>
        </td>
      </tr>
    </>
  );
};

export default ProjectListView;