/* eslint jsx-a11y/click-events-have-key-events: warn */

/* eslint jsx-a11y/no-static-element-interactions: warn */
import { Icon } from '@chakra-ui/react';
import React, { useEffect, useRef } from 'react';
import ReactDOM from 'react-dom';

import Button, { ButtonSize, ButtonVariant } from '@/components/button/Button';
import { EditIcon, EditUndoIcon, MoreVerticalIcon, TrashIcon } from '@/icons';

interface ProjectDropdownProps {
  projectId: string;
  projectName: string;
  onArchive?: (id: string) => void;
  onUnArchive?: (id: string) => void;
  onEdit?: (id: string) => void;
  isOpen: boolean;
  onOpen: (event: React.MouseEvent) => void;
  onClose: () => void;
  position: { x: number; y: number };
}

const ProjectDropdown: React.FC<ProjectDropdownProps> = ({
  projectId,
  onArchive,
  onUnArchive,
  onEdit,
  isOpen,
  onOpen,
  onClose,
  position,
}) => {
  const menuRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
        onClose();
      }
    };

    const handleScroll = () => {
      if (isOpen) {
        onClose();
      }
    };

    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside);
      // Add scroll event listeners to both window and document
      window.addEventListener('scroll', handleScroll, true);
      document.addEventListener('scroll', handleScroll, true);
    }

    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
      window.removeEventListener('scroll', handleScroll, true);
      document.removeEventListener('scroll', handleScroll, true);
    };
  }, [isOpen, onClose]);

  const menuItemStyle = {
    padding: '8px',
    cursor: 'pointer',
    transition: 'background-color 0.3s ease',
    '&:hover': {
      backgroundColor: 'rgba(255, 255, 255, 0.1)',
    },
  };

  const getAdjustedPosition = () => {
    const screenWidth = window.innerWidth;
    const menuWidth = 200; // This matches the width we set in style

    let adjustedX = position.x;
    // If menu would overflow right edge, align it to the right
    if (position.x + menuWidth > screenWidth) {
      adjustedX = position.x - menuWidth;
    }

    return {
      x: Math.max(8, adjustedX), // Ensure at least 8px from left edge
      y: position.y,
    };
  };

  const renderMenu = () => {
    const adjustedPosition = getAdjustedPosition();

    return (
      <div
        ref={menuRef}
        style={{
          position: 'fixed',
          left: `${adjustedPosition.x}px`,
          top: `${adjustedPosition.y}px`,
          background: '#252020',
          borderRadius: '8px',
          padding: '4px',
          zIndex: 1000,
          fontSize: '14px',
          fontWeight: '500',
          width: '200px',
          border: '1px solid #383737',
          boxShadow: '0 2px 10px rgba(0, 0, 0, 0.1)',
        }}
      >
        {onEdit && false && (
          <div
            style={menuItemStyle}
            onClick={() => onEdit && onEdit(projectId)}
          >
            <Icon as={EditIcon} mr={2} />
            Edit Workspace
          </div>
        )}
        {onArchive && (
          <div style={menuItemStyle} onClick={() => onArchive(projectId)}>
            <Icon as={TrashIcon} mr={2} />
            Move to Trash
          </div>
        )}
        {onUnArchive && (
          <div style={menuItemStyle} onClick={() => onUnArchive(projectId)}>
            <Icon as={EditUndoIcon} mr={2} />
            Restore Workspace
          </div>
        )}
      </div>
    );
  };

  return (
    <>
      <Button
        variant={ButtonVariant.Tertiary}
        size={ButtonSize.Mini}
        icon={MoreVerticalIcon}
        iconClassName='flex justify-center items-center'
        active={isOpen}
        enableHoverState
        onClick={onOpen}
      />
      {isOpen && ReactDOM.createPortal(renderMenu(), document.body)}
    </>
  );
};

export default ProjectDropdown;
