import React, { useState, useEffect } from "react";
import AssignTask from "../AssignTask";
import { useParams } from "react-router-dom";
import EditActivityModal from "./EditActivityModal";
import { useHasUserPermission } from "../../../hooks/useHasUserPermission";
import {
  ASSIGN_REPORT_TASK,
  MANAGE_PROJECT_INFRA,
  MANAGE_TASK,
} from "../../../utils/constants";
import ConfirmModal from "../../common/ConfirmModal";
import ProjectRepository from "../../../repositories/ProjectRepository";
import {
  useDeleteProjectTask,
  useProjectDetails,
} from "../../../hooks/useProjects";
import showToast from "../../../services/toastService";
import {
  cacheData,
  clearCacheKey,
  getCachedData,
} from "../../../slices/apiDataManager";
import { refreshData } from "../../../slices/localVariablesSlice";
import GlobalModel from "../../common/GlobalModel";
import { useDeleteMasterItem } from "../../../hooks/masterHook/useMaster";
import { useSelector } from "react-redux";

const WorkItem = ({
  workItem,
  forBuilding,
  forFloor,
  forWorkArea,
  deleteHandleTask,
}) => {
  const projectId = useSelector((store) => store.localVariables.projectId);
  const isTaskPlanning = /^\/activities\/task$/.test(location.pathname);

  const [itemName, setItemName] = useState("");
  const [NewWorkItem, setNewWorkItem] = useState();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [showModal, setShowModal] = useState(false);
  const [showModal2, setShowModal2] = useState(false);
  const ManageTasks = useHasUserPermission(MANAGE_TASK);
  const ManageInfra = useHasUserPermission(MANAGE_PROJECT_INFRA);
  const ManageAndAssignTak = useHasUserPermission(ASSIGN_REPORT_TASK);
  const [loadingDelete, setLoadingDelete] = useState(false);
  const project = getCachedData("projectInfo");

  const openModal = () => setIsModalOpen(true);
  const closeModal = () => setIsModalOpen(false);

  const showModalDelete = () => setShowModal2(true);
  const closeModalDelete = () => setShowModal2(false);
  const getProgress = (planned, completed) => {
    return (completed * 100) / planned + "%";
  };

  const { mutate: DeleteTask, isPending } = useDeleteProjectTask(() => {
    closeModalDelete?.();
  });

  const handleAssignTask = () => {
    setItemName("");
  };
  useEffect(() => {
    setNewWorkItem(workItem);
  }, [workItem]);

  const refreshWorkItem = (plannedTask) => {
    if (workItem) {
      const updated = {
        ...workItem,
        todaysAssigned: (workItem.todaysAssigned || 0) + plannedTask,
      };
      setNewWorkItem(updated);
    }
  };
  let assigndata = {
    building: forBuilding,
    floor: forFloor,
    workArea: forWorkArea,
    workItem,
  };

  const hasWorkItem = NewWorkItem && NewWorkItem;
  useEffect(() => {
    const tooltipTriggerList = Array.from(
      document.querySelectorAll('[data-bs-toggle="tooltip"]')
    );
    tooltipTriggerList.forEach((el) => new bootstrap.Tooltip(el));
  }, []);

  const handleSubmit = async () => {
    let WorkItemId = workItem.workItemId || workItem.id;
    DeleteTask({
      workItemId: WorkItemId,
      workAreaId: forWorkArea?.id,
      completedTask: workItem?.completedWork,
      plannedTask: workItem?.plannedWork,
      buildingId: forBuilding?.id,
      floorId: forFloor?.id,
    });
  };

  const PlannedWork =
    NewWorkItem?.workItem?.plannedWork || workItem?.plannedWork;
  const CompletedWork =
    NewWorkItem?.workItem?.completedWork ?? workItem?.completedWork;
  return (
    <>
      {isModalOpen && (
        <GlobalModel isOpen={isModalOpen} size="lg" closeModal={closeModal}>
          <AssignTask
            assignData={assigndata}
            onClose={closeModal}
            setAssigned={refreshWorkItem}
          />
        </GlobalModel>
      )}

      {showModal && (
        <GlobalModel
          isOpen={showModal}
          size="lg"
          closeModal={() => setShowModal(false)}
        >
          <EditActivityModal
            workItem={workItem}
            workArea={forWorkArea}
            building={forBuilding}
            floor={forFloor}
            onClose={() => setShowModal(false)}
          />
        </GlobalModel>
      )}

      {showModal2 && (
        <ConfirmModal
          isOpen={showModal2}
          type="delete"
          header="Delete Activity"
          message="Are you sure you want delete?"
          onSubmit={handleSubmit}
          onClose={closeModalDelete}
          loading={isPending}
        />
      )}

      <tr key={NewWorkItem?.workItemId}>
        {/* Activity Name - always visible */}
        <td className="text-start table-cell-small">
          <i className="bx bx-right-arrow-alt"></i>
          <span className="fw-light">
            {hasWorkItem
              ? NewWorkItem?.workItem?.activityMaster?.activityName ||
                workItem.activityMaster?.activityName
              : "NA"}
          </span>
        </td>

        {/* Status - visible only on small screens */}
        <td className="text-center d-sm-table-cell d-md-none">
          {hasWorkItem
            ? NewWorkItem?.workItem?.completedWork ??
              workItem?.completedWork ??
              "NA"
            : "NA"}
          /{" "}
          {hasWorkItem
            ? NewWorkItem?.workItem?.plannedWork || workItem?.plannedWork
            : "NA"}
        </td>

        <td className="text-center table-cell-small d-none d-md-table-cell">
          <span className="fw-light">
            {hasWorkItem
              ? NewWorkItem?.workItem?.workCategoryMaster?.name ||
                workItem.workCategoryMaster?.name ||
                "NA"
              : "NA"}
          </span>
        </td>

        <td className="text-center d-none d-md-table-cell">
          {hasWorkItem
            ? `${
                NewWorkItem?.workItem?.completedWork ??
                workItem?.completedWork ??
                "0"
              }/${
                NewWorkItem?.workItem?.plannedWork ??
                workItem?.plannedWork ??
                "0"
              }`
            : "NA"}
        </td>

        <td className="text-center d-none d-md-table-cell">
          {hasWorkItem
            ? `${
                NewWorkItem?.todaysAssigned ?? workItem?.todaysAssigned ?? "0"
              }`
            : "NA"}
        </td>

        <td className="text-center " style={{ width: "15%" }}>
          <div className="progress p-0">
            <div
              className="progress-bar"
              role="progressbar"
              style={{
                width: getProgress(
                  NewWorkItem?.workItem?.plannedWork || workItem?.plannedWork,
                  NewWorkItem?.workItem?.completedWork ||
                    workItem?.completedWork
                ),
                height: "5px",
              }}
              aria-valuenow={
                NewWorkItem?.workItem?.completedWork ?? workItem?.completedWork
              }
              aria-valuemin="0"
              aria-valuemax={
                hasWorkItem
                  ? NewWorkItem?.workItem?.plannedWork || workItem?.plannedWork
                  : 0
              }
            ></div>
          </div>
        </td>

        {(ManageInfra ||
          (ManageAndAssignTak && PlannedWork !== CompletedWork)) && (
          <td className="text-end align-items-middle border-top">
            {/* Desktop (md and up): inline icons */}
            <div className="d-none d-md-flex justify-content-end gap-1 px-2">
              {isTaskPlanning &&
                ManageAndAssignTak &&
                PlannedWork !== CompletedWork && (
                  <i
                    className="bx bx-user-plus text-primary cursor-pointer"
                    title="Assign"
                    onClick={openModal}
                    role="button"
                  ></i>
                )}

              {ManageInfra && (
                <>
                  <i
                    className="bx bxs-edit text-secondary cursor-pointer"
                    title="Edit"
                    onClick={() => setShowModal(true)}
                    role="button"
                  ></i>
                  <i
                    className="bx bx-trash text-danger cursor-pointer"
                    title="Delete"
                    onClick={showModalDelete}
                    role="button"
                  ></i>
                </>
              )}
            </div>

            {/* Mobile (sm only): dropdown with icons */}
            <div className="dropdown d-md-none text-center">
              <i
                className="bx bx-dots-vertical-rounded"
                role="button"
                data-bs-toggle="dropdown"
                aria-expanded="false"
                title="Actions"
              ></i>

              <ul className="dropdown-menu dropdown-menu-start">
                {isTaskPlanning &&
                  ManageAndAssignTak &&
                  PlannedWork !== CompletedWork && (
                    <li>
                      <a
                        className="dropdown-item d-flex align-items-center"
                        onClick={openModal}
                      >
                        <i className="bx bx-user-plus text-primary me-2"></i>{" "}
                        Assign
                      </a>
                    </li>
                  )}
                {ManageInfra && (
                  <>
                    <li>
                      <a
                        className="dropdown-item d-flex align-items-center"
                        onClick={() => setShowModal(true)}
                      >
                        <i className="bx bxs-edit text-secondary me-2"></i> Edit
                      </a>
                    </li>
                    <li>
                      <a
                        className="dropdown-item d-flex align-items-center"
                        onClick={showModalDelete}
                      >
                        <i className="bx bx-trash text-danger me-2"></i> Delete
                      </a>
                    </li>
                  </>
                )}
              </ul>
            </div>
          </td>
        )}
      </tr>
    </>
  );
};

export default WorkItem;
