<script lang="ts">
    import Icon from "$lib/components/atoms/icon.svelte";
    import Button from "$lib/components/ui/button/button.svelte";
    import Input from "$lib/components/ui/input/input.svelte";
    import { authVM } from "$lib/domains/security/auth.vm.svelte";
    import { AtSign, KeyRound, Loader2 } from "@lucide/svelte";

    let username = $state<string>("");
    let password = $state<string>("");

    const canSubmit = $derived(
        username.trim().length >= 3 && password.length >= 6 && !authVM.loggingIn,
    );

    async function onSubmit(
        e: SubmitEvent & { currentTarget: HTMLFormElement },
    ) {
        e.preventDefault();
        if (!canSubmit) return;
        await authVM.loginWithCredentials(new FormData(e.currentTarget));
    }
</script>

<form class="space-y-4" onsubmit={onSubmit}>
    <div class="space-y-2">
        <label
            for="username"
            class="text-foreground flex items-center gap-2 text-sm font-medium"
        >
            <Icon icon={AtSign} cls="h-4 w-4 text-muted-foreground" />
            <span>Username</span>
        </label>
        <Input
            id="username"
            name="username"
            type="text"
            required
            minlength={3}
            maxlength={64}
            placeholder="your-username"
            bind:value={username}
            class="h-12"
        />
    </div>

    <div class="space-y-2">
        <label
            for="password"
            class="text-foreground flex items-center gap-2 text-sm font-medium"
        >
            <Icon icon={KeyRound} cls="h-4 w-4 text-muted-foreground" />
            <span>Password</span>
        </label>
        <Input
            id="password"
            name="password"
            type="password"
            required
            minlength={6}
            placeholder="Your password"
            bind:value={password}
            class="h-12"
        />
    </div>

    <Button
        type="submit"
        class="from-primary to-primary/90 hover:from-primary/90 hover:to-primary h-12 w-full bg-gradient-to-r text-base font-medium shadow-lg transition-all duration-200 hover:shadow-xl"
        disabled={!canSubmit}
    >
        {#if authVM.loggingIn}
            <Icon icon={Loader2} cls="mr-2 h-5 w-5 animate-spin" />
            Signing In...
        {:else}
            Sign In
        {/if}
    </Button>
</form>
