import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { MoreHorizontal } from 'lucide-react';
import type { VehicleRecord } from '../types';
import { useDismissOnFocusOutside } from './useDismissOnFocusOutside';

interface RowActionsMenuProps {
  record: VehicleRecord;
  isAdmin: boolean;
  canEditOpsManager: boolean;
  onEdit: (record: VehicleRecord) => void;
  onEditOpsManager: (record: VehicleRecord) => void;
}

interface PopoverPosition {
  top: number;
  left: number;
}

export function RowActionsMenu({
  record,
  isAdmin,
  canEditOpsManager,
  onEdit,
  onEditOpsManager,
}: RowActionsMenuProps) {
  const [open, setOpen] = useState(false);
  const [position, setPosition] = useState<PopoverPosition>({ top: 0, left: 0 });
  const anchorRef = useRef<HTMLDivElement>(null);
  const popoverRef = useRef<HTMLDivElement>(null);

  const dismiss = useCallback(() => setOpen(false), []);

  useDismissOnFocusOutside(open, [anchorRef, popoverRef], dismiss);

  const updatePosition = useCallback(() => {
    const anchor = anchorRef.current;
    if (!anchor) return;
    const rect = anchor.getBoundingClientRect();
    setPosition({
      top: rect.bottom + 4,
      left: rect.right,
    });
  }, []);

  useEffect(() => {
    if (!open) return;
    updatePosition();
    window.addEventListener('resize', updatePosition);
    window.addEventListener('scroll', updatePosition, true);
    return () => {
      window.removeEventListener('resize', updatePosition);
      window.removeEventListener('scroll', updatePosition, true);
    };
  }, [open, updatePosition]);

  const items = useMemo(() => {
    const menu: Array<{ key: string; label: string; onClick: () => void }> = [];
    if (isAdmin) {
      menu.push({
        key: 'edit',
        label: '编辑',
        onClick: () => onEdit(record),
      });
    }
    if (canEditOpsManager) {
      menu.push({
        key: 'opsManager',
        label: '修改运维负责人',
        onClick: () => onEditOpsManager(record),
      });
    }
    return menu;
  }, [canEditOpsManager, isAdmin, onEdit, onEditOpsManager, record]);

  if (items.length === 0) return null;

  const runAction = (action: () => void) => {
    setOpen(false);
    action();
  };

  const toggleOpen = () => {
    setOpen((prev) => {
      const next = !prev;
      if (next) {
        window.requestAnimationFrame(updatePosition);
      }
      return next;
    });
  };

  const popover =
    open && typeof document !== 'undefined'
      ? createPortal(
          <div
            ref={popoverRef}
            className="vm-action-menu-popover vm-action-menu-popover--portal"
            role="menu"
            aria-label="更多操作"
            style={{ top: position.top, left: position.left }}
          >
            {items.map((item) => (
              <button
                key={item.key}
                type="button"
                role="menuitem"
                className="vm-action-menu-item"
                onMouseDown={(event) => event.preventDefault()}
                onClick={() => runAction(item.onClick)}
              >
                {item.label}
              </button>
            ))}
          </div>,
          document.body,
        )
      : null;

  return (
    <div className="vm-action-menu" ref={anchorRef}>
      <button
        type="button"
        className="vm-icon-btn"
        aria-label="更多操作"
        aria-haspopup="menu"
        aria-expanded={open}
        onClick={toggleOpen}
      >
        <MoreHorizontal size={16} aria-hidden />
      </button>
      {popover}
    </div>
  );
}
