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 the FilterIcon component

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

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

  // State for filters (moved to FilterIcon, but we need to receive them here)
  const [filters, setFilters] = useState({
    selectedBuilding: "",
    selectedFloors: [],
    selectedActivities: [],
  });

  // Sync projectId (either from URL or pick first accessible one)
  useEffect(() => {
    if (!project_loading && projects.length > 0 && !initialized) {
      if (projectIdFromUrl) {
        dispatch(setProjectId(projectIdFromUrl));
      } else if (selectedProject === 1 || selectedProject === undefined) {
        // If no project from URL or default/undefined, pick the first project
        dispatch(setProjectId(projects[0].id));
      }
      setInitialized(true);
    }
  }, [
    project_loading,
    projects,
    projectIdFromUrl,
    selectedProject,
    initialized,
    dispatch,
  ]);

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

  const {
    TaskList,
    loading: task_loading, // This `loading` state indicates if task data is being fetched
    error: task_error,
    refetch,
  } = useTaskList(
    initialized ? selectedProject : null,
    initialized ? dateRange.startDate : null,
    initialized ? dateRange.endDate : null
  );

  const [TaskLists, setTaskLists] = useState([]); // This state holds the *filtered* tasks for display
  const [dates, setDates] = useState([]);
  const popoverRefs = useRef([]);

  // Effect to apply filters to TaskList (from useTaskList) and update TaskLists (filtered display)
  useEffect(() => {
    // Only filter if TaskList is available (not null or undefined)
    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 {
      // If TaskList is null (e.g., during initial load or project change before data arrives),
      // ensure TaskLists is also empty to avoid displaying stale data.
      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(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(() => {
    // Ensure Bootstrap's Popover is initialized correctly
    popoverRefs.current.forEach((el) => {
      if (
        el &&
        window.bootstrap &&
        typeof window.bootstrap.Popover === "function"
      ) {
        // Dispose existing popovers to prevent duplicates if component re-renders
        const existingPopover = window.bootstrap.Popover.getInstance(el);
        if (existingPopover) {
          existingPopover.dispose();
        }
        new window.bootstrap.Popover(el, {
          trigger: "focus",
          placement: "left",
          html: true,
          content: el.getAttribute("data-bs-content"),
        });
      }
    });

    // Cleanup function for popovers when component unmounts or dependencies change
    return () => {
      popoverRefs.current.forEach((el) => {
        if (
          el &&
          window.bootstrap &&
          typeof window.bootstrap.Popover === "function"
        ) {
          const existingPopover = window.bootstrap.Popover.getInstance(el);
          if (existingPopover) {
            existingPopover.dispose();
          }
        }
      });
      popoverRefs.current = []; // Clear the refs array
    };
  }, [dates, TaskLists]); // Re-initialize popovers when tasks or dates change

  // Handler for project selection
  const handleProjectChange = (e) => {
    const newProjectId = e.target.value;
    dispatch(setProjectId(newProjectId));
    // --- IMPORTANT: Clear old data immediately to show loading state ---
    setTaskLists([]); // This makes the table empty, allowing the spinner to show
    // Reset filters when project changes (communicate to FilterIcon to clear)
    setFilters({
      selectedBuilding: "",
      selectedFloors: [],
      selectedActivities: [],
    });
  };

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

      {/* Report Task Comments Modal */}
      <div
        className={`modal fade ${isModalOpenComment ? "show d-block" : ""}`}
        tabIndex="-1"
        role="dialog"
        style={{ display: isModalOpenComment ? "block" : "none" }}
        aria-hidden={!isModalOpenComment}
      >
        <ReportTaskComments
          commentsData={comments}
          closeModal={closeCommentModal}
        />
        {isModalOpenComment && <div className="modal-backdrop fade show"></div>}{" "}
        {/* Add backdrop */}
      </div>

      <div className="container-xxl flex-grow-1 container-p-y">
        <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-6 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 component now manages its own filter states and logic */}
                <FilterIcon
                  taskListData={TaskList} // Pass the raw TaskList to FilterIcon
                  onApplyFilters={setFilters} // Callback to receive the filtered states from FilterIcon
                  currentSelectedBuilding={filters.selectedBuilding}
                  currentSelectedFloors={filters.selectedFloors}
                  currentSelectedActivities={filters.selectedActivities}
                  // You can pass the project_loading state here if you want to disable filter during project load
                  // isProjectLoading={project_loading}
                />
              </div>
              <div className="col-md-4 col-12 text-center mb-2 mb-md-0">
                <select
                  name="project_select"
                  aria-controls="DataTables_Table_0"
                  className="form-select form-select-sm"
                  value={selectedProject || ""}
                  onChange={handleProjectChange}
                  aria-label="Select Project"
                  disabled={project_loading} // Disable dropdown while projects are loading
                >
                  {project_loading && (
                    <option value="" disabled>
                      Loading Projects...
                    </option>
                  )}
                  {!project_loading &&
                    projects &&
                    projects?.map((project) => (
                      <option value={project.id} key={project.id}>
                        {project.name}
                      </option>
                    ))}
                </select>
              </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 || project_loading) && (
                    <tr>
                      <td colSpan={6} className="text-center">
                        {" "}
                        {/* ColSpan set to 6 based on your table headers */}
                        <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>
                  )}
                  {/* --- "No Reports Found" message only if not loading and no tasks --- */}
                  {!task_loading &&
                    !project_loading &&
                    TaskLists.length === 0 && (
                      <tr>
                        <td colSpan={6} className="text-center">
                          <div className="mt-10 mb-10 pt-10 pb-10">
                            {" "}
                            {/* ColSpan set to 6 */}
                            <p>No Reports Found</p>
                          </div>
                        </td>
                      </tr>
                    )}
                  {/* --- Render tasks when not loading and tasks exist --- */}
                  {!task_loading &&
                    TaskLists.length > 0 &&
                    dates.map((date, i) => {
                      const tasksForDate = TaskLists.filter((task) =>
                        task.assignmentDate.includes(date)
                      );
                      // Only render the date header if there are tasks for that date after filtering
                      if (tasksForDate.length === 0) return null;

                      return (
                        <React.Fragment key={i}>
                          <tr className="table-row-header">
                            <td colSpan={6} className="text-start">
                              {" "}
                              {/* ColSpan set to 6 */}
                              <strong>
                                {moment(date).format("DD-MM-YYYY")}
                              </strong>
                            </td>
                          </tr>
                          {tasksForDate.map((task, index) => {
                            const refIndex = `${i}-${index}`;
                            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>
                                    {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"
                                          >
                                            <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;
