import React, { useState, useRef, useEffect, useMemo } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { IconDefinition } from "@fortawesome/free-solid-svg-icons";
import Icon from "@mdi/react";
import { allIcons, faIcons, mdiIcons } from "./iconRegistry";

interface IconPickerProps {
    selectedIcon: string;
    onSelect: (iconName: string) => void;
    darkMode: boolean;
}

export default function IconPicker({ selectedIcon, onSelect, darkMode }: IconPickerProps) {
    const [search, setSearch] = useState("");
    const [activeTab, setActiveTab] = useState<"all" | "fa" | "mdi">("all");
    const searchRef = useRef<HTMLInputElement>(null);

    useEffect(() => {
        searchRef.current?.focus();
    }, []);

    const filtered = useMemo(() => {
        const source = activeTab === "all" ? allIcons : activeTab === "fa" ? faIcons : mdiIcons;
        if (!search.trim()) return source;
        const terms = search.toLowerCase().split(/\s+/);
        return source.filter(entry =>
            terms.every(term =>
                entry.name.toLowerCase().includes(term) ||
                entry.keywords.some(kw => kw.includes(term))
            )
        );
    }, [search, activeTab]);

    const bg = darkMode ? "#2a2a3a" : "#fff";
    const border = darkMode ? "#555" : "#e5e7eb";
    const textColor = darkMode ? "#d1d5db" : "#555";
    const activeBg = darkMode ? "#374151" : "#e0e7ff";
    const hoverBg = darkMode ? "#333" : "#f3f4f6";
    const tabActiveBg = darkMode ? "#374151" : "#e0e7ff";
    const tabColor = darkMode ? "#9ca3af" : "#888";

    return (
        <div style={{
            background: bg,
            border: `1px solid ${border}`,
            borderRadius: "12px",
            padding: "8px",
            boxShadow: "0 8px 24px rgba(0,0,0,0.2)",
            width: "300px",
        }}>
            {/* Search */}
            <input
                ref={searchRef}
                type="text"
                value={search}
                onChange={e => setSearch(e.target.value)}
                placeholder="Search icons..."
                style={{
                    width: "100%",
                    padding: "6px 10px",
                    border: `1px solid ${border}`,
                    borderRadius: "8px",
                    background: darkMode ? "#1e1e2e" : "#f9fafb",
                    color: darkMode ? "#e5e7eb" : "#333",
                    fontSize: "0.8rem",
                    outline: "none",
                    boxSizing: "border-box",
                    marginBottom: "6px",
                }}
            />
            {/* Tabs */}
            <div style={{ display: "flex", gap: "2px", marginBottom: "6px" }}>
                {(["all", "fa", "mdi"] as const).map(tab => (
                    <button
                        key={tab}
                        onClick={() => setActiveTab(tab)}
                        style={{
                            flex: 1,
                            padding: "3px 6px",
                            fontSize: "0.7rem",
                            fontWeight: activeTab === tab ? 600 : 400,
                            border: "none",
                            borderRadius: "6px",
                            cursor: "pointer",
                            background: activeTab === tab ? tabActiveBg : "transparent",
                            color: activeTab === tab ? (darkMode ? "#e5e7eb" : "#333") : tabColor,
                        }}
                    >
                        {tab === "all" ? `All (${allIcons.length})` : tab === "fa" ? "FontAwesome" : "Material"}
                    </button>
                ))}
            </div>
            {/* Grid */}
            <div style={{
                display: "grid",
                gridTemplateColumns: "repeat(8, 1fr)",
                gap: "2px",
                maxHeight: "240px",
                overflowY: "auto",
            }}>
                {filtered.map(entry => (
                    <button
                        key={entry.name}
                        onClick={() => onSelect(entry.name)}
                        title={entry.name}
                        style={{
                            width: "32px",
                            height: "32px",
                            border: "none",
                            background: selectedIcon === entry.name ? activeBg : "transparent",
                            borderRadius: "6px",
                            cursor: "pointer",
                            display: "flex",
                            alignItems: "center",
                            justifyContent: "center",
                            color: textColor,
                        }}
                        onMouseEnter={e => {
                            if (selectedIcon !== entry.name) (e.currentTarget as HTMLButtonElement).style.background = hoverBg;
                        }}
                        onMouseLeave={e => {
                            if (selectedIcon !== entry.name) (e.currentTarget as HTMLButtonElement).style.background = "transparent";
                        }}
                    >
                        {entry.type === "fa" ? (
                            <FontAwesomeIcon icon={entry.icon as IconDefinition} style={{ fontSize: "14px" }} />
                        ) : (
                            <Icon path={entry.icon as string} size={0.6} />
                        )}
                    </button>
                ))}
                {filtered.length === 0 && (
                    <div style={{ gridColumn: "1 / -1", textAlign: "center", padding: "16px", color: tabColor, fontSize: "0.8rem" }}>
                        No icons found
                    </div>
                )}
            </div>
        </div>
    );
}

// Re-export for backwards compatibility
export { allIcons, type IconEntry } from "./iconRegistry";
