"use client";

import { useActionState } from "react";
import { ArrowRight, LockKey } from "@phosphor-icons/react";
import type { AuthActionState } from "@/app/auth/actions";
import styles from "./login-form.module.css";

type LoginAction = (
  previous: AuthActionState,
  formData: FormData,
) => Promise<AuthActionState>;

export function LoginForm({ action }: { action: LoginAction }) {
  const [state, formAction, pending] = useActionState(action, null);

  return (
    <form className={styles.form} action={formAction} noValidate>
      <div className={styles.field}>
        <label htmlFor="owner-email">Owner email</label>
        <input
          id="owner-email"
          name="email"
          type="email"
          autoComplete="email"
          required
          aria-describedby={state?.error ? "login-error" : undefined}
        />
      </div>
      <div className={styles.field}>
        <label htmlFor="owner-password">Password</label>
        <input
          id="owner-password"
          name="password"
          type="password"
          autoComplete="current-password"
          required
          aria-describedby={state?.error ? "login-error" : undefined}
        />
      </div>
      {state?.error ? (
        <p id="login-error" className={styles.error} role="alert">
          {state.error}
        </p>
      ) : null}
      <button className={styles.submit} type="submit" disabled={pending}>
        <span className={styles.buttonIcon} aria-hidden="true">
          <LockKey size={18} weight="bold" />
        </span>
        {pending ? "Checking access…" : "Enter studio"}
        <ArrowRight size={18} weight="bold" aria-hidden="true" />
      </button>
    </form>
  );
}
