import { useState, useRef, useEffect } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faColumns3 } from '@fortawesome/pro-duotone-svg-icons';
import { Button } from '@/components/base/buttons/button';
import type { FC } from 'react';

const ColumnsIcon: FC<{ className?: string }> = ({ className }) => (
    <FontAwesomeIcon icon={faColumns3} className={className} />
);

export type ColumnDef = {
    id: string;
    label: string;
    defaultVisible?: boolean;
};

interface ColumnToggleProps {
    columns: ColumnDef[];
    visibleColumns: Set<string>;
    onToggle: (columnId: string) => void;
}

export const ColumnToggle = ({ columns, visibleColumns, onToggle }: ColumnToggleProps) => {
    const [open, setOpen] = useState(false);
    const panelRef = useRef<HTMLDivElement>(null);

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

    return (
        <div className="relative" ref={panelRef}>
            <Button
                size="sm"
                color="secondary"
                iconLeading={ColumnsIcon}
                onClick={() => setOpen(!open)}
            >
                Columns
            </Button>

            {open && (
                <div className="absolute top-full right-0 mt-2 w-56 rounded-xl bg-primary shadow-xl ring-1 ring-secondary z-50 overflow-hidden">
                    <div className="px-3 py-2 border-b border-secondary">
                        <span className="text-xs font-semibold text-tertiary">Show/Hide Columns</span>
                    </div>
                    <div className="max-h-64 overflow-y-auto py-1">
                        {columns.map(col => (
                            <button
                                key={col.id}
                                type="button"
                                onClick={(e) => { e.stopPropagation(); onToggle(col.id); }}
                                className="flex w-full items-center gap-2 px-3 py-1.5 text-xs text-primary hover:bg-primary_hover cursor-pointer text-left"
                            >
                                <span className={`flex size-4 shrink-0 items-center justify-center rounded border ${visibleColumns.has(col.id) ? 'bg-brand-solid border-brand text-white' : 'border-primary bg-primary'}`}>
                                    {visibleColumns.has(col.id) && <span className="text-[10px]">✓</span>}
                                </span>
                                {col.label}
                            </button>
                        ))}
                    </div>
                </div>
            )}
        </div>
    );
};

export const useColumnVisibility = (columns: ColumnDef[]) => {
    const [visibleColumns, setVisibleColumns] = useState<Set<string>>(() => {
        return new Set(columns.filter(c => c.defaultVisible !== false).map(c => c.id));
    });

    const toggle = (columnId: string) => {
        setVisibleColumns(prev => {
            const next = new Set(prev);
            if (next.has(columnId)) {
                next.delete(columnId);
            } else {
                next.add(columnId);
            }
            return next;
        });
    };

    return { visibleColumns, toggle };
};
