import { zodResolver } from "@hookform/resolvers/zod";
import { AxiosError } from "axios";
import { useForm } from "react-hook-form";
import { Link, redirect, useNavigate } from "react-router";
import { z } from "zod";
import { useShallow } from "zustand/react/shallow";
import { PasswordInput } from "~/components/custom-ui/password-input";
import { ThemeToggle } from "~/components/theme/theme-toggle";
import { Button, buttonVariants } from "~/components/ui/button";
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "~/components/ui/card";
import {
    Form,
    FormControl,
    FormField,
    FormItem,
    FormLabel,
    FormMessage,
} from "~/components/ui/form";
import { Input } from "~/components/ui/input";
import auth from "~/lib/api/client/auth";
import { useTokenStore } from "~/stores/token-store";
import { useUsersStore } from "~/stores/users-store";

const schema = z.object({
    username: z.string(),
    password: z.string().min(8),
});

export async function clientLoader() {
    const { token, setToken } = useTokenStore.getState()

    if (token) {
        try {
            await import("~/lib/api/client/user").then(m => m.default.me())

            return redirect("/app/@me")
        } catch (error) {
            const axiosError = error as AxiosError

            if (axiosError.status === 401) {
                setToken(undefined)
            }
        }
    }
}

export default function Login() {
    let navigate = useNavigate()
    let setToken = useTokenStore(state => state.setToken)
    const { setCurrentUserId, addUser } = useUsersStore(useShallow(state => {
        return {
            setCurrentUserId: state.setCurrentUserId,
            addUser: state.addUser
        }
    }))

    const form = useForm<z.infer<typeof schema>>({
        resolver: zodResolver(schema),
    })

    async function onSubmit(values: z.infer<typeof schema>) {
        const response = await auth.login(values)

        setToken(response.token)
        setCurrentUserId(response.user.id)
        addUser(response.user)

        navigate("/app")
    }

    return (
        <Card style={{ viewTransitionName: "auth-card-view" }}>
            <CardHeader style={{ viewTransitionName: "auth-card-header-view" }} className="relative" >
                <CardTitle>Welcome back!</CardTitle>
                <CardDescription>Please sign in to continue.</CardDescription>
                <div className="absolute top-0 right-0 px-6" style={{ viewTransitionName: "auth-card-header-mode-toggle-view" }}>
                    <ThemeToggle />
                </div>
            </CardHeader>
            <CardContent style={{ viewTransitionName: "auth-card-content-view" }}>
                <Form {...form}>
                    <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4" style={{ viewTransitionName: "auth-form-view" }}>
                        <FormField
                            control={form.control}
                            name="username"
                            render={({ field }) => (
                                <FormItem style={{ viewTransitionName: "email-field-view" }}>
                                    <FormLabel required>Username</FormLabel>
                                    <FormControl>
                                        <Input {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                        <FormField
                            control={form.control}
                            name="password"
                            render={({ field }) => (
                                <FormItem style={{ viewTransitionName: "password-field-view" }}>
                                    <FormLabel required>Password</FormLabel>
                                    <FormControl>
                                        <PasswordInput {...field} />
                                    </FormControl>
                                    <FormMessage />
                                </FormItem>
                            )}
                        />
                        <Button className="w-full" type="submit" style={{ viewTransitionName: "submit-button-view" }}>Log In</Button>
                    </form>
                </Form>
            </CardContent>
            <CardFooter style={{ viewTransitionName: "auth-card-footer-view" }}>
                <div className="flex items-center">
                    <span className="text-muted-foreground text-sm">Don't have an account?</span>
                    <Link className={buttonVariants({ variant: "link", size: "sm" })} to="/register" viewTransition>Register</Link>
                </div>
            </CardFooter>
        </Card>
    );
}