import { ChevronDown } from 'lucide-react';
import React, { useState, useEffect, useRef } from 'react'

const BacklinkTypeDropdown = ({ options, title, subTitle }: { options: Record<string, boolean>, title: string, subTitle?: string }) => {

    const [dropdownOpen, setDropdownOpen] = useState(false);
    const [checkedRings, setCheckedRings] = useState<Record<string, boolean>>(options);
    const dropdownRef = useRef<HTMLDivElement>(null);

    const toggleRing = (ring: string) => setCheckedRings(r => ({ ...r, [ring]: !r[ring] }));

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

        if (dropdownOpen) {
            document.addEventListener('mousedown', handleClickOutside);
        }

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

    return (
        <div className='relative' ref={dropdownRef}>
            <button
                className={`border rounded-lg px-3 py-1 bg-white  font-normal flex items-center text-md ${dropdownOpen ? "border-2 border-solid border-blue-500" : ""}`}
                onClick={() => setDropdownOpen(v => !v)}
            >
                {title} 
                <ChevronDown className='ml-2 text-[#65677D]' />

            </button>
            {dropdownOpen && (
                <div className={`absolute z-10 bg-white shadow-lg border rounded-lg top-[110%] right-0 px-4 py-3 min-w-[150px] `}>
                    <div className='font-semibold text-md text-gray-700 mb-2'>{subTitle}:</div>
                    {Object.keys(checkedRings).map((ring, idx) => (
                        <label
                            key={idx}
                            className='flex items-center gap-2 py-1 text-[16px] cursor-pointer select-none'
                            style={{ fontWeight: 500 }}
                        >
                            <input
                                type='checkbox'
                                checked={checkedRings[ring]}
                                className='form-checkbox accent-blue-600 w-4 h-4 rounded-full'
                                onChange={() => toggleRing(ring)}
                            />
                            {ring}
                        </label>
                    ))}
                </div>
            )}
        </div>
    );

}

export default BacklinkTypeDropdown;