import clsx from "clsx";
import { useMemo, useState } from "preact/hooks";

import { useInputState } from "@common/hooks/useInputState";

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

interface Props {
    onClose: () => void;
}

type Tab = "banned-tokens" | "system-instruction";

export const SettingsModal = ({ onClose }: Props) => {
    const { bannedTokens, systemInstruction, dispatch } = useAppState();
    const [inputValue, setInputValue] = useInputState();
    const [activeTab, setActiveTab] = useState<Tab>("banned-tokens");

    // Save system instruction on every change
    const setInstructionValue = useInputCallback((instructionValue) => {
        dispatch({
            type: "SET_SYSTEM_INSTRUCTION",
            systemInstruction: instructionValue,
        });
    }, []);

    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();
        } else if (e.key === "Escape") {
            onClose();
        }
    };

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

    return (
        <div class={styles.overlay} onClick={onClose}>
            <div class={styles.modal} onClick={(e) => e.stopPropagation()}>
                <div class={styles.header}>
                    <h2 class={styles.title}>Settings</h2>
                    <button class={styles.closeButton} onClick={onClose}>
                        <X size={20} />
                    </button>
                </div>
                <div class={styles.tabs}>
                    <button
                        class={clsx(styles.tab, activeTab === "banned-tokens" && styles.active)}
                        onClick={() => setActiveTab("banned-tokens")}
                    >
                        Banned Tokens
                    </button>
                    <button
                        class={clsx(styles.tab, activeTab === "system-instruction" && styles.active)}
                        onClick={() => setActiveTab("system-instruction")}
                    >
                        System Instruction
                    </button>
                </div>
                <div class={styles.content}>
                    {activeTab === "banned-tokens" ? (
                        <>
                            <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>
                        </>
                    ) : (
                        <div class={styles.form}>
                            <div class={styles.formGroup}>
                                <label class={styles.label}>
                                    System Instruction
                                </label>
                                <textarea
                                    value={systemInstruction}
                                    onInput={setInstructionValue}
                                    placeholder="Enter system instruction for the AI assistant..."
                                    class={clsx(styles.input, styles.textarea)}
                                    rows={10}
                                />
                            </div>
                        </div>
                    )}
                </div>
                <div class={styles.footer}>
                    <button onClick={onClose} class={clsx(styles.button, styles.buttonSecondary)}>
                        Done
                    </button>
                </div>
            </div>
        </div>
    );
};
