import React, { useEffect, useState, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import Breadcrumb from "../../components/common/Breadcrumb";
import { useTaskList } from "../../hooks/useTasks";
import { useProjects } from "../../hooks/useProjects";
import { setProjectId } from "../../slices/localVariablesSlice";
import { ReportTask } from "../../components/Activities/ReportTask";
import ReportTaskComments from "../../components/Activities/ReportTaskComments";
import DateRangePicker from "../../components/common/DateRangePicker";
import { useSearchParams } from "react-router-dom";
import moment from "moment";
import FilterIcon from "../../components/common/FilterIcon"; 
import GlobalModel from "../../components/common/GlobalModel";
import AssignTask from "../../components/Project/AssignTask";
import SubTask from "../../components/Activities/SubTask";
import {formatNumber} from "../../utils/dateUtils";
import { useHasUserPermission } from "../../hooks/useHasUserPermission";
import { APPROVE_TASK, ASSIGN_REPORT_TASK } from "../../utils/constants";

const DailyTask = () => {
  const [searchParams] = useSearchParams();
  const projectIdFromUrl = searchParams.get("project");
  const selectedProject = useSelector(
    (store) => store.localVariables.projectId
  );


  const [filters, setFilters] = useState({
    selectedBuilding: "",
    selectedFloors: [],
    selectedActivities: [],
  });



  const [dateRange, setDateRange] = useState({ startDate: "", endDate: "" });
  const ApprovedTaskRights = useHasUserPermission(APPROVE_TASK)
  const ReportTaskRights = useHasUserPermission(ASSIGN_REPORT_TASK)

  const {
    TaskList,
    loading: task_loading,
    error: task_error,
    refetch,
  } = useTaskList(
     selectedProject || null,
     dateRange?.startDate || null,
    dateRange?.endDate || null
    );
  

  const [TaskLists, setTaskLists] = useState([]);
  const [dates, setDates] = useState([]);
  const popoverRefs = useRef([]);

  useEffect(() => {
    if (TaskList) {
      let filteredTasks = TaskList;

      if (filters.selectedBuilding) {
        filteredTasks = filteredTasks.filter(
          (task) =>
            task?.workItem?.workArea?.floor?.building?.name ===
            filters.selectedBuilding
        );
      }

      if (filters.selectedFloors.length > 0) {
        filteredTasks = filteredTasks?.filter((task) =>
          filters.selectedFloors?.includes(
            task?.workItem?.workArea?.floor?.floorName
          )
        );
      }

      if (filters.selectedActivities.length > 0) {
        filteredTasks = filteredTasks.filter((task) =>
          filters.selectedActivities.includes(
            task?.workItem?.activityMaster?.activityName
          )
        );
      }
      setTaskLists(filteredTasks);
    } else {
      setTaskLists([]);
    }
  }, [
    TaskList,
    filters?.selectedBuilding,
    filters?.selectedFloors,
    filters?.selectedActivities,
  ]);

  useEffect(() => {
    const AssignmentDates = [
      ...new Set(TaskLists.map((task) => task.assignmentDate.split("T")[0])),
    ].sort((a, b) => new Date(b) - new Date(a));
    setDates(AssignmentDates);
  }, [TaskLists]);

  const [selectedTask, selectTask] = useState(null);
  const [comments, setComment] = useState({ task: null, isActionAllow: false });

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isModalOpenComment, setIsModalOpenComment] = useState(false);

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

  const openComment = () => setIsModalOpenComment(true);
  const closeCommentModal = () => setIsModalOpenComment(false);
  const [IsSubTaskNeeded, setIsSubTaskNeeded] = useState(false);
  const [SubTaskData, setSubTaskData] = useState();
  const handletask = (task) => {
    selectTask(task);
    openModal();
  };

  useEffect(() => {
    popoverRefs.current.forEach((el) => {
      if (el) {
        new bootstrap.Popover(el, {
          trigger: "focus",
          placement: "left",
          html: true,
          content: el.getAttribute("data-bs-content"),
        });
      }
    });
  }, [dates, TaskLists]);


  const handlecloseModal = () =>
  {
    setIsModalOpen( false )
    //  refetch();
  }

  const handleCloseAction = (IsSubTask) => {
    if (IsSubTask) {
      setIsSubTaskNeeded(true);
      setIsModalOpenComment(false);
    } else {
      // refetch();
      setIsModalOpenComment(false);
    }
  };
  const hanleCloseSubTask = () => {
    setIsSubTaskNeeded(false);
    setComment( null );
    // refetch();
  };


  return (
    <>
      {isModalOpen && <GlobalModel isOpen={isModalOpen} size="md" closeModal={handlecloseModal} >
        <ReportTask
          report={selectedTask}
          closeModal={handlecloseModal}
          // refetch={refetch}
        />
      </GlobalModel>}

      {isModalOpenComment && (
        <GlobalModel
          isOpen={isModalOpenComment}
          size="lg"
          closeModal={() => setIsModalOpenComment(false)}
        >
          <ReportTaskComments
            commentsData={comments.task}
            actionAllow={comments.isActionAllow}
            handleCloseAction={handleCloseAction}
            closeModal={closeCommentModal}
          />
        </GlobalModel>
      )}

      {IsSubTaskNeeded && (
        <GlobalModel
          isOpen={IsSubTaskNeeded}
          size="lg"
          closeModal={hanleCloseSubTask}
        >
          <SubTask activity={comments.task} onClose={hanleCloseSubTask} />
        </GlobalModel>
      )}

      <div className="container-fluid">
        <Breadcrumb
          data={[
            { label: "Home", link: "/dashboard" },
            { label: "Daily Progress Report", link: null },
          ]}
        ></Breadcrumb>
        <div className="card card-action mb-6 ">
          <div className="card-body p-1 p-sm-2">
            <div className="row d-flex justify-content-between align-items-center">
              <div className="col-md-12 d-flex gap-3 align-items-center col-12 text-start mb-2 mb-md-0">
                <DateRangePicker
                  onRangeChange={setDateRange}
                  endDateMode="today"
                  DateDifference="6"
                  dateFormat="DD-MM-YYYY"
                />
                <FilterIcon
                  taskListData={TaskList}
                  onApplyFilters={setFilters}
                  currentSelectedBuilding={filters.selectedBuilding}
                  currentSelectedFloors={filters.selectedFloors}
                  currentSelectedActivities={filters.selectedActivities}
                />
              </div>
            </div>
            <div className="table-responsive text-nowrap mt-3">
              <table className="table">
                <thead>
                  <tr>
                    <th>Activity</th>
                    <th>Assigned </th>
                    <th>Completed</th>
                    <th>Assign On</th>
                    <th>Team</th>
                    <th>Actions</th>
                  </tr>
                </thead>
                <tbody className="table-border-bottom-0">
                  {/* --- Spinner when tasks are loading --- */}
                  {task_loading  && (
                    <tr>
                      <td colSpan={6} className="text-center">
                        {" "}
                        <div className="mt-10 mb-10 pt-5  pb-10">
                          <div
                            className="spinner-border text-primary"
                            role="status"
                          >
                            <span className="visually-hidden">Loading...</span>
                          </div>
                          <p className="mt-2">Loading Tasks...</p>
                        </div>
                      </td>
                    </tr>
                  )}
                  {!task_loading &&
                    TaskLists.length === 0 && (
                      <tr>
                        <td colSpan={6} className="text-center">
                          <div className="mt-10 mb-10 pt-10 pb-10">
                            {" "}
                            <p>No Reports Found</p>
                          </div>
                        </td>
                      </tr>
                    )}
                  {!task_loading &&
                    TaskLists.length > 0 &&
                    dates.map((date, i) => {
                      const tasksForDate = TaskLists.filter((task) =>
                        task.assignmentDate.includes(date)
                      );
                      if (tasksForDate.length === 0) return null;

                      return (
                        <React.Fragment key={i}>
                          <tr className="table-row-header">
                            <td colSpan={6} className="text-start">
                              {" "}
                              <strong>
                                {moment(date).format("DD-MM-YYYY")}
                              </strong>
                            </td>
                          </tr>
                          {tasksForDate.map((task, index) => {
                            const refIndex = index * 10 + i;
                            return (
                              <React.Fragment key={refIndex}>
                                <tr>
                                  <td className="flex-wrap text-start">
                                    <div>
                                      {task.workItem.activityMaster
                                        .activityName || "No Activity Name"}
                                    </div>
                                    <div>
                                      <label className="col-form-label text-sm">
                                        {" "}
                                        {
                                          task?.workItem?.workArea?.floor
                                            ?.building?.name
                                        }{" "}
                                        <i
                                          className="bx bx-chevron-right text-sm"
                                          style={{ fontSize: ".75rem" }}
                                        ></i>{" "}
                                        {
                                          task?.workItem?.workArea?.floor
                                            ?.floorName
                                        }{" "}
                                        <i
                                          className="bx bx-chevron-right text-sm"
                                          style={{ fontSize: ".75rem" }}
                                        >
                                          {" "}
                                        </i>
                                        {task?.workItem?.workArea?.areaName}
                                      </label>
                                    </div>
                                  </td>
                                  <td>
                                   {formatNumber(task.plannedTask)} / {formatNumber(task.workItem.plannedWork - task.workItem.completedWork)}
                                  </td>
                                  <td>{task.completedTask}</td>
                                  <td>
                                    {moment(task.assignmentDate).format(
                                      "DD-MM-YYYY"
                                    )}
                                  </td>
                                  <td className="text-center">
                                    <div
                                      key={refIndex}
                                      ref={(el) =>
                                        (popoverRefs.current[refIndex] = el)
                                      }
                                      tabIndex="0"
                                      className="d-flex align-items-center avatar-group justify-content-center"
                                      data-bs-toggle="popover"
                                      data-bs-trigger="focus"
                                      data-bs-placement="left"
                                      data-bs-html="true"
                                      data-bs-content={`
                                      <div class="border border-secondary rounded custom-popover p-2 px-3">
                                        ${task.teamMembers
                                          .map(
                                            (member) => `
                                            <div class="d-flex align-items-center gap-2 mb-2">
                                              <div class="avatar avatar-xs">
                                                <span class="avatar-initial rounded-circle bg-label-primary">
                                                  ${
                                                    member?.firstName?.charAt(
                                                      0
                                                    ) || ""
                                                  }${
                                              member?.lastName?.charAt(0) || ""
                                            }
                                                </span>
                                              </div>
                                              <span>${member.firstName} ${
                                              member.lastName
                                            }</span>
                                            </div>
                                          `
                                          )
                                          .join("")}
                                      </div>
                                    `}
                                    >
                                      {task.teamMembers
                                        .slice(0, 3)
                                        .map((member) => (
                                          <div
                                            key={member.id}
                                            data-bs-toggle="tooltip"
                                            data-bs-html="true"
                                            data-popup="tooltip-custom"
                                            data-bs-placement="top"
                                            title={`${member.firstName} ${member.lastName}`}
                                            className="avatar avatar-xs"
                                          >
                                            <span className="avatar-initial rounded-circle bg-label-primary">
                                              {member?.firstName.slice(0, 1)}
                                            </span>
                                          </div>
                                        ))}
                                      {task.teamMembers.length > 3 && (
                                        <div
                                          className="avatar avatar-xs"
                                          data-bs-toggle="tooltip"
                                          data-bs-placement="bottom"
                                          title={`${
                                            task.teamMembers.length - 3
                                          } more`}
                                        >
                                          <span className="avatar-initial rounded-circle bg-label-secondary pull-up">
                                            + {task.teamMembers.length - 3}
                                          </span>
                                        </div>
                                      )}
                                    </div>
                                  </td>
                                  <td className="text-center">
                                    <div className="d-flex justify-content-end">
                                     { ReportTaskRights && 
                                      <button
                                        type="button"
                                        className={`btn btn-xs btn-primary ${
                                          task.reportedDate != null
                                            ? "d-none"
                                            : ""
                                        }`}
                                        onClick={() => {
                                          selectTask(task);
                                          openModal();
                                        }}
                                      >
                                        Report
                                      </button>
                          }
                                      {(ApprovedTaskRights && task.reportedDate ) && (
                                        <button
                                          type="button"
                                          className={`btn btn-xs btn-warning ${
                                            task.reportedDate && task.approvedBy
                                              ? "d-none"
                                              : ""
                                          }`}
                                          onClick={() => {
                                            setComment({
                                              task: task,
                                              isActionAllow: true,
                                            });
                                            openComment();
                                          }}
                                        >
                                          QC
                                        </button>
                                      )}

                                      <button
                                        type="button"
                                        className="btn btn-xs btn-primary ms-2"
                                        onClick={() => {
                                          setComment({
                                            task: task,
                                            isActionAllow: false,
                                          });
                                          openComment();
                                        }}
                                      >
                                        Comment
                                      </button>
                                    </div>
                                  </td>
                                </tr>
                              </React.Fragment>
                            );
                          })}
                        </React.Fragment>
                      );
                    })}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};
export default DailyTask;
