import {
  selectFormValid,
  selectStatusIsLoading,
  useAuthStore,
} from "../../model";
import type { SubmitEvent, ChangeEvent } from "react";

/**
 * Login form component
 */
export function LoginForm() {
  const { formData, setEmail, setPassword, login } = useAuthStore();

  const formValid = useAuthStore(selectFormValid);
  const isLoading = useAuthStore(selectStatusIsLoading);

  const disabled = !formValid || isLoading;

  const handleEmailChange = (e: ChangeEvent<HTMLInputElement>) => {
    setEmail(e.target.value);
  };

  const handlePasswordChange = (e: ChangeEvent<HTMLInputElement>) => {
    setPassword(e.target.value);
  };

  const handleSubmit = (e: SubmitEvent<HTMLFormElement>) => {
    e.preventDefault();
    login();
  };

  return (
    <form aria-label="Login form" onSubmit={handleSubmit}>
      <input
        type="email"
        aria-label="Email"
        value={formData?.email?.value ?? ""}
        onChange={handleEmailChange}
      />
      <input
        type="password"
        aria-label="Password"
        value={formData?.password?.value ?? ""}
        onChange={handlePasswordChange}
      />
      <button type="submit" disabled={disabled}>
        Login
      </button>
    </form>
  );
}
