import React, { useEffect, useState } 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";
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";

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 (projectId) {
        dispatch(setProjectId(projectId));
      } else if (!selectedProject) {
        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([]);

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

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

  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="1"
                />
              </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">
                  {TaskLists?.length === 0 && !task_loading && (
                    <tr>
                      <td colSpan={7} className="text-center">
                        No Task Found
                      </td>
                    </tr>
                  )}

                  {task_loading && (
                    <tr>
                      <td colSpan={7} className="text-center">
                        <p>Loading..</p>
                      </td>
                    </tr>
                  )}

                  {TaskLists.map((task, index) => {
                    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>{formatDate(task.assignmentDate)}</td>
                          <td className="text-center">
                            <div className="d-flex align-items-center avatar-group justify-content-center">
                              {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.completedTask > 0 ? "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>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};
export default DailyTask;
