import { useEffect, useRef, useState } from 'react';

import { Icon } from '../Icon';
import { GameSort } from '../../lib/types';

const OPTIONS: ReadonlyArray<{ key: GameSort; label: string }> = [
    { key: 'az', label: 'Name (A–Z)' },
    { key: 'sizeDesc', label: 'Size (largest)' },
    { key: 'sizeAsc', label: 'Size (smallest)' },
    { key: 'status', label: 'Status' },
];

interface Props {
    value: GameSort;
    onChange: (value: GameSort) => void;
}

export const SortMenu = ({ value, onChange }: Props) => {
    const [open, setOpen] = useState(false);
    const ref = useRef<HTMLDivElement | null>(null);

    useEffect(() => {
        if (!open) return;
        const onClick = (e: MouseEvent) => {
            if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
        };
        document.addEventListener('mousedown', onClick);
        return () => document.removeEventListener('mousedown', onClick);
    }, [open]);

    const current = OPTIONS.find(o => o.key === value) ?? OPTIONS[0];

    return (
        <div className="sort" ref={ref}>
            <button className="sort-btn" type="button" onClick={() => setOpen(o => !o)}>
                <Icon.sort />
                <span>Sort: <strong>{current.label}</strong></span>
                <Icon.chevron />
            </button>
            {open && (
                <div className="sort-menu">
                    {OPTIONS.map(o => (
                        <button
                            key={o.key}
                            type="button"
                            onClick={() => {
                                onChange(o.key);
                                setOpen(false);
                            }}
                        >
                            <span className="sort-check">
                                {o.key === value && <Icon.check />}
                            </span>
                            {o.label}
                        </button>
                    ))}
                </div>
            )}
        </div>
    );
};
