import React, { useEffect, useState, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import Breadcrumb from "../../components/common/Breadcrumb";
import { dailyTask } from "../../data/masters";
import { useTaskList } from "../../hooks/useTasks";
import { useProjects } from "../../hooks/useProjects";
import { setProjectId } from "../../slices/localVariablesSlice";
import { useProfile } from "../../hooks/useProfile";
// import { formatDate } from "../../utils/dateUtils"; // Removed this import
import GlobalModel from "../../components/common/GlobalModel";
import AssignRoleModel from "../../components/Project/AssignRole";
import { ReportTask } from "../../components/Activities/ReportTask";
import ReportTaskComments from "../../components/Activities/ReportTaskComments";
import DateRangePicker from "../../components/common/DateRangePicker";
import DatePicker from "../../components/common/DatePicker";
import { useSearchParams } from "react-router-dom";
import moment from "moment";

const DailyTask = () => {
  const [searchParams] = useSearchParams();
  const projectId = searchParams.get("project");
  const selectedProject = useSelector(
    (store) => store.localVariables.projectId
  );
  const {
    projects,
    loading: project_lodaing,
    error: projects_Error,
  } = useProjects();

  const [initialized, setInitialized] = useState(false);

  // Sync projectId (either from URL or pick first accessible one)
  useEffect(() => {
    if (!project_lodaing && projects.length > 0 && !initialized) {
      if (selectedProject === 1 || selectedProject === undefined) {
        dispatch(setProjectId(projects[0].id));
      }

      setInitialized(true);
    }
  }, [project_lodaing, projects, projectId, selectedProject, initialized]);

  const dispatch = useDispatch(selectedProject);
  const [dateRange, setDateRange] = useState({ startDate: "", endDate: "" });

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

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

  useEffect(() => {
    setTaskLists(TaskList);
  }, [TaskList, selectedProject]);

  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(null);

  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 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"), // use inline content from attribute
        });
      }
    });
  }, [dates]);

  return (
    <>
      <div
        className={`modal fade ${isModalOpen ? "show" : ""}`}
        tabIndex="-1"
        role="dialog"
        style={{ display: isModalOpen ? "block" : "none" }}
        aria-hidden={!isModalOpen}
      >
        <ReportTask
          report={selectedTask}
          closeModal={closeModal}
          refetch={refetch}
        />
      </div>

      <div
        className={`modal fade ${isModalOpenComment ? "show" : ""}`}
        tabIndex="-1"
        role="dialog"
        style={{ display: isModalOpenComment ? "block" : "none" }}
        aria-hidden={!isModalOpenComment}
      >
        <ReportTaskComments
          commentsData={comments}
          closeModal={closeCommentModal}
        />
      </div>

      <div className="container-xxl flex-grow-1 container-p-y">
        <Breadcrumb
          data={[
            { label: "Home", link: "/dashboard" },
            { label: "Daily Task", 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">
              <div className="col-6 text-start">
                <DateRangePicker
                  onRangeChange={setDateRange}
                  DateDifference="6"
                  dateFormat="DD-MM-YYYY"
                />
              </div>
              <div className="col-sm-3 col-6 text-end mb-1">
                <select
                  name="DataTables_Table_0_length"
                  aria-controls="DataTables_Table_0"
                  className="form-select form-select-sm"
                  value={selectedProject}
                  onChange={(e) => dispatch(setProjectId(e.target.value))}
                  aria-label=""
                >
                  {project_lodaing && (
                    <option value="Loading..." disabled>
                      Loading...
                    </option>
                  )}
                  {!project_lodaing &&
                    projects &&
                    projects?.map((project) => (
                      <option value={project.id} key={project.id}>
                        {project.name}
                      </option>
                    ))}
                </select>
              </div>
            </div>
            <div className="table-responsive text-nowrap">
              <table className="table">
                <thead>
                  <tr>
                    <th>Activity</th>
                    <th>Assigned </th>
                    <th>Compeleted</th>
                    <th>Assign On</th>
                    <th>Team</th>
                    <th>Actions</th>
                  </tr>
                </thead>
                <tbody className="table-border-bottom-0">
                  {task_loading && (
                    <tr>
                      <td colSpan={7} className="text-center">
                        <p>Loading..</p>
                      </td>
                    </tr>
                  )}
                  {!task_loading && TaskList.length === 0 && (
                    <tr>
                      <td colSpan={7} className="text-center">
                        <p>No Reports Found</p>
                      </td>
                    </tr>
                  )}
                  {dates.map((date, i) => {
                    return (
                      <React.Fragment key={i}>
                        <tr className="table-row-header">
                          <td colSpan={7} className="text-start">
                            <strong>{moment(date).format("DD-MM-YYYY")}</strong>
                          </td>
                        </tr>
                        {TaskLists.filter((task) =>
                          task.assignmentDate.includes(date)
                        ).map((task, index) => {
                          const refIndex = index * 10 + i;
                          return (
                            <React.Fragment key={index}>
                              <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>
                                  {task.plannedTask || "NA"} /
                                  {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"
                                        >
                                          {/* <img src="..." alt="Avatar" className="rounded-circle pull-up" /> */}
                                          <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-center">
                                    <button
                                      type="button"
                                      className={`btn btn-xs btn-primary ${
                                        task.reportedDate != null ? "d-none" : ""
                                      }`}
                                      onClick={() => {
                                        selectTask(task);
                                        openModal();
                                      }}
                                    >
                                      Report
                                    </button>
                                    <button
                                      type="button"
                                      className="btn btn-xs btn-primary ms-2"
                                      onClick={() => {
                                        setComment(task);
                                        openComment();
                                      }}
                                    >
                                      Comment
                                    </button>
                                  </div>
                                </td>
                              </tr>
                            </React.Fragment>
                          );
                        })}
                      </React.Fragment>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};
export default DailyTask;