import { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { useAuth } from "../hooks/useAuth";
import { formatAuthError } from "../utils/formatAuthError";
import { AuthField } from "./AuthField";
import { AuthMessage } from "./AuthMessage";
import { AuthSubmit } from "./AuthSubmit";

function UserIcon(): JSX.Element {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none">
      <path
        d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2M12 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8Z"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

function LockIcon(): JSX.Element {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none">
      <path
        d="M7 11V7a5 5 0 0 1 10 0v4M5 11h14a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2Z"
        stroke="currentColor"
        strokeWidth="2"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
    </svg>
  );
}

export function LoginForm(): JSX.Element {
  const auth = useAuth();
  const navigate = useNavigate();
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);

  return (
    <form
      className="z-login-form"
      onSubmit={async (event) => {
        event.preventDefault();
        setError("");
        setIsSubmitting(true);
        try {
          const user = await auth.login(email.trim(), password);
          navigate(user.role === "admin" ? "/admin" : "/profile");
        } catch (loginError) {
          const fallback =
            loginError && typeof loginError === "object" && "response" in loginError
              ? (loginError as { response?: { status?: number } }).response?.status === 401
                ? "Invalid credentials"
                : (loginError as { response?: { status?: number } }).response?.status === 403
                  ? "Email not verified or account blocked"
                  : "Login failed"
              : "Login failed";
          setError(formatAuthError(loginError, fallback));
        } finally {
          setIsSubmitting(false);
        }
      }}
    >
      <AuthField
        icon={<UserIcon />}
        placeholder="Email"
        type="email"
        autoComplete="email"
        value={email}
        onChange={(event) => setEmail(event.target.value)}
        required
      />
      <AuthField
        icon={<LockIcon />}
        placeholder="Password"
        type="password"
        autoComplete="current-password"
        value={password}
        onChange={(event) => setPassword(event.target.value)}
        required
      />
      <AuthSubmit loading={isSubmitting} loadingText="Logging in..." idleText="Login" />
      <p className="z-login-meta">
        <Link className="z-login-link" to="/forgot-password">
          Forgot password?
        </Link>
      </p>
      <p className="z-login-meta">
        No account yet?{" "}
        <Link className="z-login-link" to="/register">
          Register
        </Link>
      </p>
      {error ? <AuthMessage type="error" text={error} /> : null}
    </form>
  );
}
