// LoginForm.tsx
import Button from "@/components/generics/button/Button";
import Input from "@/components/generics/input/Input";
import { useAuth } from "@/shared/hooks/useAuth/useAuth";
import { useMemo, useState } from "react";
import Modal from "react-modal";

import "./LoginForm.scss";

const customStyles = {
  content: {
    top: "50%",
    left: "50%",
    right: "auto",
    bottom: "auto",
    transform: "translate(-50%, -50%)",
    borderRadius: "15px",
    width: "400px",
  },
};

const LoginForm = () => {
  const { login, isAuth } = useAuth();
  const [value, setValue] = useState<string>("");
  const [error, setError] = useState<string | null>(null);

  const rules = useMemo(
    () => [
      {
        rule: (newValue: string) => newValue.trim().length >= 5,
        errorMessage: "Пожалуйста, введите имя пользователя длиной не менее 5 символов",
      },
    ],
    []
  );

  const onSetValue = (newValue: string) => {
    if (newValue.length <= 65) {
      setValue(newValue);
    }
  };

  const onSetError = (newError: string | null) => {
    setError(newError);
  };

  const handleLogin = () => {
    if (error == null) {
      login({ name: value.trim() });
    }
  };

  return (
    <Modal style={customStyles} isOpen={!isAuth} ariaHideApp={false}>
      <div className={"login_form"}>
        <h3>Введите ваше имя</h3>
        <Input
          name={"userName"}
          placeholder={"Иванов И. И."}
          rules={rules}
          value={value}
          onSetValue={onSetValue}
          error={error}
          onSetError={onSetError}
        />
        <div className="button_container">
          <Button name="Войти" onClick={handleLogin} disabled={value.trim().length === 0 || error != null} />
        </div>
      </div>
    </Modal>
  );
};

export default LoginForm;
