import { useState, useRef, useEffect, useMemo } from 'react';
import { Search, Check, ChevronDown, User } from 'lucide-react';
import clsx from 'clsx';

export interface UserInfo {
    id: string;
    name: string;
    process?: string;
    level?: number;
    useJobReport?: boolean;
    outdate?: string | null;
}

interface UserSelectorProps {
    users: UserInfo[];
    selectedIds: string[]; // Always array for internal consistency, or handle single/multi logic
    onChange: (ids: string[]) => void;
    multiSelect?: boolean;
    placeholder?: string;
    className?: string;
    // Filter Options
    minLevel?: number;
    onlyJobReportUsers?: boolean;
    includeResigned?: boolean;
}

export function UserSelector({
    users,
    selectedIds,
    onChange,
    multiSelect = false,
    placeholder = '담당자 선택',
    className
}: UserSelectorProps) {
    const [isOpen, setIsOpen] = useState(false);
    const [searchQuery, setSearchQuery] = useState('');
    const containerRef = useRef<HTMLDivElement>(null);

    // Filter and Sort users
    const filteredAndSortedUsers = useMemo(() => {
        let result = users;

        // Filter
        if (searchQuery.trim()) {
            const query = searchQuery.toLowerCase();
            result = result.filter(user =>
                user.name.toLowerCase().includes(query) ||
                user.id.toLowerCase().includes(query)
            );
        }

        // Sort: Process -> Name
        return result.sort((a, b) => {
            // Compare Process
            const processA = a.process || '';
            const processB = b.process || '';
            if (processA !== processB) {
                if (processA < processB) return -1;
                if (processA > processB) return 1;
            }

            // Compare Name
            return a.name.localeCompare(b.name);
        });
    }, [users, searchQuery]);

    // Handle outside click
    useEffect(() => {
        function handleClickOutside(event: MouseEvent) {
            if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
                setIsOpen(false);
            }
        }
        document.addEventListener('mousedown', handleClickOutside);
        return () => document.removeEventListener('mousedown', handleClickOutside);
    }, []);

    const handleSelect = (userId: string) => {
        if (multiSelect) {
            if (selectedIds.includes(userId)) {
                onChange(selectedIds.filter(id => id !== userId));
            } else {
                onChange([...selectedIds, userId]);
            }
        } else {
            // Single select: toggle or set
            if (selectedIds.includes(userId)) {
                onChange([]); // Deselect if clicked again? Or just prevent? Usually deselect is allowed.
            } else {
                onChange([userId]);
                setIsOpen(false); // Close on selection for single mode
            }
        }
    };

    const selectedUserList = useMemo(() => users.filter(u => selectedIds.includes(u.id)), [users, selectedIds]);

    const getDisplayText = () => {
        if (selectedIds.length === 0) return placeholder;

        if (selectedUserList.length === 0) {
            return selectedIds[0];
        }

        if (selectedUserList.length === 1) {
            return `${selectedUserList[0].name}(${selectedUserList[0].id})`;
        }
        return `${selectedUserList[0].name} 외 ${selectedUserList.length - 1}명`;
    };

    return (
        <div className={clsx("relative z-30", className)} ref={containerRef}>
            {/* Trigger Button */}
            <button
                type="button"
                onClick={() => setIsOpen(!isOpen)}
                className={clsx(
                    "flex items-center justify-between w-full h-[60px] px-3 bg-white/5 border border-white/10 rounded-lg text-white transition-colors focus:outline-none focus:ring-2 focus:ring-primary-400 hover:bg-white/10",
                    isOpen && "ring-2 ring-primary-400"
                )}
            >
                <div className="flex items-center gap-3 overflow-hidden text-left">
                    <User className="w-5 h-5 text-white/50 flex-shrink-0" />
                    <div className="flex flex-col justify-center gap-0.5">
                        {selectedUserList.length === 1 ? (
                            <>
                                <div className="text-sm font-medium leading-none flex items-center">
                                    {selectedUserList[0].name}
                                    <span className="text-white/40 text-xs ml-1 font-normal">({selectedUserList[0].id})</span>
                                </div>
                                {selectedUserList[0].process ? (
                                    <div className="text-xs text-white/60 leading-none">
                                        {selectedUserList[0].process}
                                    </div>
                                ) : (
                                    <div className="text-xs text-white/30 leading-none">
                                        -
                                    </div>
                                )}
                            </>
                        ) : (
                            <span className="truncate text-sm">
                                {getDisplayText()}
                            </span>
                        )}
                    </div>
                </div>
                <ChevronDown className="w-4 h-4 text-white/50 ml-2 flex-shrink-0" />
            </button>

            {/* Popover */}
            {isOpen && (
                <div className="absolute top-full mt-2 w-[360px] bg-[#1e293b] border border-white/10 rounded-xl shadow-2xl overflow-hidden animate-fade-in-up z-50">
                    <div className="p-2 space-y-2">
                        {/* Search Input */}
                        <div className="relative">
                            <Search className="absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-white/50" />
                            <input
                                type="text"
                                placeholder="사용자 검색"
                                value={searchQuery}
                                onChange={(e) => setSearchQuery(e.target.value)}
                                className="w-full h-8 bg-black/20 border border-white/10 rounded pl-8 pr-2 text-xs text-white focus:outline-none focus:border-primary-500 placeholder-white/30"
                                autoFocus
                            />
                        </div>

                        {/* User List */}
                        <div className="max-h-60 overflow-y-auto space-y-1 scrollbar-thin scrollbar-thumb-white/10 scrollbar-track-transparent pr-1">
                            {filteredAndSortedUsers.length === 0 ? (
                                <div className="text-center text-white/40 text-xs py-4">
                                    검색 결과가 없습니다.
                                </div>
                            ) : (
                                filteredAndSortedUsers.map(user => {
                                    const isSelected = selectedIds.includes(user.id);
                                    return (
                                        <button
                                            key={user.id}
                                            onClick={() => handleSelect(user.id)}
                                            className={clsx(
                                                "w-full flex items-center gap-2 px-2 py-1.5 rounded text-left transition-colors text-sm",
                                                isSelected ? "bg-primary-500/20 text-primary-200" : "text-white/80 hover:bg-white/10"
                                            )}
                                        >
                                            <div className={clsx(
                                                "w-4 h-4 rounded border flex items-center justify-center transition-colors flex-shrink-0",
                                                isSelected ? "bg-primary-500 border-primary-500" : "border-white/30"
                                            )}>
                                                {isSelected && <Check className="w-3 h-3 text-white" />}
                                            </div>
                                            <div className="flex flex-col min-w-0">
                                                <div className="flex items-center gap-1.5">
                                                    {user.process && (
                                                        <span className="text-[10px] text-primary-300 bg-primary-500/10 px-1 rounded flex-shrink-0">
                                                            {user.process}
                                                        </span>
                                                    )}
                                                    <span className="text-xs font-medium truncate">{user.name}</span>
                                                </div>
                                                <span className="text-[10px] text-white/50">{user.id}</span>
                                            </div>
                                        </button>
                                    );
                                })
                            )}
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
