"use client";
import { useState } from "react";
import { z } from "zod";
export function StaffLogin({
  mock = false,
  apiKey,
  preview = false,
}: {
  mock?: boolean;
  apiKey?: string;
  preview?: boolean;
}) {
  const [email, setEmail] = useState(""),
    [password, setPassword] = useState("");
  const [busy, setBusy] = useState(false),
    [error, setError] = useState("");
  async function login() {
    if (busy) return;
    if (preview) {
      window.location.replace("/staff");
      return;
    }
    setBusy(true);
    setError("");
    try {
      let idToken = "mock-staff-reviewed-identity";
      if (!mock) {
        if (!apiKey || !z.email().safeParse(email).success || !password)
          throw new Error("Check your staff email and password.");
        const response = await fetch(
          `https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=${encodeURIComponent(apiKey)}`,
          {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ email, password, returnSecureToken: true }),
            signal: AbortSignal.timeout(15000),
          },
        );
        if (!response.ok)
          throw new Error(
            "Sign-in failed. Check your credentials and provisioned staff access.",
          );
        idToken = z
          .object({ idToken: z.string().min(1) })
          .parse(await response.json()).idToken;
      }
      const response = await fetch("/api/staff/session", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ idToken }),
        signal: AbortSignal.timeout(15000),
      });
      if (!response.ok)
        throw new Error(
          "This staff account could not be authorized. Contact your administrator.",
        );
      window.location.replace("/staff");
    } catch {
      setError(
        "Sign-in failed. Check your credentials and authorized staff access, then retry.",
      );
    } finally {
      setPassword("");
      setBusy(false);
    }
  }
  return (
    <div className="staff-card staff-login">
      <p className="staff-eyebrow">MAXCREDIT / STAFF</p>
      <h1>Application desk</h1>
      <p>
        {preview
          ? "Preview the desk your team uses to review loan applications."
          : "Sign in with your provisioned staff account."}
      </p>
      {preview ? (
        <p className="staff-notice">
          Preview · No sign-in needed. The desk shows synthetic sample
          applications, and nothing is sent to MaxCredit.
        </p>
      ) : mock ? (
        <p className="staff-notice">
          Local test access: reviewer@example.invalid. This preview contains
          synthetic applications only.
        </p>
      ) : null}
      <form
        onSubmit={(event) => {
          event.preventDefault();
          void login();
        }}
      >
        <fieldset disabled={busy}>
          {!mock && !preview && (
            <>
              <label htmlFor="staff-email">Staff email</label>
              <input
                id="staff-email"
                type="email"
                autoComplete="username"
                value={email}
                onChange={(event) => setEmail(event.target.value)}
                required
                maxLength={254}
              />
              <label htmlFor="staff-password">Password</label>
              <input
                id="staff-password"
                type="password"
                autoComplete="current-password"
                value={password}
                onChange={(event) => setPassword(event.target.value)}
                required
              />
            </>
          )}
          <button type="submit" className="staff-primary">
            {preview
              ? "Open preview desk"
              : busy
                ? "Signing in..."
                : mock
                  ? "Sign in as test reviewer"
                  : "Sign in"}
          </button>
        </fieldset>
        {error && (
          <p role="alert" className="staff-error">
            {error}
          </p>
        )}
      </form>
      <p className="staff-muted">
        {preview
          ? "In the live desk, access is restricted to authorized staff accounts."
          : "Access is restricted to authorized staff. Contact your administrator for account access."}
      </p>
    </div>
  );
}
