'use client';

import { useState, useRef, useEffect } from 'react';
import { MoreHorizontal, Pencil, Power } from 'lucide-react';

type ClubForActions = {
  id: string;
  name: string;
  status: string;
};

type ClubActionsMenuProps = {
  club: ClubForActions;
  onEdit: () => void;
  onToggleActive: () => void;
};

export function ClubActionsMenu({ club, onEdit, onToggleActive }: ClubActionsMenuProps) {
  const [open, setOpen] = useState(false);
  const menuRef = useRef<HTMLDivElement>(null);
  const buttonRef = useRef<HTMLButtonElement>(null);

  useEffect(() => {
    if (!open) return;

    const handleClickOutside = (e: MouseEvent) => {
      if (
        menuRef.current &&
        !menuRef.current.contains(e.target as Node) &&
        buttonRef.current &&
        !buttonRef.current.contains(e.target as Node)
      ) {
        setOpen(false);
      }
    };

    const handleEscape = (e: KeyboardEvent) => {
      if (e.key === 'Escape') setOpen(false);
    };

    document.addEventListener('mousedown', handleClickOutside);
    document.addEventListener('keydown', handleEscape);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
      document.removeEventListener('keydown', handleEscape);
    };
  }, [open]);

  const isBlocked = club.status === 'blocked';

  return (
    <div className="relative">
      <button
        ref={buttonRef}
        onClick={() => setOpen((prev) => !prev)}
        className="p-1.5 rounded-lg hover:bg-background transition-colors"
      >
        <MoreHorizontal className="h-4 w-4 text-muted" />
      </button>

      {open && (
        <div
          ref={menuRef}
          className="absolute right-0 top-full mt-1 z-20 w-48 bg-card rounded-xl shadow-lg border border-border py-1 animate-in fade-in zoom-in-95"
        >
          <button
            onClick={() => {
              setOpen(false);
              onEdit();
            }}
            className="flex items-center gap-2.5 w-full px-3 py-2 text-sm text-text hover:bg-background transition-colors"
          >
            <Pencil className="h-3.5 w-3.5 text-muted" />
            Редактировать
          </button>
          <button
            onClick={() => {
              setOpen(false);
              onToggleActive();
            }}
            className="flex items-center gap-2.5 w-full px-3 py-2 text-sm text-text hover:bg-background transition-colors"
          >
            <Power className="h-3.5 w-3.5 text-muted" />
            {isBlocked ? 'Активировать' : 'Деактивировать'}
          </button>
        </div>
      )}
    </div>
  );
}
