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

import { login } from "@common/storage";
import { useInputState } from "@common/hooks/useInputState";
import ui from "../assets/ui.module.css";
import styles from "../assets/login.module.css";

interface IProps {
    onLogin?: () => void;
    class?: string;
    className?: string;
}

export const LoginForm = ({ onLogin, ['class']: cls, className }: IProps) => {
    const [username, handleUsername] = useInputState();
    const [password, handlePassword] = useInputState();
    const [error, setError] = useState<string | null>(null);
    const [loading, setLoading] = useState(false);

    const handleSubmit = async (e: Event) => {
        e.preventDefault();
        setError(null);
        setLoading(true);
        try {
            await login(username, password);
            onLogin?.();
        } catch (err) {
            setError(err instanceof Error ? err.message : 'Login failed');
        } finally {
            setLoading(false);
        }
    };

    return (
        <form class={clsx(ui.form, cls, className)} onSubmit={handleSubmit}>
            <div class={ui.formGroup}>
                <label class={ui.label}>Username</label>
                <input
                    class={ui.input}
                    type="text"
                    value={username}
                    onInput={handleUsername}
                    autocomplete="username"
                    required
                />
            </div>
            <div class={ui.formGroup}>
                <label class={ui.label}>Password</label>
                <input
                    class={ui.input}
                    type="password"
                    value={password}
                    onInput={handlePassword}
                    autocomplete="current-password"
                    required
                />
            </div>
            {error && <span class={styles.error}>{error}</span>}
            <button class={ui.buttonPrimary} type="submit" disabled={loading}>
                {loading ? 'Logging in…' : 'Log in'}
            </button>
        </form>
    );
};
