import { Stack } from "@mui/material";
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import { toast } from "react-toastify";
import { z } from "zod";

import { isError } from "@/common/utils/axios.utils";
import { useLogin } from "@/contracts/identity";
import { Roles } from "@/entities";
import { useIdentityStore } from "@/features";
import { InputField, PrimaryButton } from "@/shared";
import { useFormikWithZod } from "@/utils/useFormikWithZod";

interface LoginState {
	username: string;
	password: string;
}

const initialValues: LoginState = {
	username: "",
	password: "",
};

export function LoginForm() {
	const { t } = useTranslation();
	const { login } = useIdentityStore();
	const [isLoading, setIsLoading] = useState(false);
	const navigate = useNavigate();
	const { mutateAsync } = useLogin();

	const validationSchema = z.object({
		username: z.string({
			required_error: t("required field"),
			invalid_type_error: t("required field"),
		}),
		password: z.string({
			required_error: t("required field"),
			invalid_type_error: t("required field"),
		}),
	});

	const {
		values,
		errors,
		handleSubmit,
		handleBlur,
		handleChange,
		isValid,
		touched,
	} = useFormikWithZod({
		initialValues,
		validationSchema,
		onSubmit: async (values) => {
			try {
				setIsLoading(true);

				const response = await mutateAsync({ data: values });

				login({
					username: response.username,
					id: response.id,
					role: response.role as Roles,
				});
				navigate("/app");
			} catch (error: unknown) {
				if (isError(error, "InvalidUsernameOrPassword")) {
					toast.error("Неверное имя пользователя или пароль");
					return;
				}

				toast.error("Произошла неизвестная ошибка");
			} finally {
				setIsLoading(false);
			}
		},
	});

	return (
		<form onSubmit={handleSubmit} className="w-100">
			<Stack spacing="31px">
				<Stack spacing="15px">
					<InputField
						disabled={isLoading}
						name="username"
						label={t("Login")}
						placeholder={t("Type login")}
						defaultValue={values.username}
						onChange={handleChange}
						onBlur={handleBlur}
						error={touched.username && errors.username}
						autoComplete="on"
					/>
					<InputField
						disabled={isLoading}
						name="password"
						label={t("Password")}
						placeholder={t("Type password")}
						defaultValue={values.password}
						onChange={handleChange}
						onBlur={handleBlur}
						error={touched.password && errors.password}
						type="password"
						autoComplete="on"
					/>

					<PrimaryButton
						disabled={!isValid || isLoading}
						type="submit"
					>
						{t("enter")}
					</PrimaryButton>
				</Stack>
			</Stack>
		</form>
	);
}
