import React, { useState, useRef, useEffect } from 'react'
import { createPortal } from 'react-dom'
import { More } from 'iconsax-react'

export interface RowActionItem {
    label: string;
    icon?: React.ReactNode;
    onClick: () => void;
    className?: string;
}

interface RowActionsDropdownProps {
    actions: RowActionItem[];
    className?: string;
    trigger?: React.ReactNode;
    topOffset?: number;
    leftOffset?: number;
    topOffsetMobile?: number;
    leftOffsetMobile?: number;
}

const RowActionsDropdown: React.FC<RowActionsDropdownProps> = ({
    actions,
    className = '',
    trigger,
    topOffset = 0,
    leftOffset = 0,
    topOffsetMobile = 0,
    leftOffsetMobile = 0
}) => {
    const [isOpen, setIsOpen] = useState(false)
    const [dropdownPosition, setDropdownPosition] = useState({ top: 0, left: 0 })
    const dropdownRef = useRef<HTMLDivElement>(null)
    const buttonRef = useRef<HTMLButtonElement>(null)

    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
                setIsOpen(false)
            }
        }

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

    const calculatePosition = (rect: DOMRect) => {
        const isMobile = window.innerWidth < 768
        const dropdownWidth = isMobile ? 140 : 150
        const dropdownHeight = actions.length * (isMobile ? 36 : 40)

        // انتخاب offset بر اساس سایز صفحه
        const currentTopOffset = isMobile ? topOffsetMobile : topOffset
        const currentLeftOffset = isMobile ? leftOffsetMobile : leftOffset

        let left = rect.left + window.scrollX - dropdownWidth + rect.width + currentLeftOffset
        let top = rect.bottom + window.scrollY + currentTopOffset

        if (left + dropdownWidth > window.innerWidth) {
            left = rect.left + window.scrollX - dropdownWidth + currentLeftOffset
        }

        if (left < 0) {
            left = isMobile ? 20 : 40
        }

        if (top + dropdownHeight > window.innerHeight + window.scrollY) {
            top = rect.top + window.scrollY - dropdownHeight + currentTopOffset
        }

        // اطمینان از اینکه dropdown از صفحه خارج نشود
        if (left < 0) left = 20
        if (left + dropdownWidth > window.innerWidth) left = window.innerWidth - dropdownWidth - 20
        if (top < 0) top = 20
        if (top + dropdownHeight > window.innerHeight) top = window.innerHeight - dropdownHeight - 20

        return { top, left }
    }

    const handleToggle = (e: React.MouseEvent) => {
        e.stopPropagation()

        if (!isOpen && buttonRef.current) {
            const rect = buttonRef.current.getBoundingClientRect()
            const calculatedPosition = calculatePosition(rect)
            setDropdownPosition(calculatedPosition)
        }

        setIsOpen(!isOpen)
    }

    const handleActionClick = (action: RowActionItem) => {
        action.onClick()
        setIsOpen(false)
    }

    const renderDropdown = () => {
        if (!isOpen) return null

        return createPortal(
            <div
                ref={dropdownRef}
                className="fixed py-3 md:py-3 bg-white dark:bg-[#252526] rounded-xl md:rounded-2xl shadow-lg z-[5] min-w-[140px] md:min-w-[150px] border border-[#d0d0d0]"
                style={{
                    top: `${dropdownPosition.top}px`,
                    left: `${dropdownPosition.left}px`,
                }}
            >
                {actions.map((action, index) => (
                    <button
                        key={index}
                        onClick={() => handleActionClick(action)}
                        className={`w-full mt-1 text-right px-2 md:px-3 py-1 md:py-1.5 text-xs md:text-[13px] flex items-center gap-2 hover:bg-gray-50 dark:hover:bg-[#2d2d30] ${index === 0 ? 'rounded-t-lg' : ''}  ${action.className || ''}`}
                    >
                        {action.icon && <span className="ml-2">{action.icon}</span>}
                        <span className={`${action.label === 'حذف' ? 'text-red-500' : ''} dark:text-gray-200`}>{action.label}</span>
                    </button>
                ))}
            </div>,
            document.body
        )
    }

    return (
        <div className={className}>
            <button
                ref={buttonRef}
                onClick={handleToggle}
                className="mt-2 hover:bg-gray-100 dark:hover:bg-[#2d2d30] rounded-full transition-colors"
                aria-haspopup="menu"
                aria-expanded={isOpen}
            >
                {trigger ? trigger : (
                    <More size={16} color={'black'} className="rotate-90" />
                )}
            </button>

            {renderDropdown()}
        </div>
    )
}

export default RowActionsDropdown 