import React, {
  useMemo,
  useState,
  useCallback,
  useEffect,
  SetStateAction,
  useRef,
} from "react";
import * as Yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import { Controller, FormProvider, useForm } from "react-hook-form";
import Chip from "@mui/material/Chip";
import Drawer from "@mui/material/Drawer";
import Button from "@mui/material/Button";
import Avatar from "@mui/material/Avatar";
import Divider from "@mui/material/Divider";
import Tooltip from "@mui/material/Tooltip";
import TextField from "@mui/material/TextField";
import IconButton from "@mui/material/IconButton";
import { alpha, styled } from "@mui/material/styles";
import { ConfirmDialog } from "@/components/custom-dialog";
import { LoadingButton, TabContext, TabPanel } from "@mui/lab";
import {
  AvatarGroup,
  Box,
  Grid,
  Icon,
  InputLabel,
  ListItem,
  ListItemIcon,
  ListItemText,
  Stack,
  Tab,
  Tabs,
  Typography,
  avatarGroupClasses,
  useMediaQuery,
  useTheme,
  ListItemAvatar,
} from "@mui/material";
import { useBoolean, useResponsive } from "@/hooks";
import AttachFileIcon from "@mui/icons-material/AttachFile";
import CommentIcon from "@mui/icons-material/Comment";
import HistoryIcon from "@mui/icons-material/History";
import AssignmentIcon from "@mui/icons-material/Assignment";
import Iconify from "@/shared/components/iconify";
import Scrollbar from "@/shared/components/scrollbar";
import CustomDateRangePicker, {
  useDateRangePicker,
} from "@/shared/components/custom-date-range-picker";
import Dialog from "@mui/material/Dialog";
import DialogContent from "@mui/material/DialogContent";
import DialogTitle from "@mui/material/DialogTitle";
import commentIcon from "@iconify-icons/material-symbols/comment";
import { ITaskItem } from "@/contexts/types/tasks";
import { collaborator } from "@/contexts/types/Project";

import {
  CommentItem,
  CommentReplyItem,
  ReplyComment,
} from "@/contexts/types/tasks";
import KanbanInputName from "./task-input-name";
import KanbanDetailsToolbar from "./task-details-toolbar";
import KanbanContactsDialog from "./task-contacts-dialog";
import SubTaskContactsDialog from "./sub-task-contacts-dialog";
import TaskDetailsPriority from "../add-task/task-details-priority";
import TaskDetailsAttachments from "../add-task/task-details-attachments";

import KanbanDetailsCommentInput from "./task-details-comment-input";
import {
  TASK_TYPE_OPTIONS,
  TASK_STATUS_OPTIONS,
  _taskHistory,
} from "@/shared/_mock";
import {
  FormControlLabel,
  MenuItem,
  Radio,
  RadioGroup,
  Select,
} from "@mui/material";
import Label from "@/components/label";
import { ITaskComment, IUnderTask } from "@/contexts/types/tasks";
import TaskHistory from "./task-history";
import { RHFEditor } from "@/shared/components/hook-form";
import { DatePicker, LocalizationProvider } from "@mui/x-date-pickers";
import { AdapterDateFns } from "@mui/x-date-pickers/AdapterDateFns";
import { Project } from "@/contexts/types/Project";
import axios from "axios";
import { IKanbanColumn } from "@/shared/types/kanban";
import {
  favoriteTask,
  unfavoriteTask,
  useGetParticipants,
  useGetCollaboratorsOfProject,
  useGetManager,
  getSubTasksByTaskId,
  addSubTask,
  updateSubTask,
  deleteSubTask,
  assignSubTaskToCollaborator,
  useGetCollaborator,
  toggleCollaborator,
} from "@/shared/api/task";
import { enqueueSnackbar } from "@/components/snackbar";
import {
  createComment,
  deleteComment,
  toggleLike,
  useGetComments,
  postReplyComment,
  useGetRepliesForComment,
} from "@/shared/api/comment";
import {} from "@/shared/api/comment";

import { useGetCollaborators } from "@/shared/api/project";
import { fToNow } from "@/utils/format-time";
import ReplyCommentInput from "./input-reply-comment";
import ReplyCommentList from "./list-reply-comment";
import { axiosInstance, endpoints } from "@/utils/axios";
import { PROJECT_API } from "@/config-global";
import { sendNotificationToUserAfterAssigningTask, sendNotificationToUserAfterChangingTaskStatus, sendNotificationToUserAfterComment } from '@/shared/api/notif';
import { generateToken } from '@/utils/firebase';
import { INotif } from "@/shared/types/notif";

// ----------------------------------------------------------------------

const StyledLabel = styled("span")(({ theme }) => ({
  ...theme.typography.caption,
  width: 100,
  flexShrink: 0,
  color: theme.palette.text.secondary,
  fontWeight: theme.typography.fontWeightSemiBold,
}));

// ----------------------------------------------------------------------

type Props = {
  task: ITaskItem | null;
  openDetails: boolean;
  onCloseDetails: VoidFunction;
  onUpdateTask: (updateTask: ITaskItem) => void;
  onArchiveTask: (id: number) => void;
  onDeleteTask: (id: number) => void;
  onFavoriteTask: (id: number) => void;
  onUnFavoriteTask: (id: number) => void;
};

