'use client';

import { useState, useRef, useEffect } from 'react';
import { RiArrowDownSLine } from 'react-icons/ri';
import BorderButton from '@/Component/Common/Forms/BorderButton';

export interface NeedHelpOption {
    id: string;
    label: string;
    onClick: () => void;
}

interface NeedHelpDropdownProps {
    options: NeedHelpOption[];
    helpGuideUrl: string;
    helpGuideLabel: string;
    buttonLabel?: string;
    customClass?: string;
}

const NeedHelpDropdown = (props: NeedHelpDropdownProps) => {
    const { options, helpGuideUrl, helpGuideLabel, buttonLabel = 'Need Help?', customClass = '' } = props;
    const [isOpen, setIsOpen] = useState(false);
    const ref = useRef<HTMLDivElement>(null);

    useEffect(() => {
        const handleClickOutside = (event: MouseEvent) => {
            if (ref.current && !ref.current.contains(event.target as Node)) {
                setIsOpen(false);
            }
        };
        document.addEventListener('click', handleClickOutside, true);
        return () => document.removeEventListener('click', handleClickOutside, true);
    }, []);

    const handleHelpGuides = () => {
        setIsOpen(false);
        window.open(helpGuideUrl, '_blank');
    };

    return (
        <div ref={ref} className={`relative text-sm ${customClass}`}>
            <BorderButton
                buttonType="button"
                customClass="!h-auto !py-2 flex items-center gap-1.5"
                onClick={() => setIsOpen((prev) => !prev)}
            >
                {buttonLabel}
                <RiArrowDownSLine className={`w-5 h-5 transition-transform ${isOpen ? 'rotate-180' : ''}`} />
            </BorderButton>
            {isOpen && (
                <div className="absolute right-0 top-full mt-2 min-w-[220px] rounded-2xl border border-neutral-100 bg-white shadow-pop py-1.5 z-50 animate-scale-in">
                    {options.map((opt) => (
                        <button
                            key={opt.id}
                            type="button"
                            className="px-4 py-2.5 text-left text-xs font-medium text-neutral-700 hover:bg-primary/10 hover:text-primary rounded-xl mx-1 w-[calc(100%-0.5rem)] transition-colors"
                            onClick={() => {
                                setIsOpen(false);
                                opt.onClick();
                            }}
                        >
                            {opt.label}
                        </button>
                    ))}
                    <button
                        type="button"
                        className="px-4 py-2.5 text-left text-xs font-medium text-primary hover:bg-primary/10 rounded-xl mx-1 w-[calc(100%-0.5rem)] transition-colors"
                        onClick={handleHelpGuides}
                    >
                        {helpGuideLabel}
                    </button>
                </div>
            )}
        </div>
    );
};

export default NeedHelpDropdown;
