import useLoginForm from "@/src/hooks/use-login-form";
import Tag from "@/twui/components/elements/Tag";
import Form from "@/twui/components/form/Form";
import Input from "@/twui/components/form/Input";
import Button from "@/twui/components/layout/Button";
import Stack from "@/twui/components/layout/Stack";
import z from "zod";

export default function LoginForm() {
    const { loading, setLoginData, submitLogin, alert } = useLoginForm();

    return (
        <Form
            className="w-full"
            submitHandler={() => {
                submitLogin();
            }}
        >
            <Stack className="w-full items-stretch gap-6">
                {alert?.text ? (
                    <Tag
                        color="error"
                        variant="outlined"
                        className="py-2 px-6 opacity-70"
                    >
                        {alert.text}
                    </Tag>
                ) : null}

                <Input
                    placeholder="Email Address or Username"
                    title="Email/Username"
                    changeHandler={(v) => {
                        const email_schema = z.email();
                        const is_email = email_schema.safeParse(v);

                        setLoginData((prev) => ({
                            ...prev,
                            email: is_email.success ? v : undefined,
                            username: is_email.success ? undefined : v,
                        }));
                    }}
                    validity={
                        alert?.field_name == "email-username"
                            ? {
                                  isValid: false,
                                  msg: alert?.text,
                              }
                            : {
                                  isValid: true,
                              }
                    }
                    showLabel
                />

                <Input
                    placeholder="Password"
                    title="Password"
                    type="password"
                    onChange={(e) => {
                        setLoginData((prev) => ({
                            ...prev,
                            password: e.target.value,
                        }));
                    }}
                    validity={
                        alert?.field_name == "password"
                            ? {
                                  isValid: false,
                                  msg: alert?.text,
                              }
                            : {
                                  isValid: true,
                              }
                    }
                    showLabel
                />

                <Button title="Login" loading={loading} onClick={submitLogin}>
                    Login
                </Button>
            </Stack>{" "}
        </Form>
    );
}
