import Inventory2Outlined from "@mui/icons-material/Inventory2Outlined";
import LoginOutlined from "@mui/icons-material/LoginOutlined";
import TextField from "@mui/material/TextField";
import { useEffect, useState } from "react";
import { Navigate, useLocation, useNavigate } from "react-router-dom";
import { useAuth } from "@/app/auth/AuthProvider.jsx";
import { isDocumentEntryTarget, redirectAfterLogin, resolveLoginRedirectTarget } from "@/features/auth/loginRedirect.js";
import { Button } from "@/shared/ui/Button.jsx";
import { useToast } from "@/shared/ui/ToastProvider.jsx";

export function LoginPage() {
  const [username, setUsername] = useState("admin");
  const [password, setPassword] = useState("");
  const [submitting, setSubmitting] = useState(false);
  const { login, user } = useAuth();
  const { showToast } = useToast();
  const navigate = useNavigate();
  const location = useLocation();
  const from = resolveLoginRedirectTarget(location);
  const needsDocumentRedirect = isDocumentEntryTarget(from);

  useEffect(() => {
    if (user && needsDocumentRedirect) {
      redirectAfterLogin(from, navigate);
    }
  }, [from, navigate, needsDocumentRedirect, user]);

  if (user) {
    if (needsDocumentRedirect) {
      return null;
    }
    return <Navigate to={from} replace />;
  }

  const submit = async (event) => {
    event.preventDefault();
    setSubmitting(true);
    try {
      await login({ username, password });
      showToast("登录成功", "success");
      redirectAfterLogin(from, navigate);
    } catch (err) {
      showToast(err.message || "登录失败", "error");
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <main className="login-page">
      <form className="login-panel" onSubmit={submit}>
        <div className="login-brand">
          <div className="brand-mark">
            <Inventory2Outlined fontSize="small" />
          </div>
          <div>
            <h1>HYApp 管理平台</h1>
            <p>Admin Platform</p>
          </div>
        </div>

        <div className="login-form">
          <TextField
            autoFocus
            fullWidth
            label="账号"
            onChange={(event) => setUsername(event.target.value)}
            required
            value={username}
          />
          <TextField
            fullWidth
            label="密码"
            onChange={(event) => setPassword(event.target.value)}
            required
            type="password"
            value={password}
          />
          <Button disabled={submitting} type="submit" variant="primary">
            <LoginOutlined fontSize="small" />
            {submitting ? "登录中" : "登录"}
          </Button>
        </div>
      </form>
    </main>
  );
}
