import React, { useEffect, useState, useRef } from "react";
import moment from "moment";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { TasksRepository } from "../../repositories/TaskRepository";
import showToast from "../../services/toastService";
import Avatar from "../common/Avatar";
import { getBgClassFromHash } from "../../utils/projectStatus";
import { cacheData, getCachedData } from "../../slices/apiDataManager";

const schema = z.object({
  comment: z.string().min(1, "Comment cannot be empty"),
});

const ReportTaskComments = ({ commentsData, closeModal }) => {
  const [loading, setloading] = useState(false);
  const [comments, setComment] = useState([]);
  const [bgClass, setBgClass] = useState("");
  const {
    register,
    handleSubmit,
    formState: { errors },
    reset,
  } = useForm({
    resolver: zodResolver(schema),
  });

  const containerRef = useRef(null);
  useEffect(() => {
    setComment(commentsData?.comments);
  }, [commentsData]);

  useEffect(() => {
    if (containerRef.current) {
      containerRef.current.scrollTop = containerRef.current.scrollHeight;
    }
  }, [comments]);

  const onSubmit = async (data) => {
    let sendComment = {
      ...data,
      taskAllocationId: commentsData?.id,
      commentDate: new Date().toISOString(),
    };
    try {
      setloading(true);
      const resp = await TasksRepository.taskComments(sendComment);
      setComment((prevItems) => [...prevItems, resp.data]);
      const taskList = getCachedData("taskList");
      const updatedTaskList = taskList.data.map((task) => {
        if (task.id === resp.data.taskAllocationId) {
          const existingComments = Array.isArray(task.comments)
            ? task.comments
            : [];
          return {
            ...task,
            comments: [...existingComments, resp.data],
          };
        }
        return task;
      });
      cacheData("taskList", {
        data: updatedTaskList,
        projectId: taskList.projectId,
      });
      reset();
      setloading(false);
      showToast("Successfully Sent", "success");
      // closeModal();
    } catch (error) {
      setloading(false);
      showToast(error.response.data?.message || "Something wrong", "error");
    }
  };
  return (
    <div
      className="modal-dialog modal-lg modal-simple report-task-comments-modal mx-sm-auto mx-1"
      role="document"
    >
      <div className="modal-content">
        <div className="modal-body p-sm-4 p-0">
          <button
            type="button"
            className="btn-close"
            onClick={closeModal}
            aria-label="Close"
          ></button>
          <p className="fs-6 text-dark text-start">
            {`${commentsData?.workItem?.workArea?.floor?.building?.name}`}{" "}
            <i className="bx bx-chevron-right"></i>{" "}
            {`${commentsData?.workItem?.workArea?.floor?.floorName} `}{" "}
            <i className="bx bx-chevron-right"></i>
            {`${commentsData?.workItem?.workArea?.areaName}`}
            <i className="bx bx-chevron-right"></i>
            {` ${commentsData?.workItem?.activityMaster?.activityName}`}
          </p>

          <ul
            className="list-grouph px-0 mx-0 overflow-auto"
            ref={containerRef}
            style={{ maxHeight: "400px" }}
          >
            {comments &&
              comments.map((data) => {
                const fullName = `${data?.employee?.firstName} ${data?.employee?.lastName}`;
                const bgClass = getBgClassFromHash(fullName);
                return (
                  <li
                    className={`list-group-item list-group-item-action  my-2 p-1`}
                  >
                    <div
                      className={`li-wrapper d-flex justify-content-start align-items-start my-0 `}
                    >
                      <div className="avatar avatar-xs me-1">
                        <span
                          className={`avatar-initial rounded-circle bg-label-primary}`}
                        >
                          {`${data?.employee?.firstName.slice(
                            0,
                            1
                          )} ${data?.employee?.lastName.slice(0, 1)}`}
                        </span>
                      </div>

                      <div className={` text-start  py-0  `}>
                        <p className={`mb-0 text-${bgClass}`}>{fullName}</p>
                        <p
                          className=" text-muted m-0 "
                          style={{ fontSize: "10px" }}
                        >
                          {moment.utc(data?.commentDate).local().fromNow()}
                        </p>
                      </div>
                    </div>
                    <p className={`ms-6 text-start mb-0 text-body`}>
                      {data?.comment}
                    </p>
                  </li>
                );
              })}
          </ul>
          <form onSubmit={handleSubmit(onSubmit)}>
            <textarea
              {...register("comment")}
              className="form-control"
              id="exampleFormControlTextarea1"
              rows="1"
              placeholder="Enter comment"
            />
            {errors.comment && (
              <div className="danger-text">{errors.comment.message}</div>
            )}
            <div className="text-end my-1">
              <button
                type="button"
                className="btn btn-sm btn-secondary"
                onClick={closeModal}
                data-bs-dismiss="modal"
              >
                Close
              </button>
              <button type="submit" className="btn btn-sm btn-primary ms-2">
                {loading ? "Sending..." : "Comment"}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

export default ReportTaskComments;
