import Input from "@/twui/components/form/Input";
import Button from "@/twui/components/layout/Button";
import Stack from "@/twui/components/layout/Stack";
import useSignupForm from "../(hooks)/use-signup-form";
import fetchApi from "@/twui/components/utils/fetch/fetchApi";
import { APIReqObject } from "@/src/types";
import { APIResponseObject } from "@moduletrace/datasquirel/dist/package-shared/types";
import { NSQLITE_TURBOCI_ADMIN_USERS } from "@/src/db/types";
import { twMerge } from "tailwind-merge";
import SignupFormPassword from "./signup-form-password";

type Props = {
    new_deployment_user?: boolean;
    existing_user?: NSQLITE_TURBOCI_ADMIN_USERS;
};

export default function SignupForm({
    new_deployment_user,
    existing_user,
}: Props) {
    const init = useSignupForm({ new_deployment_user, existing_user });
    const {
        newUser,
        setNewUser,
        loading,
        setLoading,
        isPasswordConfirmed,
        setIsPasswordConfirmed,
        pageProps,
    } = init;

    const is_password_valid = Boolean(
        isPasswordConfirmed &&
        Boolean(newUser.password?.match(/./)) &&
        Boolean(newUser.confirmed_password?.match(/./)),
    );

    return (
        <form
            onSubmit={(e) => {
                e.preventDefault();
            }}
        >
            <Stack className="w-full items-stretch gap-6">
                <Input
                    placeholder="Eg. John"
                    title="First Name"
                    defaultValue={existing_user?.first_name}
                    changeHandler={(v) => {
                        setNewUser((prev) => ({
                            ...prev,
                            first_name: v,
                        }));
                    }}
                    required
                    showLabel
                />
                <Input
                    placeholder="Eg. Doe"
                    title="Last Name"
                    defaultValue={existing_user?.last_name}
                    changeHandler={(v) => {
                        setNewUser((prev) => ({
                            ...prev,
                            last_name: v,
                        }));
                    }}
                    showLabel
                />
                <Input
                    placeholder="Email Address"
                    title="Email"
                    type="email"
                    defaultValue={existing_user?.email}
                    changeHandler={(v) => {
                        setNewUser((prev) => ({
                            ...prev,
                            email: v,
                        }));
                    }}
                    required
                    showLabel
                />
                {pageProps.user?.id && !existing_user?.is_super_admin ? (
                    <Input
                        placeholder="Username"
                        title="Username"
                        defaultValue={existing_user?.username}
                        changeHandler={(v) => {
                            setNewUser((prev) => ({
                                ...prev,
                                username: v,
                            }));
                        }}
                        validationRegex={/^[a-z0-9\-]{3,}$/}
                        info={
                            <>
                                Allowed characters:{" "}
                                <code>
                                    <b>a-z, 0-9, -</b>
                                </code>
                                .
                            </>
                        }
                        wrapperWrapperProps={{
                            className: twMerge(
                                "items-start!",
                                Boolean(existing_user?.username)
                                    ? "opacity-70 pointer-events-none"
                                    : "",
                            ),
                        }}
                        disabled={Boolean(existing_user?.username)}
                        required
                        showLabel
                    />
                ) : null}

                {existing_user?.id ? null : <SignupFormPassword {...init} />}
                <Button
                    title="Login"
                    onClick={() => {
                        if (!is_password_valid) {
                            return;
                        }

                        const confirm_msg = pageProps.user?.id
                            ? `Add New User?`
                            : `Create Super Admin Account?`;

                        if (!window.confirm(confirm_msg)) {
                            return;
                        }

                        setLoading(true);

                        fetchApi<APIReqObject, APIResponseObject>(
                            existing_user?.id
                                ? `/api/admin/edit-user`
                                : `/api/auth/signup`,
                            {
                                method: "POST",
                                body: {
                                    new_user: newUser,
                                    user_id: existing_user?.id,
                                },
                            },
                        )
                            .then((res) => {
                                if (res.success) {
                                    if (pageProps.user?.id) {
                                        window.location.pathname = `/admin/users`;
                                    } else {
                                        window.location.reload();
                                    }
                                } else {
                                    window.alert(
                                        res.msg ||
                                            res.error ||
                                            `New User Creation Failed!`,
                                    );
                                    console.log("res", res);
                                }
                            })
                            .finally(() => {
                                setTimeout(() => {
                                    setLoading(false);
                                }, 5000);
                            });
                    }}
                    loading={loading}
                >
                    {existing_user?.id
                        ? `Edit User`
                        : pageProps.user?.super_admin
                          ? "Add User"
                          : "Signup"}
                </Button>
            </Stack>
        </form>
    );
}
