import { useInputState } from "@common/hooks/useInputState";
import clsx from "clsx";
import { X } from "lucide-preact";
import styles from "../../assets/settings-modal.module.css";
import { useAppState } from "../../contexts/state";

export const BannedTokensSettings = () => {
    const { bannedTokens, dispatch } = useAppState();
    const [inputValue, setInputValue] = useInputState();

    const sortedTokens = [...bannedTokens].sort((a, b) =>
        a.trim().toLowerCase().localeCompare(b.trim().toLowerCase())
    );

    const handleAdd = () => {
        const trimmed = inputValue.trim();
        if (trimmed && !bannedTokens.includes(trimmed)) {
            dispatch({ type: "SET_BANNED_TOKENS", tokens: [...bannedTokens, trimmed] });
            setInputValue("");
        }
    };

    const handleRemove = (token: string) => {
        dispatch({ type: "SET_BANNED_TOKENS", tokens: bannedTokens.filter((t) => t !== token) });
    };

    const handleKeyDown = (e: KeyboardEvent) => {
        if (e.key === "Enter") handleAdd();
    };

    return (
        <>
            <div class={styles.inputRow}>
                <input
                    type="text"
                    value={inputValue}
                    onInput={setInputValue}
                    onKeyDown={handleKeyDown}
                    placeholder="Token to ban"
                    class={styles.input}
                    autoFocus
                />
                <button onClick={handleAdd} class={clsx(styles.button, styles.buttonPrimary)}>
                    Add
                </button>
            </div>
            <div class={styles.divider} />
            <div class={styles.tokenList}>
                {sortedTokens.length === 0 ? (
                    <p class={styles.emptyText}>No banned tokens</p>
                ) : (
                    sortedTokens.map((token) => (
                        <div key={token} class={styles.tokenItem}>
                            <span>{token}</span>
                            <button onClick={() => handleRemove(token)} class={styles.tokenRemoveButton}>
                                <X size={12} />
                            </button>
                        </div>
                    ))
                )}
            </div>
        </>
    );
};
