import { useState, useRef, useEffect, useCallback } from 'react';
import { createPortal } from 'react-dom';
import { Icon } from '../../Atoms/Icon/Icon';
import { Typography } from '../../Atoms/Typography/Typography';
import { FONT_FAMILY_SANS } from '../../../designTokens';

export const MenuAcciones = ({
  actions = [],
  ariaLabel = 'Acciones',
  menuWidth = 140,
  menuHeight,
  triggerIconColor = '#0F172A',
}) => {
  const [isOpen, setIsOpen] = useState(false);
  const menuRef = useRef(null);
  const buttonRef = useRef(null);
  const [menuPosition, setMenuPosition] = useState(null);
  const rafRef = useRef(null);

  const updateMenuPosition = useCallback(() => {
    if (!buttonRef.current) return;
    const rect = buttonRef.current.getBoundingClientRect();
    setMenuPosition({
      top: rect.bottom + 4,
      left: rect.right - menuWidth,
    });
  }, [menuWidth]);

  useEffect(() => {
    if (!isOpen) return undefined;
    const handleClickOutside = (event) => {
      if (menuRef.current && !menuRef.current.contains(event.target)) {
        setIsOpen(false);
      }
    };
    document.addEventListener('mousedown', handleClickOutside);
    return () => document.removeEventListener('mousedown', handleClickOutside);
  }, [isOpen]);

  useEffect(() => {
    if (!isOpen) return undefined;

    const handleViewportChange = () => {
      if (rafRef.current) cancelAnimationFrame(rafRef.current);
      rafRef.current = requestAnimationFrame(() => {
        updateMenuPosition();
      });
    };

    updateMenuPosition();
    window.addEventListener('resize', handleViewportChange);
    window.addEventListener('scroll', handleViewportChange, true);

    return () => {
      window.removeEventListener('resize', handleViewportChange);
      window.removeEventListener('scroll', handleViewportChange, true);
      if (rafRef.current) cancelAnimationFrame(rafRef.current);
      rafRef.current = null;
    };
  }, [isOpen, updateMenuPosition]);

  const visibleActions = actions.filter((action) => !!action?.label && typeof action?.onClick === 'function');
  const resolvedMenuHeight =
    menuHeight ?? Math.min(320, Math.max(56, 16 + visibleActions.length * 40));

  return (
    <div
      style={{
        position: 'relative',
        display: 'inline-flex',
        alignItems: 'center',
        justifyContent: 'center',
        overflow: 'visible',
      }}
    >
      <button
        type="button"
        aria-label={ariaLabel}
        ref={buttonRef}
        onClick={(event) => {
          event?.stopPropagation?.();
          setIsOpen((prev) => {
            const next = !prev;
            if (next && buttonRef.current) {
              updateMenuPosition();
            }
            return next;
          });
        }}
        style={{
          border: 'none',
          background: 'transparent',
          padding: 0,
          display: 'inline-flex',
          alignItems: 'center',
          justifyContent: 'center',
          cursor: 'pointer',
        }}
      >
        <Icon
          name="EllipsisVerticalIcon"
          variant="24-outline"
          size={24}
          style={{
            width: 24,
            height: 24,
            opacity: 1,
            color: triggerIconColor,
            strokeWidth: 1.5,
          }}
        />
      </button>

      {isOpen && visibleActions.length > 0 && menuPosition && typeof document !== 'undefined'
        && createPortal(
          <div
            ref={menuRef}
            style={{
              position: 'fixed',
              top: menuPosition.top,
              left: menuPosition.left,
              width: menuWidth,
              minHeight: resolvedMenuHeight,
              height: 'auto',
              borderRadius: 12,
              border: '1px solid var(--color-main-700, #38656D)',
              padding: 8,
              background: 'var(--color-neutrals-white, #FFFFFF)',
              display: 'flex',
              flexDirection: 'column',
              zIndex: 1300,
            }}
          >
            {visibleActions.map((action) => (
              <button
                key={action.key ?? action.label}
                type="button"
                onClick={(event) => {
                  event?.stopPropagation?.();
                  action.onClick?.(event);
                  setIsOpen(false);
                }}
                style={{
                  width: '100%',
                  minHeight: 40,
                  gap: 8,
                  borderRadius: 8,
                  padding: '8px 10px',
                  border: 'none',
                  background: 'transparent',
                  boxSizing: 'border-box',
                  display: 'flex',
                  alignItems: 'center',
                  cursor: 'pointer',
                  textAlign: 'left',
                }}
              >
                <Icon
                  name={action.icon}
                  variant="24-outline"
                  size={24}
                  style={{
                    width: 24,
                    height: 24,
                    minWidth: 24,
                    minHeight: 24,
                    flexShrink: 0,
                    color: action.danger ? '#B30808' : 'var(--color-main-800, #29474C)',
                  }}
                />
                <Typography
                  component="span"
                  style={{
                    fontFamily: FONT_FAMILY_SANS,
                    fontWeight: 400,
                    fontStyle: 'normal',
                    fontSize: '14px',
                    lineHeight: '21px',
                    letterSpacing: '0px',
                    color: action.danger ? '#B30808' : 'var(--color-main-800, #29474C)',
                    margin: 0,
                    whiteSpace: 'nowrap',
                  }}
                >
                  {action.label}
                </Typography>
              </button>
            ))}
          </div>,
          document.body
        )}
    </div>
  );
};

export default MenuAcciones;