export default function TaskDetails({
  task,
  openDetails,
  onCloseDetails,
  onArchiveTask,
  onUpdateTask,
  onDeleteTask,
  onFavoriteTask,
  onUnFavoriteTask,
}: Props) {
  const like = useBoolean();
  const click = useBoolean();
  const mdUp = useResponsive("up", "md");
  const contacts = useBoolean();
  const theme = useTheme();
  const isXsScreen = useMediaQuery(theme.breakpoints.down("sm"));

  //---------------content------------------
  const NewTaskSchema = Yup.object().shape({
    description: Yup.string(),
  });
  const StyledFieldLabel = styled(Typography)(({ theme }) => ({
    fontWeight: 600,
    color: theme.palette.text.secondary,
    marginRight: theme.spacing(1),
  }));

  const StyledFieldValue = styled(Typography)(({ theme }) => ({
    fontWeight: 500,
    color: theme.palette.text.primary,
  }));

  const defaultValues = useMemo(
    () => ({
      description: task?.description || "",
    }),
    [task]
  );

  const methods = useForm({
    resolver: yupResolver(NewTaskSchema),
    defaultValues,
  });
  const {
    reset,
    control,
    watch,
    setValue,
    handleSubmit,
    formState: { isSubmitting },
  } = methods;

  //-----------------------------------------

  const [type, setType] = useState(task?.type || "");
  const [status, setStatus] = useState<string>(task?.status || "");
  const [project, setProject] = useState(task?.project || null);
  const [project1, setProject1] = useState<Project | null>(null);
  const [taskDescription, setTaskDescription] = useState(task?.description);
  const [taskMark, setTaskMark] = useState(task?.point || 0);
  const [showDatePicker, setShowDatePicker] = useState(false);
  const [priority, setPriority] = useState(task?.priority || "LOW");
  const [taskName, setTaskName] = useState(task?.name || "default");
  const [sousTaches, setSousTaches] = useState<IUnderTask[]>(
    task?.subTask || []
  );
  const [nouvelleSousTache, setNouvelleSousTache] = useState("");
  const [modificationId, setModificationId] = useState(0);
  const [texteModifie, setTexteModifie] = useState("");
  const [assigneeDialogOpen, setAssigneeDialogOpen] = useState(false);
  const [sousTacheActuelle, setSousTacheActuelle] = useState<IUnderTask | null>(
    null
  );
  const [selectedAssignee, setSelectedAssignee] = useState<number | null>(null);
  const [isEditorChanged, setIsEditorChanged] = useState(false);
  const [isButtonClicked, setIsButtonClicked] = useState(false);
  const [isButtonShown, setIsButtonShown] = useState(true);
  const [hoveredTaskId, setHoveredTaskId] = useState<number | null>(null);
  const isTaskHovered = (taskId: number) => taskId === hoveredTaskId;
  const [tabValue, setTabValue] = useState(0);
  const [tabValue1, setTabValue1] = useState(0);
  const [endDate, setEndDate] = useState(
    task?.endDate ? new Date(task.endDate) : null
  );
  const confirm = useBoolean();
  const [favorite, setFavorite] = useState<boolean>(
    task?.itemStates === "FAVORITE"
  );
  const [likeCount, setLikeCount] = useState(0);
  const [liked, setLiked] = useState<boolean | null>(null);
  const [usersWhoLiked, setUsersWhoLiked] = useState<string[]>([]);
  const [commentLikeCount, setCommentLikeCount] = useState<{
    [key: number]: number;
  }>({});
  const [commentLiked, setCommentLiked] = useState<{ [key: number]: boolean }>(
    {}
  );
  const [usersWhoLikedComment, setUsersWhoLikedComment] = useState<{
    [key: number]: string[];
  }>({});
  const [showUsersWhoLiked, setShowUsersWhoLiked] = useState<number | null>(
    null
  );

  const [isEditingName, setIsEditingName] = useState(false);
  const [newTaskName, setNewTaskName] = useState(task?.name || "");
  const statuses = [
    { id: 1, name: "TO DO" },
    { id: 2, name: "IN PROGRESS" },
    { id: 3, name: "DONE" },
  ];
  const [isEditingStatus, setIsEditingStatus] = useState(false);
  const [newStatus, setNewStatus] = useState<string>(status || "");
  const [isEditingType, setIsEditingType] = useState(false);
  const [newType, setNewType] = useState<string>(type || "");
  const [isEditingDescription, setIsEditingDescription] = useState(false);
  const [newDescription, setNewDescription] = useState(task?.description || "");
  const [isEditingMark, setIsEditingMark] = useState(false);
  const [newMark, setNewMark] = useState(task?.point || 0);
  const [availableCollaborators, setAvailableCollaborators] = useState<
    collaborator[]
  >([]);

const selectedAgency = localStorage.getItem("selectedAgency");
const agencyRole = localStorage.getItem("agency_role");

const [notification, setNotification] = useState({
  open: false,
  message: "",
  severity: "info", 
});

const showNotification = (message: string, severity = "info") => {
  setNotification({ open: true, message, severity });
};

const handleCloseNotification = () => {
  setNotification((prev) => ({ ...prev, open: false }));
};


const isManagerForSelectedAgency = (): boolean => {
  try {
    const selectedAgency = localStorage.getItem("selectedAgency");
    const agencyRole = localStorage.getItem("agency_role");

    if (!selectedAgency || !agencyRole) {
      console.error("Selected agency or agency role not found in localStorage");
      return false;
    }
    const agencyRoleObject = JSON.parse(agencyRole);

    const roleForSelectedAgency = agencyRoleObject[selectedAgency];
    const isManager = roleForSelectedAgency === "MANAGER";

    return isManager;
  } catch (error) {
    console.error("Error parsing agency_role from localStorage:", error);
    return false;
  }
};





  const handleSaveDescription = async () => {
    try {
      if (task && newDescription) {
        await updateTaskDescription(task.id, newDescription);
        setNewDescription(newDescription);
      }
      setIsEditingDescription(false);
    } catch (error) {
      console.error("Failed to update task description:", error);
    }
  };

  const handleSaveMark = async () => {
    try {
      if (task && newMark) {
        await updateTaskPoint(task.id, newMark);
        setNewMark(newMark);
      }
      setIsEditingMark(false);
    } catch (error) {
      console.error("Failed to update task points:", error);
    }
  };

  const handleEditName = () => {
    setIsEditingName(true);
    setNewTaskName(taskName);
  };

  const handleCancelEditName = () => {
    setIsEditingName(false);
    setNewTaskName(taskName);
  };

  const handleSaveTaskName = async () => {
    if (task && newTaskName !== taskName) {
      await updateTaskName(task.id, newTaskName);
      setTaskName(newTaskName);
    }
    setIsEditingName(false);
  };
  const handleCancelEditType = () => {
    setNewType(type);
    setIsEditingType(false);
  };

  const handleEditType = () => {
    setNewType(type);
    setIsEditingType(true);
  };
  const toggleUsersWhoLikedComment = (commentId: number) => {
    setShowUsersWhoLiked((prev) => (prev === commentId ? null : commentId));
  };
  const [taskHistory, setTaskHistory] = useState([]);
  interface TaskHistoryEntry {
    id: string;
    action: string;
    date: string;
    modifiedFields?: string | null;
  }
  const fetchTaskHistory = async () => {
    try {
      const response = await axios.get(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/tasks/${task?.id}/history`
      );
      const mappedHistory = response.data.map((entry: TaskHistoryEntry) => ({
        id: entry.id,
        title: entry.action,
        time: new Date(entry.date),
        type: "update",
        details: entry.modifiedFields || null,
      }));
      setTaskHistory(mappedHistory);
    } catch (error) {
      console.error("Failed to fetch task history:", error);
    }
  };
  useEffect(() => {
    const fetchAvailableCollaborators = async () => {
      try {
        const response = await axiosInstance.get(
          `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/accountsagency`,
          { params: { agencyId: project1?.agencyId } }
        );
        setAvailableCollaborators(response.data);
      } catch (error) {
        console.error("Error fetching available collaborators:", error);
      }
    };

    fetchAvailableCollaborators();
  }, [project1?.agencyId]);

  useEffect(() => {
    if (task) fetchTaskHistory();
  }, [task]);

  useEffect(() => {
    const fetchProject = async () => {
      if (task && task.projectId) {
        try {
          const response = await axios.get(
            `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/get/${task.projectId}`
          );
          const projectData: Project = response.data;
          setProject1(projectData);
        } catch (error) {
          console.error("Failed to fetch project", error);
        }
      }
    };

    fetchProject(); // Call the fetchProject function
  }, [task]);

  const handleToggleFavorite = async () => {
    try {
      if (favorite) {
        await unfavoriteTask(task?.id || 0);
      } else {
        await favoriteTask(task?.id || 0);
      }
      setFavorite((prev) => !prev);
    } catch (error) {
      console.error("An error occurred:", error);
      enqueueSnackbar("An error occurred. Please try again later.", {
        variant: "error",
      });
    }
  };

  // 1. Add a key to force refresh of useGetComments
  const [commentRefreshKey, setCommentRefreshKey] = useState(0);

  // 2. Modify how we get comments to include the refresh key
  const { comments } = task?.id !== undefined ? useGetComments(task.id, commentRefreshKey) : { comments: [] };

  // 3. Update the useEffect for comments
  useEffect(() => {
    if (comments && comments.length > 0) {
      setListData(comments);
    }
  }, [comments]);

  const [listData, setListData] = useState<CommentItem[]>([]);  // Initialize as empty array

  const { collaborators } = useGetCollaborators();
  const [collaboratorData1, setCollaboratorData1] = useState<collaborator[]>(
    collaborators as unknown as collaborator[]
  );

  useEffect(() => {
    if (collaborators.length) {
      setCollaboratorData1(collaborators as unknown as collaborator[]);
    }
  }, [collaborators]);

  function getCollaboratorById(collaboratorId: number) {
    return collaboratorData1.find(
      (collaborator) => collaborator.id === collaboratorId
    );
  }

  const [commentCollaborators, setCommentCollaborators] = useState<{ [key: number]: any }>({});

  useEffect(() => {
    const fetchCollaborators = async () => {
      for (const comment of listData) {
        if (comment.collaboratorId && !commentCollaborators[comment.collaboratorId]) {
          try {
            const response = await axiosInstance.get(
              `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/accountagency/id`,
              {
                params: { Id: comment.collaboratorId }
              }
            );
            setCommentCollaborators(prev => ({
              ...prev,
              [comment.collaboratorId as number]: response.data
            }));
          } catch (error) {
            console.error('Error fetching collaborator:', error);
          }
        }
      }
    };

    fetchCollaborators();
  }, [listData]);

  // 3. Update the handleAddComment function
  const handleAddComment = async (newComment: CommentItem) => {
    // Create optimistic comment
    const optimisticComment: CommentItem = {
      id: Date.now(),
      idTask: task?.id || 0,
      type: "BUG",
      collaboratorId: undefined,
      message: newComment.message || '',
      isLiked: false,
      attachments: [],
      createdAt: new Date()
    };

    // Immediately update the UI with the optimistic comment
    setListData(prevList => [...(prevList || []), optimisticComment]);

    try {
      const email = localStorage.getItem("email");
      const agencyId = localStorage.getItem("selectedAgency");

      // Get collaborator ID
      const response = await axiosInstance.get(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/accountagency/${email}/${agencyId}`
      );
      const collaboratorId = response.data.id;

      // Create comment with collaborator ID
      const commentToCreate = {
        ...optimisticComment,
        collaboratorId
      };

      // Create comment in database
      const commentResponse = await createComment(commentToCreate);
      const createdComment = commentResponse.data;

      // Force refresh of comments
      setCommentRefreshKey(prev => prev + 1);

      // Update collaborators data for the new comment
      setCommentCollaborators(prev => ({
        ...prev,
        [createdComment.collaboratorId as number]: response.data
      }));

      // Handle notifications
      const firebaseToken = await generateToken();
      if (firebaseToken && task?.collaboratorIds) {
        // Get collaborator details
        for (const collaboratorId of task.collaboratorIds) {
          try {
            const response = await axiosInstance.get(
              `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/accountagency/id`,
              {
                params: { Id: collaboratorId }
              }
            );
            const collaborator = response.data;

            if (collaborator?.user?.email) {
              const notificationData: INotif = {
                firebaseToken,
                email: collaborator.user.email,
              };
              
              await sendNotificationToUserAfterComment(notificationData);
            }
          } catch (error) {
            console.error('Error sending notification:', error);
          }
        }
      }
    } catch (error) {
      // Remove optimistic comment if there's an error
      setListData(prevList => 
        (prevList || []).filter(comment => comment.id !== optimisticComment.id)
      );
      console.error("Error adding comment:", error);
      enqueueSnackbar("Failed to add comment", { variant: "error" });
    }
  };

 

  const fetchCommentLikes = async (commentId: number) => {
    try {
      const likeCountResponse = await axiosInstance.get(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/likes/count`,
        { params: { entityId: commentId, entityType: "COMMENT" } }
      );
      setCommentLikeCount((prev) => ({
        ...prev,
        [commentId]: likeCountResponse.data,
      }));

      // Fetch the like status for the current user
      const email = localStorage.getItem("email");
      const userResponse = await axiosInstance.get(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/user/email`,
        {
          params: { email },
        }
      );
      const userId = userResponse.data.id;

      const likeStatusResponse = await axiosInstance.get(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/likes/status`,
        { params: { entityId: commentId, entityType: "COMMENT", userId } }
      );
      setCommentLiked((prev) => ({
        ...prev,
        [commentId]: likeStatusResponse.data,
      }));

      // Fetch users who liked the comment
      const userIdsResponse = await axios.get(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/likes/user-ids`,
        { params: { entityId: commentId, entityType: "COMMENT" } }
      );
      const userIds = userIdsResponse.data;

      const userDetailsPromises: Promise<any>[] = userIds.map(
        (userId: number) =>
          axiosInstance.get(
            `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/${userId}`
          )
      );

      const usersDetailsResponses = await Promise.all(userDetailsPromises);

      const users = usersDetailsResponses.map((response) => {
        const { firstName, lastName } = response.data;
        return `${firstName} ${lastName}`;
      });

      setUsersWhoLikedComment((prev) => ({ ...prev, [commentId]: users }));
    } catch (error) {
      console.error("Error fetching comment likes:", error);
    }
  };
  useEffect(() => {
    comments.forEach((comment) => {
      if (comment.id !== undefined) {
        fetchCommentLikes(comment.id);
      }
    });
  }, [comments]);

  const handleToggleLikeComment = async (commentId: number) => {
    try {
      const email = localStorage.getItem("email");
      if (!email) {
        console.error("Email not found in localStorage");
        enqueueSnackbar("Failed to toggle like. Please log in first.", {
          variant: "error",
        });
        return;
      }

      // Fetch user ID based on email
      const userResponse = await axiosInstance.get(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/user/email`,
        {
          params: { email },
        }
      );
      const userId = userResponse.data.id;

      if (!userId) {
        console.error("Failed to fetch user ID");
        enqueueSnackbar("Failed to toggle like. Please try again.", {
          variant: "error",
        });
        return;
      }

      if (commentLiked[commentId]) {
        // Remove like
        await axios.delete(
          `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/likes/remove`,
          {
            params: { entityId: commentId, entityType: "COMMENT", userId },
          }
        );
        setCommentLikeCount((prev) => ({
          ...prev,
          [commentId]: Math.max((prev[commentId] || 0) - 1, 0),
        }));
        setCommentLiked((prev) => ({ ...prev, [commentId]: false }));

        // Show notification for removing like
        enqueueSnackbar("Like removed successfully.", { variant: "info" });
      } else {
        // Add like
        await axios.post(
          `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/likes/add`,
          {
            entityId: commentId,
            entityType: "COMMENT",
            userId,
          }
        );
        setCommentLikeCount((prev) => ({
          ...prev,
          [commentId]: (prev[commentId] || 0) + 1,
        }));
        setCommentLiked((prev) => ({ ...prev, [commentId]: true }));

        // Show notification for adding like
        enqueueSnackbar("Comment liked successfully.", { variant: "success" });
      }
      await fetchCommentLikes(commentId);
    } catch (error) {
      console.error("Error toggling like for comment:", error);

      // Show error notification
      enqueueSnackbar("Failed to toggle like. Please try again.", {
        variant: "error",
      });
    }
  };

  const renderUsersWhoLikedComment = (commentId: number) => {
    const users = usersWhoLikedComment[commentId] || [];
    return (
      <Box sx={{ p: 2 }}>
        <Typography variant="subtitle1">Liked By:</Typography>
        {users.length > 0 ? (
          <ul>
            {users.map((user, index) => (
              <li key={index}>
                <Typography variant="body2">{user}</Typography>
              </li>
            ))}
          </ul>
        ) : (
          <Typography variant="body2" color="textSecondary">
            No likes yet.
          </Typography>
        )}
      </Box>
    );
  };
  const fetchUsersWhoLikedTask = async (taskId: number) => {
    try {
      const userIdsResponse = await axios.get(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/likes/user-ids`,
        { params: { entityId: task?.id, entityType: "TASK" } }
      );

      const userIds = userIdsResponse.data;
      const userDetailsPromises: Promise<any>[] = userIds.map(
        (userId: number) =>
          axiosInstance.get(
            `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/${userId}`
          )
      );

      const usersDetailsResponses = await Promise.all(userDetailsPromises);

      const users = usersDetailsResponses.map((response) => {
        const { firstName, lastName } = response.data;
        return `${firstName} ${lastName}`;
      });

      return users;
    } catch (error) {
      console.error("Error fetching users who liked the task:", error);
      return [];
    }
  };
  useEffect(() => {
    fetchLikes();
  }, [task]);

  const fetchLikes = async () => {
    if (task) {
      try {
        const email = localStorage.getItem("email");
        if (!email) {
          console.error("Email not found in localStorage");
          return;
        }

        const userResponse = await axiosInstance.get(
          `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/user/email`,
          {
            params: { email },
          }
        );
        const userId = userResponse.data.id;

        if (!userId) {
          console.error("Failed to fetch user ID");
          return;
        }

        const likeCountResponse = await axios.get(
          `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/likes/count`,
          { params: { entityId: task.id, entityType: "TASK" } }
        );
        setLikeCount(likeCountResponse.data);

        const likeStatusResponse = await axios.get(
          `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/likes/status`,
          { params: { entityId: task.id, entityType: "TASK", userId } }
        );
        setLiked(likeStatusResponse.data);

        const userNames = await fetchUsersWhoLikedTask(task.id);
        setUsersWhoLiked(userNames);
      } catch (error) {
        console.error("Failed to fetch likes data:", error);
      }
    }
  };

  useEffect(() => {
    if (task) {
      setType(task.type || "");
      setStatus(task.status || "");
      setProject(task.project || null);
      setTaskDescription(task.description || "");
      setTaskMark(task.point || 0);
      setPriority(task.priority || "LOW");
      setTaskName(task.name || "default");
      setSousTaches(task.subTask || []);
      setEndDate(task.endDate ? new Date(task.endDate) : null);
    }
  }, [task]);

  //----------------- gestion des sous-tâches-------------------

  // Fonction pour activer/désactiver le survol d'une tâche
  const handleTaskMouseEnter = (taskId: number) => {
    setHoveredTaskId(taskId);
  };

  const handleTaskMouseLeave = () => {
    setHoveredTaskId(null);
  };

  useEffect(() => {
    if (task) {
      fetchSubTasks(task.id);
    }
  }, [task]);

  const fetchSubTasks = async (taskId: number) => {
    try {
      const fetchedSubTasks = await getSubTasksByTaskId(task?.id || 0);
      setSousTaches(fetchedSubTasks);
    } catch (error) {
      console.error("Failed to fetch subtasks:", error);
    }
  };
  const handleToggleLikeTask = async () => {
    try {
      const email = localStorage.getItem("email");
      if (!email) {
        console.error("Email not found in localStorage");
        enqueueSnackbar("Email is required to like a task.", {
          variant: "error",
        });
        return;
      }

      const userResponse = await axiosInstance.get(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/user/email`,
        {
          params: { email },
        }
      );
      const userId = userResponse.data.id;
      if (!userId) {
        console.error("Failed to fetch user ID");
        enqueueSnackbar("Failed to fetch user information.", {
          variant: "error",
        });
        return;
      }

      if (liked) {
        await axios.delete(
          `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/likes/remove`,
          { params: { entityId: task?.id, entityType: "TASK", userId } }
        );
        setLikeCount((prev) => Math.max(prev - 1, 0));
        setLiked(false);
        enqueueSnackbar("Like removed successfully.", { variant: "info" });
      } else {
        await axios.post(
          `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/likes/add`,
          {
            entityId: task?.id,
            entityType: "TASK",
            userId,
          }
        );
        setLikeCount((prev) => prev + 1);
        setLiked(true);
        enqueueSnackbar("Task liked successfully.", { variant: "success" });
      }
      if (task?.id !== undefined) {
        const updatedUsers = await fetchUsersWhoLikedTask(task.id);
        setUsersWhoLiked(updatedUsers);
      } else {
        console.error(
          "Task ID is undefined, cannot fetch users who liked the task."
        );
      }
    } catch (error) {
      console.error("Error toggling like status:", error);
      enqueueSnackbar("Failed to toggle like status. Please try again.", {
        variant: "error",
      });
    }
  };

  const ajouterSousTache = async () => {
    if (!task) {
      console.error("Task is null");
      return;
    }
    if (nouvelleSousTache.trim() !== "") {
      const nouvelle: IUnderTask = {
        id: Date.now(),
        name: nouvelleSousTache,
        task: task,
        collaboratorId: selectedAssignee || 0,
      };

      try {
        const addedSubTask = await addSubTask(task?.id || 0, nouvelle);
        setSousTaches([...sousTaches, addedSubTask]);
        setNouvelleSousTache("");
      } catch (error) {
        console.error("Failed to add subtask:", error);
      }
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === "Enter") {
      ajouterSousTache();
      e.preventDefault();
    }
  };

  const supprimerSousTache = async (id: number) => {
    try {
      await deleteSubTask(id);
      setSousTaches(sousTaches.filter((tache) => tache.id !== id));
    } catch (error) {
      console.error("Failed to delete subtask:", error);
    }
  };

  const ouvrirAssigneeDialog = (sousTache: any) => {
    setAssigneeDialogOpen(true);
    setSousTacheActuelle(sousTache);
  };

  const { collaborator } = useGetCollaborator(
    sousTacheActuelle?.collaboratorId || 0
  );

  const [collaboratorData2, setCollaborator] = useState<collaborator | null>(
    null
  );

  useEffect(() => {
    if (collaborator) {
      setCollaborator(collaborator as unknown as collaborator);
    }
  }, [collaborator]);

  const assignerCollaborateur = async (collaborateurId: number) => {
    if (sousTacheActuelle) {
      try {
        const collaboratorResponse = await axiosInstance.get(
          `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/accountagency/id`,
          {
            params: {
              Id: collaborateurId,
            },
          }
        );
        const collaborator = collaboratorResponse.data;

        const updatedSubTask: IUnderTask = {
          ...sousTacheActuelle,
          collaboratorId: collaborateurId,
        };

        setSousTaches((prevSousTaches) =>
          prevSousTaches.map((tache) =>
            tache.id === sousTacheActuelle.id ? updatedSubTask : tache
          )
        );

        setAssigneeDialogOpen(false);
      } catch (error) {
        console.error("Failed to assign collaborator to subtask:", error);
      }
    }
  };
  const fetchCollaborator = async (collaboratorId: number) => {
    try {
      const response = await axiosInstance.get(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/accountagency/id`,
        { params: { Id: collaboratorId } }
      );
      return response.data;
    } catch (error) {
      console.error("Error fetching collaborator data:", error);
      return null;
    }
  };
  useEffect(() => {
    const getManager = async () => {
      if (task?.managerId) {
        try {
          const manager = await fetchCollaborator(task.managerId);
          setManagerData(manager);
        } catch (error) {
          console.error("Error fetching manager:", error);
        }
      }
    };

    getManager();
  }, [task?.managerId]);

  //
  const modifierAssignation = (sousTacheId: number, collaborateur: any) => {
    setSousTaches(
      sousTaches.map((tache) =>
        tache.id === sousTacheId ? { ...tache, assignee: collaborateur } : tache
      )
    );
  };

  const activerModification = (tache: IUnderTask) => {
    setModificationId(tache.id);
    setTexteModifie(tache.name);
  };

  const sauvegarderModification = async (id: number) => {
    const subTaskToUpdate = sousTaches.find((tache) => tache.id === id);
    if (subTaskToUpdate && task) {
      const updatedSubTask: IUnderTask = {
        ...subTaskToUpdate,
        name: texteModifie,
        task: task, // Assurez-vous d'inclure la tâche principale
      };

      try {
        const updatedTask = await updateSubTask(id, updatedSubTask);
        setSousTaches(
          sousTaches.map((tache) => (tache.id === id ? updatedTask : tache))
        );
        setModificationId(0);
        setTexteModifie("");
      } catch (error) {
        console.error("Failed to update subtask:", error);
      }
    }
  };
  //-------------------------------------------------------------------------------------
  const handleTabChange = (event: any, newValue: any) => {
    setTabValue(newValue);
  };
  const handleTabChange1 = (event: any, newValue: any) => {
    setTabValue1(newValue);
  };
  //utiliser par la suite
  const handleChangeTaskDescription = useCallback((value: string) => {
    setTaskDescription(value);
  }, []);

  useEffect(() => {
    if (isEditorChanged && !isButtonClicked) {
      setIsButtonShown(true);
    } else {
      setIsButtonShown(false);
    }
  }, [isEditorChanged, isButtonClicked]);

  const handleButtonClick = () => {
    setIsButtonClicked(true);
    setIsButtonShown(false);
  };

  //------------------------------render--------------
  const renderHead = (
    <KanbanDetailsToolbar
      liked={liked ?? false}
      clicked={click.value}
      onClicked={click.onToggle}
      favorite={favorite}
      onFavorite={handleToggleFavorite}
      taskName={task?.name || ""}
      task={task}
      taskObserver={task?.observerIds || []}
      shared={task?.shared || []}
      onLike={handleToggleLikeTask}
      likeCount={likeCount}
      url={task?.url || ""}
      onDelete={onDeleteTask}
      onArchiveTask={async (id: number) => {
        await archiveTask(id);
      }}
      taskStatus={task?.status || ""}
      onCloseDetails={onCloseDetails}
      usersWhoLiked={usersWhoLiked}
      isManager={isManagerForSelectedAgency()}
    />
  );
  //-----------------------------------------------
  useEffect(() => {
    if (task) {
      setTaskName(task.name);
    }
  }, [task]);

  const updateTaskName = async (taskId: number, newName: string) => {
    try {
      const response = await axios.put(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/tasks/update/${taskId}/name`,
        null,
        {
          params: { newName },
        }
      );
      onUpdateTask(response.data);
      fetchTaskHistory();
    } catch (error) {
      console.error("Failed to update task name:", error);
    }
  };

  const handleChangeTaskName = async (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    const newName = event.target.value;
    setTaskName(newName);

    if (task) {
      await updateTaskName(task.id, newName);
    }
  };

  const renderName = (
    <Stack direction="row" alignItems="center" spacing={1}>
      <StyledFieldLabel variant="subtitle2">Name:</StyledFieldLabel>
      {isEditingName ? (
        <>
          <TextField
            value={newTaskName}
            onChange={(e) => setNewTaskName(e.target.value)}
            size="small"
            fullWidth
          />
          <IconButton onClick={handleSaveTaskName} color="primary">
            <Iconify icon="eva:checkmark-outline" />
          </IconButton>
          <IconButton onClick={handleCancelEditName} color="error">
            <Iconify icon="eva:close-outline" />
          </IconButton>
        </>
      ) : (
        <>
          <StyledFieldValue>{taskName}</StyledFieldValue>
          <IconButton onClick={handleEditName} color="primary">
            <Iconify icon="eva:edit-outline" />
          </IconButton>
        </>
      )}
    </Stack>
  );

  const { collaborators1 } = useGetCollaboratorsOfProject(project?.id || 0);
  const [collaboratorData, setCollaboratorData] = useState<collaborator[]>();
  const [managerData, setManagerData] = useState<collaborator | null>(null);

  const [isEditingReporter, setIsEditingReporter] = useState(false);

  const updateTaskManager = async (taskId: number, newManagerId: number) => {
    try {
      await axios.put(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/tasks/update/${taskId}/manager`,
        null,
        { params: { managerId: newManagerId } }
      );
      
      if (task) {
        onUpdateTask({ ...task, managerId: newManagerId });
      }
      fetchTaskHistory();
    } catch (error) {
      console.error("Failed to update task manager:", error);
      throw error;
    }
  };

  const handleAssignManager = async (newManagerId: number) => {
    try {
      if (task) {
        await updateTaskManager(task.id, newManagerId);
        const manager = await fetchCollaborator(newManagerId);
        setManagerData(manager);
      }
      setIsEditingReporter(false);
    } catch (error) {
      console.error("Failed to assign manager:", error);
      enqueueSnackbar("Failed to update manager", { variant: "error" });
    }
  };

  const renderReporter = (
    <Stack direction="row" alignItems="center">
      <StyledLabel>Reporter</StyledLabel>
      <Stack direction="row" flexWrap="wrap" alignItems="center" spacing={1}>
        {managerData ? (
          <Tooltip
            title={`${managerData.user.firstName} ${managerData.user.lastName}`}
          >
            <Avatar
              alt={managerData.user.lastName + " " + managerData.user.firstName}
              sx={{ width: 40, height: 40, flexShrink: 0, marginRight: 1 }}
            >
              <Avatar>
                {managerData.user.firstName?.charAt(0).toUpperCase()}
                {managerData.user.lastName?.charAt(0).toUpperCase()}
              </Avatar>
            </Avatar>
          </Tooltip>
        ) : (
          <Avatar sx={{ width: 40, height: 40, flexShrink: 0, marginRight: 1 }}>
            ?
          </Avatar>
        )}

        <Tooltip title="Change reporter">
          <IconButton
            onClick={() => {
              const isManager = isManagerForSelectedAgency();
              if (isManager) {
                setIsEditingReporter(true);
              } else {
                enqueueSnackbar("Only managers can modify the reporter.", {
                  variant: "warning",
                });
              }
            }}
            sx={{
              bgcolor: (theme) => alpha(theme.palette.grey[500], 0.08),
              border: (theme) => `dashed 1px ${theme.palette.divider}`,
            }}
          >
            <Iconify icon="eva:edit-outline" />
          </IconButton>
        </Tooltip>

        {/* Dialog for selecting new manager */}
        <Dialog
          open={isEditingReporter}
          onClose={() => setIsEditingReporter(false)}
          maxWidth="sm"
          fullWidth
        >
          <DialogTitle>Select Reporter</DialogTitle>
          <DialogContent>
            <Stack spacing={2}>
              {availableCollaborators.map((collaborator) => (
                <ListItem
                  key={collaborator.id}
                  button
                  onClick={() => handleAssignManager(collaborator.id)}
                >
                  <ListItemAvatar>
                    <Avatar>
                      {collaborator.user.firstName?.charAt(0).toUpperCase()}
                      {collaborator.user.lastName?.charAt(0).toUpperCase()}
                    </Avatar>
                  </ListItemAvatar>
                  <ListItemText
                    primary={`${collaborator.user.firstName} ${collaborator.user.lastName}`}
                    secondary={collaborator.user.email}
                  />
                </ListItem>
              ))}
            </Stack>
          </DialogContent>
        </Dialog>
      </Stack>
    </Stack>
  );

  const [collaboratorsData, setCollaboratorsData] = useState<collaborator[]>(
    []
  );
  const updateCollaborators = async (collaboratorIds: number[]) => {
    const collaborators = await Promise.all(
      collaboratorIds.map(async (id) => {
        const collaborator = await fetchCollaborator(id);
        return collaborator;
      })
    );

    setCollaboratorsData(
      collaborators.filter(
        (collaborator) => collaborator !== null
      ) as collaborator[]
    );
  };

  useEffect(() => {
    if (task?.collaboratorIds && task.collaboratorIds.length > 0) {
      updateCollaborators(task.collaboratorIds);
    } else {
      setCollaboratorsData([]);
    }
  }, [task?.collaboratorIds]);

  const handleAssignToggle = async (collaborator: collaborator) => {
    try {
      const isAlreadyAssigned = task?.collaboratorIds.includes(collaborator.id);

      if (!isAlreadyAssigned) {
        task?.collaboratorIds.push(collaborator.id);
        
        // Send notification to the newly assigned collaborator
        const firebaseToken = await generateToken();

        if (firebaseToken && collaborator.user?.email) {
          const notificationData: INotif = {
            firebaseToken,
            email: collaborator.user.email,
          };

          try {
            const notifResponse = await sendNotificationToUserAfterAssigningTask(notificationData);
          } catch (notifError) {
            console.error('Error sending notification:', notifError);
          }
        } else {
          console.warn('Failed to generate Firebase token or missing collaborator email');
        }
      } else {
        return;
      }

      const response = await axiosInstance.put(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/tasks/update/${task?.id}/collaborators`,
        null,
        {
          params: {
            collaboratorIds: task?.collaboratorIds.join(","),
          },
        }
      );

      if (response.status === 200) {
        await updateCollaborators(task?.collaboratorIds ?? []);
      } else {
        console.error("Failed to update collaborators");
      }
    } catch (error) {
      console.error("Error in handleAssignToggle:", error);
    }
  };

  const transformedCollaboratorsData: collaborator[] = collaboratorsData.map(
    (data) => ({
      id: data.id,
      successCount: data.successCount,
      user: {
        firstName: data.user.firstName,
        lastName: data.user.lastName,
        email: data.user.email,
        phoneNumber: data.user.phoneNumber,
      },
    })
  );

  const renderAssignee = (
    <Stack direction="row">
      <StyledLabel sx={{ height: 40, lineHeight: "40px" }}>
        Assignee
      </StyledLabel>
  
      <Stack direction="row" flexWrap="wrap" alignItems="center" spacing={1}>
        {collaboratorsData &&
          collaboratorsData.map((user) => (
            <Tooltip
              key={user.id}
              title={`${user.user.firstName} ${user.user.lastName}`}
            >
              <Avatar
                alt={user.user.lastName + " " + user.user.firstName}
                sx={{ width: 40, height: 40, flexShrink: 0, marginRight: 1 }}
              >
                <Avatar>
                  {user.user.firstName?.charAt(0).toUpperCase()}
                  {user.user.lastName?.charAt(0).toUpperCase()}
                </Avatar>
              </Avatar>
            </Tooltip>
          ))}
  
        {/* Add Assignee Button */}
        <Tooltip title="Add assignee">
  <IconButton
    onClick={() => {
      const isManager = isManagerForSelectedAgency(); 

      if (isManager) {
        contacts.onTrue(); 
      } else {
        enqueueSnackbar("Only managers can modify the assignee.", {
          variant: "warning", 
        });
      }
    }}
    sx={{
      bgcolor: (theme) => alpha(theme.palette.grey[500], 0.08),
      border: (theme) => `dashed 1px ${theme.palette.divider}`,
    }}
  >
    <Iconify icon="mingcute:add-line" />
  </IconButton>
</Tooltip>

  
        {/* Kanban Contacts Dialog */}
        <KanbanContactsDialog
          assignee={availableCollaborators}
          projectId={project1?.id || 0}
          open={contacts.value}
          onClose={contacts.onFalse}
          onAssignToggle={handleAssignToggle}
        />
      </Stack>
    </Stack>
  );
  
  

  function formatDate(date: any) {
    if (!date || !(date instanceof Date)) {
      console.error("La variable n'est pas un objet Date valide.");
      return "";
    }
    const day = date.getDate().toString().padStart(2, "0");
    const month = new Intl.DateTimeFormat("en", { month: "short" }).format(
      date
    );
    const year = date.getFullYear();
    return `${day} ${month} ${year}`;
  }

  //***********************************************************/
  const updateTaskDateAPI = async (taskId: number, newEndDate: Date) => {
    try {
      await axios.put(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/tasks/update/${taskId}/date`,
        null,
        { params: { endDate: newEndDate.toISOString().split("T")[0] } }
      );
      
      if (task) {
        onUpdateTask({ ...task, endDate: newEndDate.toISOString() });
      }
    } catch (error) {
      console.error("Failed to update task date:", error);
      throw error;
    }
  };

  const handleDateChange = async (newDate: any) => {
    setEndDate(newDate);
    setShowDatePicker(false);

    if (task && newDate) {
      try {
        await updateTaskDateAPI(task.id, newDate);
        fetchTaskHistory();
      } catch (error) {
        console.error("Failed to update task date:", error);
      }
    }
  };

  const renderDueDate = (
    <Stack direction="row" alignItems="center">
      <StyledLabel>Due date</StyledLabel>

      {endDate ? (
        <Tooltip title="View due date">
          <Button size="small" onClick={() => setShowDatePicker(true)}>
            {formatDate(endDate)}
            {/* Afficher la date de fin */}
          </Button>
        </Tooltip>
      ) : (
        <Tooltip title="Add due date">
          <IconButton
            onClick={() => setShowDatePicker(true)}
            sx={{
              bgcolor: (theme) => alpha(theme.palette.grey[500], 0.08),
              border: (theme) => `dashed 1px ${theme.palette.divider}`,
            }}
          >
            <Iconify icon="mingcute:add-line" />
          </IconButton>
        </Tooltip>
      )}

      {showDatePicker && (
        <div style={{ display: "none" }}>
          <LocalizationProvider dateAdapter={AdapterDateFns}>
            <DatePicker
              open={true}
              value={endDate}
              onChange={handleDateChange}
              onClose={() => setShowDatePicker(false)}
            />
          </LocalizationProvider>
        </div>
      )}
    </Stack>
  );
  //----------------------------------------------------
  const updateTaskPriority = async (taskId: number, newPriority: string) => {
    try {
      await axios.put(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/tasks/update/${taskId}/priority`,
        null,
        { params: { priority: newPriority } }
      );
      
      if (task) {
        onUpdateTask({ ...task, priority: newPriority });
      }
      fetchTaskHistory();
    } catch (error) {
      console.error("Failed to update task priority:", error);
    }
  };

  const handleChangePriority = async (newPriority: string) => {
    setPriority(newPriority);

    if (task) {
      await updateTaskPriority(task.id, newPriority);
    }
  };

  const renderPriority = (
    <Stack direction="row" alignItems="center">
      <StyledLabel>Priority</StyledLabel>

      <TaskDetailsPriority
        priority={priority}
        onChangePriority={handleChangePriority}
      />
    </Stack>
  );
  //------------------------------------------------------------------------------

  const updateTaskDescription = async (taskId: number, newDescription: string) => {
    try {

      const response = await axios.put(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/tasks/update/${taskId}/description`,
        newDescription,
        { headers: { 'Content-Type': 'text/plain' } } 
    );
      onUpdateTask(response.data);
      fetchTaskHistory();
    } catch (error) {
      console.error("Failed to update task description:", error);
    }
  };

  const handleEditorChange = async (newDescription: string) => {
    setTaskDescription(newDescription);

    if (task) {
      await updateTaskDescription(task.id, newDescription);
    }
  };
  const renderDescription = (
    <Stack direction="column" spacing={1}>
      <StyledLabel>Description</StyledLabel>
      <FormProvider {...methods}>
        <Controller
          name="description"
          control={control}
          render={({ field }) => (
            <RHFEditor
              name={field.name}
              value={field.value}
              onChange={(newValue) => {
                field.onChange(newValue);
                setNewDescription(newValue);
              }}
              simple
            />
          )}
        />
      </FormProvider>
      {newDescription !== task?.description && (
        <Button
          variant="contained"
          size="small"
          sx={{ mt: 1 }}
          onClick={handleSaveDescription}
        >
          Save
        </Button>
      )}
    </Stack>
  );

  //****************************************************/
  const updateTaskPoint = async (taskId: number, newPoints: number) => {
    try {
      await axios.put(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/tasks/update/${taskId}/point`,
        null,
        { params: { point: newPoints } }
      );
      
      if (task) {
        onUpdateTask({ ...task, point: newPoints });
      }
      fetchTaskHistory();
    } catch (error) {
      console.error("Failed to update task points:", error);
    }
  };

  const handleChangeTaskMark = async (
    event: React.ChangeEvent<HTMLInputElement>
  ) => {
    const newMark = parseInt(event.target.value, 10);
    setTaskMark(newMark);

    if (task) {
      await updateTaskPoint(task.id, newMark);
    }
  };

  const renderMark = (
    <Stack direction="row" alignItems="center" spacing={1}>
      <Typography
        variant="subtitle2"
        sx={{ minWidth: 80, color: "text.secondary", fontWeight: "bold" }}
      >
        Points:
      </Typography>
      {isEditingMark ? (
        <>
          <TextField
            value={newMark}
            onChange={(e) => setNewMark(Number(e.target.value))}
            size="small"
            fullWidth
            type="number"
            InputProps={{ inputProps: { min: 0 } }} // Ensure non-negative values
          />
          <IconButton onClick={handleSaveMark} color="primary">
            <Iconify icon="eva:checkmark-outline" />
          </IconButton>
          <IconButton onClick={() => setIsEditingMark(false)} color="error">
            <Iconify icon="eva:close-outline" />
          </IconButton>
        </>
      ) : (
        <>
          <Typography
            variant="body2"
            sx={{
              color: "text.primary",
              fontWeight: "medium",
            }}
          >
            {newMark || "No Points Assigned"}
          </Typography>
          <IconButton onClick={() => setIsEditingMark(true)} color="primary">
            <Iconify icon="eva:edit-outline" />
          </IconButton>
        </>
      )}
    </Stack>
  );

  //************************************************* */
  const renderAttachments = (
    <Stack direction="row">
      <StyledLabel>upload a file</StyledLabel>
      <TaskDetailsAttachments
        attachments={task?.attachments}
        taskId={task?.id}
      />
    </Stack>
  );

  //***********************************/
  const updateTaskType = async (taskId: number, newType: string) => {
    try {
      await axios.put(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/tasks/update/${taskId}/type`,
        null,
        { params: { type: newType } }
      );
      
      if (task) {
        onUpdateTask({ ...task, type: newType });
      }
      fetchTaskHistory();
    } catch (error) {
      console.error("Failed to update task type:", error);
    }
  };
  const handleSaveType = async () => {
    try {
      if (task && newType) {
        await updateTaskType(task.id, newType);

        setType(newType);
      }
      setIsEditingType(false);
    } catch (error) {
      console.error("Failed to update task type:", error);
    }
  };

  const handleTypeChange = async (
    event: React.ChangeEvent<{ value: unknown }>
  ) => {
    const newType = event.target.value as string;
    setType(newType);

    if (task) {
      await updateTaskType(task.id, newType);
    }
  };

  const renderType = (
    <Stack direction="row" alignItems="center" spacing={1}>
      <Typography
        variant="subtitle2"
        sx={{ minWidth: 80, color: "text.secondary", fontWeight: "bold" }}
      >
        Type:
      </Typography>
      {isEditingType ? (
        <>
          <Select
            value={newType}
            onChange={(e) => setNewType(e.target.value)}
            size="small"
            fullWidth
          >
            {["BUG", "FEATURE"].map((option) => (
              <MenuItem key={option} value={option}>
                {option}
              </MenuItem>
            ))}
          </Select>
          <IconButton onClick={handleSaveType} color="primary">
            <Iconify icon="eva:checkmark-outline" />
          </IconButton>
          <IconButton onClick={() => setIsEditingType(false)} color="error">
            <Iconify icon="eva:close-outline" />
          </IconButton>
        </>
      ) : (
        <>
          <Typography
            variant="body2"
            sx={{
              color: "text.primary",
              fontWeight: "medium",
            }}
          >
            {type || "No Type"}
          </Typography>
          <IconButton onClick={() => setIsEditingType(true)} color="primary">
            <Iconify icon="eva:edit-outline" />
          </IconButton>
        </>
      )}
    </Stack>
  );

  //**************************************************************/

  const updateTaskStatus = async (taskId: number, newStatus: string) => {
    try {
      await axios.put(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/tasks/update/${taskId}/status`,
        null,
        { params: { status: newStatus } }
      );
      
      // Only update the status field in the task
      if (task) {
        onUpdateTask({ ...task, status: newStatus });
      }
      fetchTaskHistory();
    } catch (error) {
      console.error("Failed to update task status:", error);
    }
  };
  const handleSaveStatus = async () => {
    try {
      if (task && newStatus) {
        await updateTaskStatus(task.id, newStatus);
        setStatus(newStatus);

        const firebaseToken = await generateToken();
      

        if (firebaseToken && task.collaboratorIds) {
          for (const collaboratorId of task.collaboratorIds) {
            try {
              const response = await axiosInstance.get(
                `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/user/accountagency/id`,
                {
                  params: { Id: collaboratorId }
                }
              );
              const collaborator = response.data;
              
              if (collaborator?.user?.email) {
                const notificationData: INotif = {
                  firebaseToken,
                  email: collaborator.user.email,
                };
              
                await sendNotificationToUserAfterChangingTaskStatus(notificationData);
              }
            } catch (error) {
              console.error(`Error fetching collaborator ${collaboratorId}:`, error);
            }
          }
        }
      }
      setIsEditingStatus(false);
    } catch (error) {
      console.error("Failed to save task status:", error);
    }
  };

  const handleStatusChange = async (event: React.ChangeEvent<{ value: unknown }>) => {
    const newStatus = event.target.value as string;
    setStatus(newStatus);

    if (task) {
      try {
        // Update task status
        await updateTaskStatus(task.id, newStatus);
        }
       catch (error) {
        console.error('Error updating task status:', error);
      }
    }
  };

  const handleCancelEditStatus = () => {
    setNewStatus(status || ""); // Revert to original value
    setIsEditingStatus(false);
  };
  const handleEditStatus = () => {
    setNewStatus(status || ""); // Initialize with current value
    setIsEditingStatus(true);
  };

  const renderStatus = (
    <Stack direction="row" alignItems="center" spacing={1}>
      <Typography
        variant="subtitle2"
        sx={{ minWidth: 80, color: "text.secondary", fontWeight: "bold" }}
      >
        Status:
      </Typography>
      {isEditingStatus ? (
        <>
          <Select
            value={newStatus}
            onChange={(e) => setNewStatus(e.target.value)}
            size="small"
            fullWidth
          >
            {["TO DO", "IN PROGRESS", "DONE"].map((option) => (
              <MenuItem key={option} value={option}>
                {option}
              </MenuItem>
            ))}
          </Select>
          <IconButton onClick={handleSaveStatus} color="primary">
            <Iconify icon="eva:checkmark-outline" />
          </IconButton>
          <IconButton onClick={() => setIsEditingStatus(false)} color="error">
            <Iconify icon="eva:close-outline" />
          </IconButton>
        </>
      ) : (
        <>
          <Typography
            variant="body2"
            sx={{
              color: "text.primary",
              fontWeight: "medium",
            }}
          >
            {status || "No Status"}
          </Typography>
          <IconButton onClick={() => setIsEditingStatus(true)} color="primary">
            <Iconify icon="eva:edit-outline" />
          </IconButton>
        </>
      )}
    </Stack>
  );

  //-------------------------------------------------------------

  const [collaboratorsSubtask, setCollaboratorsSubtask] = useState<{
    [key: number]: collaborator | null;
  }>({});

  useEffect(() => {
    const fetchCollaborators = async () => {
      for (let tache of sousTaches) {
        if (tache.collaboratorId) {
          try {
            const collaborator = await fetchCollaborator(tache.collaboratorId);
            setCollaboratorsSubtask((prev) => ({
              ...prev,
              [tache.id]: collaborator,
            }));
          } catch (error) {
            console.error("Failed to fetch collaborator:", error);
          }
        }
      }
    };

    fetchCollaborators();
  }, [sousTaches]);

  const renderUnderTask = (
    <Stack direction="row">
      <div>
        <Grid container spacing={1} alignItems="center">
          <Typography variant="h6">Manage your subtasks...</Typography>
          <Grid item xs={9}>
            <TextField
              fullWidth
              size="small"
              value={nouvelleSousTache}
              onChange={(e) => setNouvelleSousTache(e.target.value)}
              onKeyPress={handleKeyPress}
              placeholder="Add a subtask"
              variant="outlined"
            />
          </Grid>
          <Grid item xs={3}>
            <Button variant="contained" onClick={ajouterSousTache}>
              Add
            </Button>
          </Grid>
        </Grid>

        {sousTaches.map((tache) => {
          const collaborator = collaboratorsSubtask[tache.id]; // Retrieve collaborator for the current task

          return (
            <ListItem
              key={tache.id}
              onMouseEnter={() => handleTaskMouseEnter(tache.id)}
              onMouseLeave={handleTaskMouseLeave}
            >
              {modificationId === tache.id ? (
                <Grid container spacing={1} alignItems="center">
                  <Grid item xs={9}>
                    <TextField
                      fullWidth
                      size="small"
                      value={texteModifie}
                      onChange={(e) => setTexteModifie(e.target.value)}
                      variant="outlined"
                    />
                  </Grid>
                  <Grid item xs={3}>
                    <IconButton
                      onClick={() => sauvegarderModification(tache.id)}
                    >
                      <Iconify
                        icon="fluent:save-edit-24-filled"
                        width="1.2em"
                      />
                    </IconButton>
                  </Grid>
                </Grid>
              ) : (
                <>
                  <ListItemIcon>
                    <Iconify icon="lets-icons:check-fill" />
                  </ListItemIcon>
                  <ListItem
                    sx={{
                      display: "flex",
                      alignItems: "center",
                    }}
                  >
                    <ListItemText primary={tache.name} />

                    {/* Display Collaborator Information */}
                    <ListItemText
                      primary={
                        collaborator
                          ? `Assigned to ${collaborator.user.firstName} ${collaborator.user.lastName}`
                          : "No collaborator assigned"
                      }
                      sx={{ marginLeft: 4 }}
                    />

                    <ListItemAvatar>
                      {collaborator ? (
                        <Avatar
                          alt={`${collaborator.user.firstName} ${collaborator.user.lastName}`}
                          sx={{
                            width: 24,
                            height: 24,
                            flexShrink: 0,
                            marginLeft: 1,
                            fontSize: "1rem",
                          }}
                        >
                          <Avatar>
                            {collaborator.user.firstName?.charAt(0).toUpperCase()}
                            {collaborator.user.lastName?.charAt(0).toUpperCase()}
                          </Avatar>
                        </Avatar>
                      ) : (
                        <Avatar
                          sx={{
                            width: 24,
                            height: 24,
                            flexShrink: 0,
                            marginLeft: 1,
                            backgroundColor: "grey.400",
                          }}
                        >
                          ?
                        </Avatar>
                      )}
                    </ListItemAvatar>
                  </ListItem>

                  <IconButton onClick={() => activerModification(tache)}>
                    <Iconify icon="fluent:edit-48-filled" />
                  </IconButton>
                  <IconButton onClick={() => supprimerSousTache(tache.id)}>
                    <Iconify icon="solar:trash-bin-trash-bold" />
                  </IconButton>
                  <IconButton onClick={() => ouvrirAssigneeDialog(tache)}>
                    <Iconify icon="pajamas:assignee" />
                  </IconButton>
                </>
              )}
            </ListItem>
          );
        })}
      </div>

      <SubTaskContactsDialog
        assigne={
          collaboratorData && collaboratorData.length > 0
            ? collaboratorData[0]
            : undefined
        }
        projectId={project1?.id || 0}
        open={assigneeDialogOpen}
        onClose={() => setAssigneeDialogOpen(false)}
        onAssign={assignerCollaborateur}
      />
    </Stack>
  );

  //-------------------------------------------------------------------
  const [projects, setProjects] = useState<Project[]>([]);
  useEffect(() => {
    const fetchProjects = async () => {
      try {
        const response = await axios.get(`${endpoints.project.list}/1`);
        setProjects(response.data);
      } catch (error) {
        console.error("Erreur lors de la récupération des projets :", error);
      }
    };
    fetchProjects();
  }, []);

  const handleChangeProject = async (event: any) => {
    const newProjectId = parseInt(event.target.value, 10);
    const newProject =
      projects.find((project) => project.id === newProjectId) || null;

    setProject(newProject);

    if (task && newProject) {
      try {
        const updatedTask = await updateTaskProject(task.id, newProject);
        onUpdateTask(updatedTask);
      } catch (error) {
        console.error("Failed to update task project:", error);
      }
    }
  };

  const updateTaskProject = async (taskId: number, newProject: Project) => {
    try {
      const response = await axios.put(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/tasks/${taskId}/project`,
        newProject,
        {
          headers: {
            "Content-Type": "application/json",
          },
        }
      );
      return response.data;
    } catch (error) {
      console.error("Failed to update task project:", error);
      throw error;
    }
  };
  const handleDeleteComment = async (commentId: number) => {
    try {
      await deleteComment(commentId);
      setListData((prevComments) =>
        prevComments.filter((comment) => comment.id !== commentId)
      );
    } catch (error) {
      console.error("Failed to delete comment:", error);
    }
  };

  const renderProject = (
    <Stack direction="row" alignItems="center">
      <StyledLabel>Project</StyledLabel>
      <Typography
        variant="body2"
        sx={{
          color: "text.primary",
          fontWeight: "medium",
        }}
      >
        {project1 ? project1.name : "No project assigned"}
      </Typography>
    </Stack>
  );

  const [replyingToCommentId, setReplyingToCommentId] = useState<number | null>(
    null
  );
  const handleToggleLike = async (commentId: number) => {
    try {
      await toggleLike(commentId);

      setListData((prevComments) =>
        prevComments.map((comment) =>
          comment.id === commentId
            ? { ...comment, isLiked: !comment.isLiked }
            : comment
        )
      );
    } catch (error) {
      console.error("Failed to toggle like:", error);
    }
  };

  const renderComments = (
    <Stack
      spacing={3}
      flexGrow={1}
      sx={{
        py: 3,
        px: 2.5,
      }}
    >
      {listData.map((comment) => {
        const collaborator = commentCollaborators[comment.collaboratorId as number];
        return (
          <Stack
            key={comment.id}
            direction="row"
            spacing={2}
            sx={{
              border: "1px solid",
              borderColor: "divider",
              borderRadius: 2,
              p: 2,
              margin: "8px 0",
            }}
          >
            {/* Collaborator Avatar */}
            <Avatar alt={collaborator?.user?.firstName || "?"}>
              <Avatar>
                {collaborator?.user?.firstName?.charAt(0).toUpperCase()}
                {collaborator?.user?.lastName?.charAt(0).toUpperCase()}
              </Avatar>
            </Avatar>

            <Stack spacing={0.5} flexGrow={1}>
              {/* Header: User and Timestamp */}
              <Stack
                direction="row"
                alignItems="center"
                justifyContent="space-between"
              >
                <Typography variant="subtitle2">
                  {collaborator?.user?.firstName} {collaborator?.user?.lastName}
                </Typography>

                <Stack
                  direction="row"
                  alignItems="center"
                  justifyContent="space-between"
                >
                  <Typography variant="caption" sx={{ color: "text.disabled" }}>
                    {fToNow(comment.createdAt)}
                  </Typography>
                  <Tooltip
                    title={comment.type === "PUBLIC" ? "Public" : "Private"}
                  >
                    <IconButton
                      size="small"
                      color={comment.type === "PRIVATE" ? "info" : "default"}
                      sx={{ borderRadius: 1 }}
                    >
                      {comment.type == "PUBLIC" ? (
                        <Iconify
                          width={14}
                          icon="octicon:feed-public-16"
                          sx={{ mr: -0.75 }}
                        />
                      ) : (
                        <Iconify
                          width={16}
                          icon="ri:chat-private-fill"
                          sx={{ mr: -0.75 }}
                        />
                      )}
                    </IconButton>
                  </Tooltip>
                </Stack>
              </Stack>

              {/* Comment Message */}
              <Typography variant="body2">{comment.message}</Typography>
              <Divider sx={{ my: 1 }} />

              {/* Actions: Like, Show Users, Reply, Delete */}
              <Stack
                direction="row"
                justifyContent="flex-end"
                alignItems="center"
                spacing={1}
              >
                {/* Like Button */}
                <Tooltip title="Like">
                  <IconButton
                    onClick={() => {
                      if (comment.id !== undefined) {
                        handleToggleLikeComment(comment.id);
                      }
                    }}
                    color={commentLiked[comment.id || 0] ? "info" : "default"}
                  >
                    <Iconify icon="ic:round-thumb-up" />
                  </IconButton>
                </Tooltip>

                {/* Like Count */}
                <Typography variant="caption" sx={{ alignSelf: "center" }}>
                  {commentLikeCount[comment.id || 0] || 0} Likes
                </Typography>

                {/* Show Users Who Liked */}
                <Tooltip title="Who liked this?">
                  <IconButton
                    onClick={() => {
                      if (comment.id !== undefined)
                        toggleUsersWhoLikedComment(comment.id);
                    }}
                    sx={{ alignSelf: "center" }}
                  >
                    <Iconify icon="ic:outline-info" />
                  </IconButton>
                </Tooltip>

                {/* Dropdown for Users Who Liked */}
                {showUsersWhoLiked === comment.id && (
                  <Box
                    sx={{
                      position: "absolute",
                      top: 40,
                      right: 0,
                      bgcolor: "background.paper",
                      boxShadow: 1,
                      borderRadius: 1,
                      p: 1,
                      zIndex: 10,
                      width: 200,
                    }}
                  >
                    <Typography variant="subtitle2" sx={{ mb: 1 }}>
                      Liked By:
                    </Typography>
                    {usersWhoLikedComment[comment.id]?.length > 0 ? (
                      <ul style={{ margin: 0, padding: 0, listStyle: "none" }}>
                        {usersWhoLikedComment[comment.id].map((user, index) => (
                          <li key={index}>
                            <Typography variant="body2">{user}</Typography>
                          </li>
                        ))}
                      </ul>
                    ) : (
                      <Typography variant="body2" color="textSecondary">
                        No likes yet.
                      </Typography>
                    )}
                  </Box>
                )}

                {/* Reply Button */}
                <Tooltip title="Reply">
                  <IconButton
                    onClick={() => {
                      if (comment.id) setReplyingToCommentId(comment.id);
                    }}
                  >
                    <Iconify icon="ic:baseline-reply" />
                  </IconButton>
                </Tooltip>

                {/* Delete Button */}
                <Tooltip title="Delete">
                  <IconButton onClick={() => confirm.onTrue()}>
                    <Iconify icon="solar:trash-bin-trash-bold" />
                  </IconButton>
                </Tooltip>
              </Stack>

              {/* Confirm Dialog for Deletion */}
              <ConfirmDialog
                open={confirm.value}
                onClose={confirm.onFalse}
                title="Delete"
                content={<>Are you sure want to delete this comment?</>}
                action={
                  <Button
                    variant="contained"
                    color="error"
                    onClick={() => {
                      if (comment.id) handleDeleteComment(comment.id);
                      confirm.onFalse();
                    }}
                  >
                    Delete
                  </Button>
                }
              />

              {/* Reply Comments */}
              {comment.id !== undefined && (
                <ReplyCommentList
                  idComment={comment.id}
                  replyingToCommentId={replyingToCommentId}
                  setReplyingToCommentId={setReplyingToCommentId}
                />
              )}
            </Stack>
          </Stack>
        );
      })}
    </Stack>
  );

  const archiveTask = async (taskId: number) => {
    try {
      const response = await axios.post(
        `${process.env.NEXT_PUBLIC_GATEWAY_API}/api/projects/api/tasks/archive/${taskId}`
      );
      
      if (response.status === 200) {
        enqueueSnackbar("Task archived successfully", { variant: "success" });
        onCloseDetails(); 
      }
    } catch (error) {
      enqueueSnackbar("Failed to archive task", { variant: "error" });
    }
  };

  return (
    <Dialog open={openDetails} onClose={onCloseDetails} maxWidth="xl" fullWidth>
      <DialogTitle>{renderHead}</DialogTitle>
      <Divider />
      <DialogContent sx={{ overflowY: "hidden" }} dividers>
        <Grid container spacing={3}>
          <Grid item xs={12} md={5.95}>
            {renderName}
            <Scrollbar
              sx={{
                height: "calc(100vh - 200px)",
                "& .simplebar-content": {
                  height: "auto",
                  display: "flex",
                  flexDirection: "column",
                },
              }}
            >
              <Stack
                spacing={3}
                sx={{
                  pt: 3,
                  pb: 5,
                  px: 2.5,
                }}
              >
                {renderReporter}
                {renderAssignee}
                {renderDueDate}
                {renderType}
                {renderStatus}
                {renderProject}
                {renderPriority}
                {renderDescription}
                {renderMark}
                <TabContext value={tabValue1}>
                  <Box sx={{ borderBottom: 1, borderColor: "divider" }}>
                    <Tabs value={tabValue1} onChange={handleTabChange1}>
                      <Tab
                        label="sub-Tasks"
                        value="sous-taches"
                        icon={<AssignmentIcon />}
                      />
                      <Tab
                        label="Attachments"
                        value="pieces-jointes"
                        icon={<AttachFileIcon />}
                      />
                    </Tabs>
                  </Box>
                  <TabPanel value="sous-taches">{renderUnderTask}</TabPanel>
                  <TabPanel value="pieces-jointes">
                    {renderAttachments}
                  </TabPanel>
                </TabContext>
              </Stack>
            </Scrollbar>
          </Grid>

          <Divider orientation="vertical" flexItem />

          <Grid item xs={12} md={6} sx={{ bgcolor: "background.paper" }}>
            <Typography variant="h5">Activity</Typography>
            <Grid item>
              <Tabs value={tabValue} onChange={handleTabChange}>
                <Tab label="Comment" icon={<CommentIcon />} />
                <Tab label="History" icon={<HistoryIcon />} />
              </Tabs>
            </Grid>

            {tabValue === 0 && (
              <Box
                sx={{
                  height: "calc(100vh - 200px)",
                  display: "flex",
                  flexDirection: "column",
                  bgcolor: "background.paper",
                }}
              >
                <Box
                  sx={{
                    overflowY: "auto",
                    flexGrow: 1,
                    bgcolor: "background.paper",
                  }}
                >
                  <Scrollbar
                    sx={{
                      height: "calc(100vh - 200px)",
                      "& .simplebar-content": {
                        height: "auto",
                        display: "flex",
                        flexDirection: "column",
                      },
                    }}
                  >
                    {comments.length > 0 ? renderComments : "No Comments"}
                  </Scrollbar>
                </Box>
                {task?.id !== undefined && (
                  <div style={{ marginBottom: "20px" }}>
                    <KanbanDetailsCommentInput
                      onAddComment={handleAddComment}
                      idTask={task.id}
                    />
                  </div>
                )}
              </Box>
            )}
            {tabValue === 1 && (
              <Box sx={{ p: 2 }}>
                <Scrollbar
                  sx={{
                    height: "calc(100vh - 200px)",
                    "& .simplebar-content": {
                      height: "auto",
                      display: "flex",
                      flexDirection: "column",
                    },
                  }}
                >
                  <TaskHistory
                    title="Task History"
                    subheader="Changes made to this task"
                    list={taskHistory}
                  />{" "}
                </Scrollbar>
              </Box>
            )}
          </Grid>
        </Grid>
      </DialogContent>
    </Dialog>
  );
}
