import { useEffect } from "preact/hooks";
import { useHordeState } from "../../contexts/state";
import { useInputState } from "@common/hooks/useInputState";
import { Modal } from "@common/components/Modal";
import styles from "../../assets/options-modal.module.css";

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

export const OptionsModal = ({ open, onClose }: Props) => {
    const { state, dispatch } = useHordeState();
    const [draft, setDraft] = useInputState(state.apiKey);

    useEffect(() => {
        if (open) setDraft(state.apiKey);
    }, [open]);

    const save = () => {
        dispatch({ type: 'SET_API_KEY', apiKey: draft.trim() });
        onClose();
    };

    const clear = () => {
        dispatch({ type: 'SET_API_KEY', apiKey: '' });
        setDraft('');
        onClose();
    };

    return (
        <Modal
            open={open}
            onClose={onClose}
            title="Options"
            class={styles.modal}
            footer={<>
                <button class={styles.saveBtn} onClick={save}>Save</button>
                {state.apiKey && <button class={styles.clearBtn} onClick={clear}>Clear</button>}
            </>}
        >
            <label class={styles.label}>
                <span>API Key</span>
                <input
                    type="password"
                    value={draft}
                    onInput={setDraft}
                    onKeyDown={e => { if (e.key === 'Enter') save(); }}
                    placeholder="Enter your AI Horde API key"
                    autoFocus
                />
            </label>
        </Modal>
    );
};
