import { TextUtil } from "@greatness/util";
import { useCallback, useState } from "react";
import { boolean, object, Schema, string } from "yup";

import Button from "@greatness/components/src/Button";
import CheckboxInput from "@greatness/components/src/form/checkbox/CheckboxInput";
import Form from "@greatness/components/src/form/Form";
import TextInput from "@greatness/components/src/form/text/TextInput";
import { useSessionContext } from "@/components/SessionContext";
import { useIntl } from "@/i18n/IntlProvider";
import type { IUserLoginRequest } from "@/api/controller/user";

const loginValidation: Schema<IUserLoginRequest> = object({
  email: string().required(),
  password: string().required(),
  rememberMe: boolean().required(),
});

export default function LoginForm() {
  const { t } = useIntl();
  const { login } = useSessionContext();
  const [errorMessage, setErrorMessage] = useState<string | null>(null);
  const [isLoginLoading, setIsLoginLoading] = useState(false);

  const handleLogin = useCallback(
    async (loginValues: IUserLoginRequest) => {
      setIsLoginLoading(true);
      const submitError = await login(
        loginValues.email.toLowerCase(),
        loginValues.password,
        loginValues.rememberMe ?? false,
      );
      if (submitError) {
        const shownMessage = TextUtil.isEmpty(submitError.message)
          ? t("page.login.error.wrongPassword")
          : submitError.message;
        setErrorMessage(shownMessage);
        setIsLoginLoading(false);
      }
    },
    [t, login],
  );

  return (
    <div className="flex flex-col">
      <h3 className="my-l mx-0 text-center">{t("page.login.title")}</h3>
      {!TextUtil.isEmpty(errorMessage) && (
        <h6 className="text-red mb-m">{errorMessage!}</h6>
      )}
      <Form<IUserLoginRequest>
        className="flex flex-col gap-y-m"
        handleSubmit={handleLogin}
        defaultValues={{
          rememberMe: false,
        }}
        validation={loginValidation}
      >
        <div className="flex gap-m">
          <TextInput type="email" name="email" label={t("field.common.email")} />
        </div>
        <div className="flex gap-m">
          <TextInput
            type="password"
            autoComplete="current-password"
            name="password"
            label={t("field.common.password")}
          />
        </div>
        <div className="flex gap-m flex-col mb-m">
          <div className="flex-1 flex word-break-keep-all">
            <CheckboxInput name="rememberMe" label={t("page.login.rememberMe")} />
          </div>
          <Button
            type="submit"
            label={t("page.login.action.login")}
            isLoading={isLoginLoading}
          />
        </div>
      </Form>
    </div>
  );
};
