import { Button } from "@/components/ui/button.tsx";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card.tsx";
import { Input } from "@/components/ui/input.tsx";
import { Label } from "@/components/ui/label.tsx";
import { doLogin } from "@/state/user.ts";
import { useState } from "react";
import { useLocation } from "wouter";

export function LoginForm() {
    const [username, setUsername] = useState("");
    const [password, setPassword] = useState("");
    const [, setLocation] = useLocation();

    return (
      <Card className="w-full max-w-sm">
        <CardHeader>
          <CardTitle className="text-2xl">Login</CardTitle>
          <CardDescription>
            Enter your email below to login to your account.
          </CardDescription>
        </CardHeader>
        <CardContent className="grid gap-4">
          <div className="grid gap-2">
            <Label htmlFor="username">Username</Label>
            <Input id="username" type="text" placeholder="username" required value={username} onChange={e=> setUsername(e.target.value)}/>
          </div>
          <div className="grid gap-2">
            <Label htmlFor="password">Password</Label>
            <Input id="password" type="password" required value={password} onChange={e=> setPassword(e.target.value)}/>
          </div>
        </CardContent>
        <CardFooter>
          <Button className="w-full" onClick={()=>{
                doLogin({
                    username,
                    password,
                }).then((r)=>{
                    if (typeof r === "string") {
                        alert(r);
                    } else {
                        setLocation("/");
                    }
                })
          }}>Sign in</Button>
        </CardFooter>
      </Card>
    )
}

export function LoginPage() {
    return (
      <div className="flex items-center justify-center h-screen">
        <LoginForm />
      </div>
    )
}

export default LoginPage;