import { ActionIcon, Avatar, Button, Flex, Select, Text, Textarea, Title, Timeline, Box, Popover, Paper, ScrollArea } from '@mantine/core';
import { IconChevronDown, IconPointFilled, IconTrash, IconTrashX } from '@tabler/icons-react';
import React, { Fragment, useEffect, useState, useRef } from 'react';
import { useDisclosure } from '@mantine/hooks';
import { useDispatch, useSelector } from "react-redux";
import { useEditor, EditorContent } from '@tiptap/react';
import { Link, RichTextEditor } from '@mantine/tiptap';
import StarterKit from '@tiptap/starter-kit';
import Underline from '@tiptap/extension-underline';
import Placeholder from '@tiptap/extension-placeholder';
import Mention from '@tiptap/extension-mention';
import TextAlign from '@tiptap/extension-text-align';
import { createComment, deleteComment } from "../../../Settings/store/taskSlice";
import { modals } from "@mantine/modals";
import { hasPermission, useProjectPermissions } from "../../../ui/permissions";
import dayjs from "dayjs";
import { translate } from '../../../../utils/i18n';

const TaskComment = ({ task, selectedValue, hideInput, hideList }) => {

  const dispatch = useDispatch();
  const rawMembers = task && task.project && task.project.members;
  const [comments, setComments] = useState(task && task.comments ? task.comments : []);
  const [commentText, setCommentText] = useState('');
  const { loggedUserId, name } = useSelector((state) => state.auth.user)
  const { loggedInUser } = useSelector((state) => state.auth.session)
  const dateTimeFormat = 'DD MMM YYYY hh:mm A'
  const [mentionPopoverOpened, setMentionPopoverOpened] = useState(false);
  const [popoverTarget, setPopoverTarget] = useState(null);
  const [mentionItems, setMentionItems] = useState([]);
  const [mentionCommand, setMentionCommand] = useState(() => () => { });
  const mentionAnchorRef = useRef(null);
  const { projectInfo } = useSelector((state) => state.settings.task);
  const projectPermissions = useProjectPermissions(projectInfo?.id);


  const formatTimestamp = (timestamp) => {
    const now = new Date();
    const commentTime = new Date(timestamp);
    const timeDiff = Math.abs(now - commentTime) / 1000; // in seconds

    if (timeDiff < 60) {
      return 'Just now';
    } else if (timeDiff < 3600) {
      const minutes = Math.floor(timeDiff / 60);
      return `${minutes} min ago`;
    } else if (timeDiff < 86400) {
      const hours = Math.floor(timeDiff / 3600);
      return `${hours} hour${hours > 1 ? 's' : ''} ago`;
    } else {
      return commentTime.toLocaleString();
    }
  };

  const handleAddComment = () => {
    const timestamp = new Date().toISOString();
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = commentText;

    // Find all mention elements
    const mentions = tempDiv.querySelectorAll('.mention');
    const mentionedUsers = Array.from(mentions).map(mention => ({
      id: mention.getAttribute('data-id'),
      name: mention.getAttribute('data-label')
    }));
    const newComment = {
      user_id: loggedInUser?.loggedUserId || loggedUserId,
      user_name: loggedInUser?.name || name,
      commentable_id: task && task.id ? task.id : null,
      commentable_type: 'task',
      content: commentText,
      mention_users: mentionedUsers,
      created_at: formatTimestamp(timestamp)
    };
    dispatch(createComment(newComment)).then((response) => {
      if (response.payload && response.payload.data) {
        setComments([response.payload.data, ...comments]);
        editor?.commands.clearContent();
        setCommentText('');
      }
    });
    setCommentText(''); // Clear textarea
  };
  useEffect(() => {
    setComments(task && task.comments ? task.comments : []);
  }, [task.comments]);

  const commentDeleteHandler = (commentId) => modals.openConfirmModal({
    title: (
      <Title order={5}>Are you sure this comment delete?</Title>
    ),
    size: 'sm',
    radius: 'md',
    withCloseButton: false,
    children: (
      <Text size="sm">
        This action is so important that you are required to confirm it with a modal. Please click
        one of these buttons to proceed.
      </Text>
    ),
    labels: { confirm: 'Confirm', cancel: 'Cancel' },
    onCancel: () => console.log('Cancel'),
    onConfirm: () => {
      if (commentId && commentId !== 'undefined') {
        dispatch(deleteComment({ id: commentId, data: { 'deleted_by': loggedUserId } })).then((response) => {
          if (response.payload && response.payload.data) {
            setComments(comments.filter(comment => comment.id !== response.payload.data.id));

          }
        });
      }
    },
  });

  const drawerRef = useRef(null);

  const [mentionProps, setMentionProps] = useState(null);
  const membersRef = useRef([]);
  useEffect(() => {
    if (rawMembers && rawMembers.length) {
      membersRef.current = rawMembers.map(user => ({
        id: user.id,
        label: user.name,
        avatar: user.avatar
      }));
    }
  }, [rawMembers]);

  const editor = useEditor({
    extensions: [
      StarterKit,
      Link.configure({
        autolink: true,
        linkOnPaste: true,
        openOnClick: true,
        HTMLAttributes: {
          target: '_blank',
          rel: 'noopener noreferrer'
        }
      }),
      Underline,
      TextAlign.configure({
        types: ['heading', 'paragraph'],
      }),
      Placeholder.configure({ placeholder: 'Type your comment here...' }),
      Mention.configure({
        HTMLAttributes: {
          class: 'mention',
          'data-id': 'id',
          'data-label': 'label'
        },
        renderText: ({ node }) => `@${node.attrs.label}`,
        suggestion: {
          char: '@',
          items: ({ query }) =>
            membersRef.current.filter(u =>
              u.label.toLowerCase().startsWith(query.toLowerCase())
            ),
          render: () => {
            return {
              onStart: (props) => {
                setMentionProps(props);
                setMentionItems(props.items);
                setMentionCommand(() => props.command);
                setMentionPopoverOpened(true);
              },
              onUpdate: (props) => {
                setMentionProps(props);
                setMentionItems(props.items);
                setMentionCommand(() => props.command);
              },
              onExit: () => {
                setMentionProps(props);
                setMentionPopoverOpened(false);
                setPopoverTarget(null);
                setMentionItems([]);
              },
            };
          },
        },
      }),
    ],
    content: commentText,
    onUpdate: ({ editor }) => {
      setCommentText(editor.getHTML());
    },
  });


  return (
    <Fragment>
      {!hideInput && selectedValue === 'Only Comments' && (() => {
        const isCreatorOrAssignee = task && (
          (task.createdBy_id != null && task.createdBy_id == loggedUserId) ||
          (task.assignedTo_id != null && task.assignedTo_id == loggedUserId)
        );
        const canComment = isCreatorOrAssignee || hasPermission(loggedInUser, ['add-comments'], projectPermissions, 'project');
        return (
        <div className="write-comments pb-1 mb-6">
          <div className={`bg-white border border-[#E2E8F0] shadow-sm rounded-xl p-4 ${!canComment ? 'opacity-50 pointer-events-none' : ''}`}>
            <div className="flex gap-3 w-full">
              <Avatar size={34} radius="xl"
                src={loggedInUser && loggedInUser.avatar ? loggedInUser.avatar : ''}
                alt={loggedInUser && loggedInUser.name} />

              <div className="flex-1">
                <RichTextEditor editor={editor} className="border-0 !p-0">
                  <RichTextEditor.Content
                    className="prose prose-sm min-h-[60px]"
                    spellCheck={false}
                  />

                  <div className="flex justify-between items-center mt-3 pt-3 border-t border-[#F1F5F9]">
                    <RichTextEditor.Toolbar className="border-0 p-0 bg-transparent">
                      <RichTextEditor.ControlsGroup>
                        <RichTextEditor.Bold />
                        <RichTextEditor.Italic />
                        <RichTextEditor.Underline />
                        <RichTextEditor.Strikethrough />
                        <RichTextEditor.Link />
                      </RichTextEditor.ControlsGroup>
                    </RichTextEditor.Toolbar>
                    <Button radius="md" color="#2563EB" size="sm" onClick={handleAddComment} disabled={!canComment}>{translate('Post')} ➔</Button>
                  </div>
                </RichTextEditor>
                <div ref={mentionAnchorRef} />
              </div>
            </div>
            {mentionProps && mentionProps.clientRect && ReactDOM.createPortal(
              <Box
                onMouseDown={(e) => {
                  e.preventDefault();
                  e.stopPropagation();
                }}
                style={{
                  position: 'absolute',
                  top: mentionProps.clientRect().bottom + window.scrollY,
                  left: mentionProps.clientRect().left + window.scrollX,
                  background: 'white',
                  border: '1px solid #ddd',
                  borderRadius: 4,
                  boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
                  zIndex: 9999,
                }}
              >
                {mentionProps.items.map(item => (
                  <Flex
                    key={item.id}
                    align="center"
                    px="sm"
                    py="xs"
                    style={{ cursor: 'pointer' }}
                    onMouseDown={(e) => {
                      e.preventDefault();
                      e.stopPropagation();
                      mentionProps.command({ id: item.id, label: item.label });
                      setTimeout(() => {
                        editor?.commands.focus();
                      }, 0);
                    }}
                  >
                    <Avatar src={item.avatar} size={24} radius="xl" mr={8} />
                    <Text>{item.label}</Text>
                  </Flex>
                ))}
              </Box>,
              document.body
            )}
          </div>
        </div>
        );
      })()}

      {
        !hideList && (
          <Timeline color="gray.3" bulletSize={40} lineWidth={2} style={{ textAlign: 'left', marginTop: '16px' }} classNames={{ itemBullet: 'bg-white' }}>
            {selectedValue === 'Only Comments' && comments && comments.length > 0 && comments.map((comment, index) => (
              <Timeline.Item
                key={index}
                className="mb-4"
                bullet={
                  <Avatar size={40} src={comment.avatar} alt={comment.user_name} radius="xl" className="border-[3px] border-white shadow-sm" />
                }
              >
                <div className="bg-white border border-[#E2E8F0] shadow-sm rounded-xl p-4 ml-2 mt-[-10px]">
                  <div className="flex justify-between items-start mb-2">
                    <div className="flex items-center gap-2">
                      <Text fw={600} fz={15} c="#0F172A">{comment.user_name}</Text>
                      <span className="px-2 py-0.5 rounded-full text-[10px] uppercase font-bold tracking-wide leading-none bg-[#EFF6FF] text-[#2563EB]">
                        COMMENT
                      </span>
                    </div>
                    <Text size="xs" c="#64748B">{comment.created_at ? dayjs(comment.created_at).format(dateTimeFormat) : ''}</Text>
                  </div>

                  <Flex
                    gap="xs"
                    justify="flex-start"
                    align="flex-start"
                    direction="column"
                    mt={8}
                  >
                    {comment.content && (
                      <div className="w-full">
                        <div className="comment-body mb-2">
                          <span
                            className={'gray-900 dark:text-gray-500 whitespace-pre-line custom-html-content text-sm'}
                            dangerouslySetInnerHTML={{ __html: comment.content }}
                          />
                        </div>
                        {(parseInt(loggedUserId) === parseInt(comment.user_id) ||
                          hasPermission(loggedInUser, ['delete-comments-by-others'], projectPermissions, 'project')) && (
                            <ActionIcon
                              onClick={() => commentDeleteHandler(comment && comment.id)}
                              variant="transparent"
                              aria-label="Delete"
                              className="mt-2"
                            >
                              <IconTrash size={16} stroke={1} color="var(--mantine-color-red-filled)" />
                            </ActionIcon>
                          )}
                      </div>
                    )}
                  </Flex>
                </div>
              </Timeline.Item>
            ))}
          </Timeline>
        )
      }

    </Fragment >
  );
};

export default TaskComment;
