import { LstCard } from "../extendedUI/LstCard";
import { CardHeader } from "../ui/card";
import { toast } from "sonner";

import { Label } from "../ui/label";
import { Input } from "../ui/input";
import { Button } from "../ui/button";
import { useForm } from "@tanstack/react-form";
import { Separator } from "../ui/separator";
import { useNavigate } from "@tanstack/react-router";
import { useState } from "react";
import axios from "axios";

export default function RegisterForm() {
    const navigate = useNavigate();
    const [registering, setRegistering] = useState(false);
    const form = useForm({
        defaultValues: {
            username: "",
            password: "",
            email: "",
        },
        onSubmit: async ({ value }) => {
            setRegistering(true);
            try {
                const res = await axios.post("/api/auth/register", value);

                if (res.data.success) {
                    navigate({ to: "/login" });
                    form.reset();
                    toast.success(
                        `${value.username} was just created please login`
                    );
                    setRegistering(false);
                }

                if (!res.data.success) {
                    toast.error(res.data.message);
                    setRegistering(false);
                }
            } catch (error) {
                //console.log(error);
                toast.error("There was an error registering");
                setRegistering(false);
            }
        },
    });

    return (
        <div className="ml-[25%]">
            <LstCard className="p-3 w-96">
                <CardHeader>
                    <div>
                        <p className="text-2xl">Login to register</p>
                    </div>
                </CardHeader>
                <hr className="rounded"></hr>
                <form
                    onSubmit={(e) => {
                        e.preventDefault();
                        e.stopPropagation();
                    }}
                >
                    <Separator />
                    <form.Field
                        name="username"
                        validators={{
                            // We can choose between form-wide and field-specific validators
                            onChange: ({ value }) =>
                                value.length > 3
                                    ? undefined
                                    : "Username must be longer than 3 letters",
                        }}
                        children={(field) => {
                            return (
                                <div className="m-2 min-w-48 max-w-96 p-2">
                                    <Label htmlFor="username" className="mb-2">
                                        Username
                                    </Label>
                                    <Input
                                        name={field.name}
                                        value={field.state.value}
                                        onBlur={field.handleBlur}
                                        //type="number"
                                        onChange={(e) =>
                                            field.handleChange(e.target.value)
                                        }
                                    />
                                    {field.state.meta.errors.length ? (
                                        <em>
                                            {field.state.meta.errors.join(",")}
                                        </em>
                                    ) : null}
                                </div>
                            );
                        }}
                    />
                    <Separator />
                    <form.Field
                        name="email"
                        validators={{
                            // We can choose between form-wide and field-specific validators
                            onChange: ({ value }) =>
                                value.length > 3
                                    ? undefined
                                    : "You must enter a valid email",
                        }}
                        children={(field) => {
                            return (
                                <div className="m-2 min-w-48 max-w-96 p-2">
                                    <Label htmlFor="email" className="mb-2">
                                        Alpla Email
                                    </Label>
                                    <Input
                                        name={field.name}
                                        value={field.state.value}
                                        onBlur={field.handleBlur}
                                        //type="number"
                                        onChange={(e) =>
                                            field.handleChange(e.target.value)
                                        }
                                    />
                                    {field.state.meta.errors.length ? (
                                        <em>
                                            {field.state.meta.errors.join(",")}
                                        </em>
                                    ) : null}
                                </div>
                            );
                        }}
                    />
                    <Separator className="m-2" />
                    <p>
                        Your password Should be your windows password, as this
                        is how you will interact with alplaprod
                    </p>
                    <form.Field
                        name="password"
                        // We can choose between form-wide and field-specific validators
                        validators={{
                            onChangeAsyncDebounceMs: 500,
                            onChangeAsync: ({ value }) => {
                                // if (
                                //     window.location.pathname.includes(
                                //         "/users"
                                //     ) &&
                                //     value.length === 0
                                // ) {
                                //     return;
                                // }
                                if (value.length < 4) {
                                    return "Password must be at least 4 characters long.";
                                }

                                if (!/[A-Z]/.test(value)) {
                                    return "Password must contain at least one uppercase letter.";
                                }

                                if (!/[a-z]/.test(value)) {
                                    return "Password must contain at least one lower case letter.";
                                }

                                if (!/[0-9]/.test(value)) {
                                    return "Password must contain at least one number.";
                                }

                                if (
                                    !/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(
                                        value
                                    )
                                ) {
                                    return "Password must contain at least one special character.";
                                }
                            },
                        }}
                        children={(field) => {
                            return (
                                <div className="m-2 min-w-48 max-w-96 p-2">
                                    <Label htmlFor="password1" className="mb-2">
                                        Password
                                    </Label>
                                    <Input
                                        name={field.name}
                                        value={field.state.value}
                                        onBlur={field.handleBlur}
                                        type="password"
                                        onChange={(e) =>
                                            field.handleChange(e.target.value)
                                        }
                                    />
                                    {field.state.meta.errors.length ? (
                                        <em>
                                            {field.state.meta.errors.join(",")}
                                        </em>
                                    ) : null}
                                </div>
                            );
                        }}
                    />
                    <div className="mt-4 ml-4 flex justify-end">
                        <Button
                            type="submit"
                            onClick={form.handleSubmit}
                            disabled={registering}
                        >
                            Register
                        </Button>
                    </div>
                </form>
            </LstCard>
        </div>
    );
}
