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

const DailyTask = () => {
  const { profile: LoggedUser } = useProfile();
  const {
    projects,
    loading: project_lodaing,
    error: projects_Error,
  } = useProjects();
  const selectedProject = useSelector(
    (store) => store.localVariables.projectId
  );
  const dispatch = useDispatch( selectedProject );
  const {
    TaskList,
    loading: task_loading,
    error: task_error,
    refetch
  } = useTaskList(selectedProject);
  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: "Attendance", link: null },
          ]}
        ></Breadcrumb>
        <div className="card card-action mb-6">
          <div className="card-body">
            <div className="row">
              <div className="col-sm-3 col-8 text-start 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 || projects.length < 0) && (
                    <option value="Loading..." disabled>
                      Loading...
                    </option>
                  )}
                  {!project_lodaing &&
                    projects
                      ?.filter((project) =>
                        LoggedUser?.projects?.map(Number).includes(project.id)
                      )
                      .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></th>
                    <th>Activity</th>
                    <th>Planned </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 Data Found
                      </td>
                    </tr>
                  )}

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

                  {TaskLists.map((task, index) => {
                    const accordionId = `accordion-${index}`;
                    return (
                      <React.Fragment key={index}>
                        {/* Main Row */}
                        <tr >
                          <td>
                            <div className="d-flex justify-content-center align-items-center"     data-bs-toggle="collapse"
                                data-bs-target={`#${accordionId}`}
                               aria-expanded="false"
                              aria-controls={accordionId}
                            >
                              <div className="d-flex flex-column">
                                <a
                                  href="#"
                                  className="text-heading text-truncate"
                                  
                                >
                                  <i class='bx bx-chevron-right'></i>
                                </a>
                              </div>
                            </div>
                          </td>
                          <td className="flex-wrap">
                            {task.workItem.activityMaster.activityName || "No Activity Name"}
                          </td>
                          <td>{task.plannedTask || "NA"}</td>
                          <td>{task.completedTask}</td>
                          <td>{formatDate( task.assignmentDate )}</td>
                          <td className="text-center">
                           <div class="d-flex align-items-center avatar-group justify-content-center">
                              {task.teamMembers.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" class="rounded-circle pull-up" /> */}
                                    <span className="avatar-initial rounded-circle bg-label-primary">{member?.firstName.slice(0,1) }</span>
                                  </div>  
                             ))}
                            </div>
                          </td>
                          <td className="text-center">
                            <div className="d-flex justify-content-center">
                            <button
                              type="button"
                              className="btn btn-xs btn-primary"
                              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>

                        {/* Accordion Content */}
                        <tr
                          id={accordionId}
                          className="accordion-collapse collapse"
                        >
                          <td colSpan={5}>
                            <div className="row">
                              <p>{task.subdata?.name}</p>
                            </div>
                          </td>
                        </tr>
                      </React.Fragment>
                    );
                  })}
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};
export default DailyTask;
