import { useSessionStore } from "../../lib/store/sessionStore";
import { LstCard } from "../extendedUI/LstCard";
import { CardHeader } from "../ui/card";
import { toast } from "sonner";
import { z } from "zod";
import { useRouter, useSearch } from "@tanstack/react-router";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Label } from "../ui/label";
import { Input } from "../ui/input";
import { Checkbox } from "../ui/checkbox";
import { Button } from "../ui/button";

const FormSchema = z.object({
    username: z.string().min(1, "You must enter a valid username"),
    password: z.string().min(4, "You must enter a valid password"),
    rememberMe: z.boolean(),
});

const LoginForm = () => {
    const { setSession } = useSessionStore();
    const rememeberMe = localStorage.getItem("rememberMe") === "true";
    const username = localStorage.getItem("username") || "";
    const router = useRouter();
    const search = useSearch({ from: "/login" });
    const {
        register,
        handleSubmit,
        control,
        formState: { errors },
    } = useForm<z.infer<typeof FormSchema>>({
        resolver: zodResolver(FormSchema),
        defaultValues: {
            username: username || "",
            password: "",
            rememberMe: rememeberMe,
        },
    });

    const onSubmitLogin = async (value: z.infer<typeof FormSchema>) => {
        // Do something with form data

        // first update the rememberMe incase it was selected
        if (value.rememberMe) {
            localStorage.setItem("rememberMe", value.rememberMe.toString());
            localStorage.setItem("username", value.username);
        } else {
            localStorage.removeItem("rememberMe");
            localStorage.removeItem("username");
        }

        try {
            const response = await fetch("/api/auth/login", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify({
                    username: value.username,
                    password: value.password,
                }),
            });

            const data = await response.json();

            // Store token in localStorage
            // localStorage.setItem("auth_token", data.data.token);
            if (data.success) {
                const prod = btoa(
                    `${value.username.toLowerCase()}:${value.password}`
                );
                const prodUser = { ...data.user, prod: prod };

                setSession(prodUser, data.token);
                toast.success(`You are logged in as ${data.user.username}`);

                console.log(search.redirect ? search.redirect : "oops");
                router.history.push(search.redirect ? search.redirect : "/");
            }

            if (!data.success) {
                toast.error(`${data.message}`);
            }

            //console.log(data);
        } catch (err) {
            toast.error("Invalid credentials");
        }
    };

    return (
        <div className="ml-[25%]">
            <LstCard className="p-3 w-96">
                <CardHeader>
                    <div>
                        <p className="text-2xl">Login to LST</p>
                    </div>
                </CardHeader>
                <hr className="rounded"></hr>
                <form onSubmit={handleSubmit(onSubmitLogin)}>
                    <div>
                        <Label htmlFor="username" className="m-1">
                            Username
                        </Label>
                        <Input
                            placeholder="smith001"
                            {...register("username")}
                            className={errors.username ? "border-red-500" : ""}
                            aria-invalid={!!errors.username}
                        />
                        {errors.username && (
                            <p className="text-red-500 text-sm mt-1">
                                {errors.username.message}
                            </p>
                        )}
                    </div>
                    <div>
                        <>
                            <Label htmlFor={"password"} className="m-1">
                                Password
                            </Label>
                            <Input
                                type="password"
                                {...register("password")}
                                className={
                                    errors.password ? "border-red-500" : ""
                                }
                                aria-invalid={!!errors.password}
                            />
                            {errors.password && (
                                <p className="text-red-500 text-sm mt-1">
                                    {errors.password.message}
                                </p>
                            )}
                        </>
                    </div>
                    <div className="flex justify-between pt-2">
                        <div className="flex">
                            <Controller
                                render={({ field }) => (
                                    <>
                                        <Checkbox
                                            id="remember"
                                            checked={field.value}
                                            onCheckedChange={field.onChange}
                                        />
                                        <label
                                            htmlFor="remember"
                                            className="pl-2 text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
                                        >
                                            remember me
                                        </label>
                                    </>
                                )}
                                control={control}
                                name="rememberMe"
                                defaultValue={rememeberMe}
                            />
                        </div>

                        <div className="flex justify-end">
                            <Button type="submit">Submit</Button>
                        </div>
                    </div>
                </form>
            </LstCard>
        </div>
    );
};

export default LoginForm;
