import React, { useEffect, useState } from "react";

import { Alert, Box, Button, Checkbox, Divider, FormControlLabel, Paper, TextField, Typography } from "@mui/material";

import { useLocation, useNavigate } from "react-router-dom";

import { api, getApiErrorMessage } from "../api";
import { getRememberMePref, setAuthPersistencePreference } from "../auth";
import GoogleAuthCard from "../components/GoogleAuthCard";
import MicrosoftAuthCard from "../components/MicrosoftAuthCard";
import TwoFactorChallenge from "../components/TwoFactorChallenge";
import TurnstileWidget from "../components/TurnstileWidget";
import { useToast } from "../toast";
import { useI18n } from "../i18n/I18nProvider";

type AuthConfig = {
  requireAuth: boolean;
  googleEnabled: boolean;
  microsoftEnabled: boolean;
  localEnabled: boolean;
  allowRegistration: boolean;
  requireEmailVerification: boolean;
  turnstileEnabled?: boolean;
  turnstileSiteKey?: string;
};

export default function LoginPage({ initialMode = "login" }: { initialMode?: "login" | "register" }) {
  const { toast } = useToast();
  const { t } = useI18n();
  const navigate = useNavigate();
  const location = useLocation() as any;

  const [cfg, setCfg] = useState<AuthConfig | null>(null);

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [rememberMe, setRememberMe] = useState(() => getRememberMePref());
  const [loading, setLoading] = useState(false);
  const [pendingToken, setPendingToken] = useState<string | null>(null);
  const [emailNotVerified, setEmailNotVerified] = useState(false);
  const [resendingVerification, setResendingVerification] = useState(false);
  const [verificationResent, setVerificationResent] = useState(false);
  const [fieldErrors, setFieldErrors] = useState<{ email?: string; password?: string; confirmPassword?: string }>({});
  const [registerMode, setRegisterMode] = useState(initialMode === "register");
  const [turnstileToken, setTurnstileToken] = useState("");

  const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

  const requestedNextPath = location?.state?.from;
  const nextPath = typeof requestedNextPath === "string"
    && requestedNextPath.startsWith("/")
    && !requestedNextPath.startsWith("//")
    && !requestedNextPath.includes("\\")
    ? requestedNextPath
    : "/dashboard";

  useEffect(() => {
    api
      .get<AuthConfig>("/auth/config")
      .then((r) => setCfg(r.data))
      .catch(() => setCfg(null));
  }, []);

  async function completeLogin() {
    setAuthPersistencePreference(rememberMe ? "local" : "session");
    await api.get("/auth/me");
    toast(t("signedIn"), "success");
    navigate(nextPath, { replace: true });
  }

  function validate(mode: "login" | "register") {
    const errors: { email?: string; password?: string; confirmPassword?: string } = {};
    if (!email.trim()) errors.email = mode === "login" ? t("usernameOrEmailRequired") : t("emailRequired");
    else if (mode === "register" && !EMAIL_PATTERN.test(email.trim())) errors.email = t("invalidEmail");

    if (!password) errors.password = t("passwordRequired");
    else if (mode === "register" && password.length < 8) errors.password = t("passwordTooShort");

    if (mode === "register" && password && confirmPassword !== password) {
      errors.confirmPassword = t("passwordsDoNotMatch");
    }

    setFieldErrors(errors);
    return Object.keys(errors).length === 0;
  }

  async function submit(mode: "login" | "register") {
    if (!validate(mode)) return;
    setLoading(true);
    setEmailNotVerified(false);
    setVerificationResent(false);
    try {
      const url = mode === "register" ? "/auth/register" : "/auth/login";
      const payload = { email, password, rememberMe, ...(cfg?.turnstileEnabled ? { turnstileToken } : {}) };
      const res = await api.post<{ requiresTwoFactor?: boolean; pendingToken?: string; verificationRequired?: boolean }>(url, payload);
      if (res.data?.verificationRequired) {
        setEmailNotVerified(true);
        toast(t("registerCheckEmailForVerification"), "info");
        return;
      }
      if (res.data?.requiresTwoFactor && res.data.pendingToken) {
        setPendingToken(res.data.pendingToken);
        return;
      }
      await completeLogin();
    } catch (e: any) {
      if (mode === "login" && e?.response?.data?.error === "email_not_verified") {
        setEmailNotVerified(true);
      } else {
        toast(getApiErrorMessage(e, t("loginFailed")), "error");
      }
    } finally {
      setLoading(false);
    }
  }

  async function resendVerification() {
    setResendingVerification(true);
    try {
      await api.post("/auth/resend-verification-email", { email });
      setVerificationResent(true);
      toast(t("verificationEmailResent"), "success");
    } catch (e: any) {
      toast(getApiErrorMessage(e, t("verifyEmailFailed")), "error");
    } finally {
      setResendingVerification(false);
    }
  }

  const allowReg = cfg?.allowRegistration ?? false;

  return (
    <Box
      sx={{
        minHeight: "100vh",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        p: 2,
        background:
          "radial-gradient(1200px 700px at 20% 0%, rgba(79,140,255,0.14), transparent 55%), radial-gradient(900px 600px at 80% 20%, rgba(245,158,11,0.10), transparent 55%)",
      }}
    >
      <Paper sx={{ width: "min(520px, 100%)", p: 4, borderRadius: 4, border: "none", boxShadow: "0px 1px 2px 0px rgba(15,23,42,0.04), 0px 8px 24px -12px rgba(15,23,42,0.12)" }}>
        <Typography variant="h5" sx={{ fontWeight: 900, mb: 0.5 }}>
          {registerMode ? t("createAccount") : t("signInTitle")}
        </Typography>
        <Typography sx={{ color: "text.secondary", mb: 2 }}>
          {cfg?.requireAuth ? t("authRequired") : t("authOptional")}
        </Typography>

        {pendingToken ? (
          <TwoFactorChallenge
            pendingToken={pendingToken}
            onCancel={() => setPendingToken(null)}
            onSuccess={() => { setPendingToken(null); void completeLogin(); }}
          />
        ) : (
          <>
            <Box
              component="form"
              onSubmit={(e) => { e.preventDefault(); void submit(registerMode ? "register" : "login"); }}
              sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}
            >
                {registerMode && cfg && !allowReg ? <Alert severity="info">{t("registrationUnavailable")}</Alert> : null}
                {cfg?.requireEmailVerification && emailNotVerified && (
                  <Alert
                    severity="warning"
                    action={
                      <Button color="inherit" size="small" disabled={resendingVerification || verificationResent} onClick={() => void resendVerification()}>
                        {verificationResent ? t("verificationEmailResent") : t("resendVerificationEmail")}
                      </Button>
                    }
                  >
                    {t("emailNotVerified")}
                  </Alert>
                )}
              <TextField
                  label={registerMode ? t("profileEmail") : t("usernameOrEmail")}
                  type={registerMode ? "email" : "text"}
                  value={email}
                  onChange={(e) => { setEmail(e.target.value); setFieldErrors((f) => ({ ...f, email: undefined })); }}
                  autoComplete={registerMode ? "email" : "username"}
                  autoFocus
                  error={Boolean(fieldErrors.email)}
                  helperText={fieldErrors.email}
                  fullWidth
                />
                <TextField
                  label={t("profileCurrentPassword")}
                  value={password}
                  onChange={(e) => { setPassword(e.target.value); setFieldErrors((f) => ({ ...f, password: undefined, confirmPassword: undefined })); }}
                  autoComplete={registerMode ? "new-password" : "current-password"}
                  type="password"
                  error={Boolean(fieldErrors.password)}
                  helperText={fieldErrors.password || (registerMode ? t("passwordTooShort") : undefined)}
                  fullWidth
                />
                {registerMode && (
                  <TextField
                    label={t("confirmPassword")}
                    value={confirmPassword}
                    onChange={(e) => { setConfirmPassword(e.target.value); setFieldErrors((f) => ({ ...f, confirmPassword: undefined })); }}
                    autoComplete="new-password"
                    type="password"
                    error={Boolean(fieldErrors.confirmPassword)}
                    helperText={fieldErrors.confirmPassword}
                    fullWidth
                  />
                )}

                {!registerMode && (
                  <Box sx={{ display: "flex", alignItems: { xs: "flex-start", sm: "center" }, justifyContent: "space-between", gap: 1, flexWrap: "wrap" }}>
                    <FormControlLabel
                      control={<Checkbox disableRipple checked={rememberMe} onChange={(e) => setRememberMe(e.target.checked)} />}
                      label={t("rememberMe")}
                    />
                    <Button
                      type="button"
                      variant="text"
                      size="small"
                      disableRipple
                      onClick={() => navigate(`/forgot-password${email.trim() ? `?email=${encodeURIComponent(email.trim())}` : ""}`)}
                      sx={{ px: 0, minWidth: 0, fontWeight: 700, alignSelf: { xs: "stretch", sm: "auto" } }}
                    >
                      {t("forgotPassword")}
                    </Button>
                  </Box>
                )}

                {!registerMode && (
                  <Typography variant="body2" sx={{ color: "text.secondary", mt: -0.5 }}>
                    {rememberMe ? t("rememberMeHelpPersistent") : t("rememberMeHelpSession")}
                  </Typography>
                )}

                {cfg?.turnstileEnabled && cfg.turnstileSiteKey ? (
                  <TurnstileWidget key={registerMode ? "register" : "login"} siteKey={cfg.turnstileSiteKey} action={registerMode ? "register" : "login"} onToken={setTurnstileToken} />
                ) : null}

                <Box sx={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 1, mt: 1, flexWrap: "wrap" }}>
                  {(allowReg || initialMode === "register") && (
                    <Button
                      type="button"
                      variant="text"
                      size="small"
                      disableRipple
                      disabled={loading}
                      onClick={() => { if (initialMode === "register") navigate("/login"); else setRegisterMode((v) => !v); setFieldErrors({}); }}
                      sx={{ px: 0, minWidth: 0, fontWeight: 700 }}
                    >
                      {registerMode ? t("backToLogin") : t("createAccount")}
                    </Button>
                  )}
                  <Button type="submit" variant="contained" disableRipple disabled={loading || (registerMode && cfg !== null && !allowReg) || Boolean(cfg?.turnstileEnabled && !turnstileToken)} sx={{ ml: "auto" }}>
                    {registerMode ? t("createAccount") : t("signInTitle")}
                  </Button>
                </Box>
            </Box>

            {!registerMode && (cfg?.googleEnabled || cfg?.microsoftEnabled) ? (
              <Box sx={{ mt: 2.5 }}>
                <Divider sx={{ mb: 2 }}>{t("or")}</Divider>
                <Box sx={{ display: "flex", flexDirection: "column", gap: 1.25 }}>
                  {cfg?.googleEnabled ? <GoogleAuthCard presentation="sign-in" onSignedIn={() => { navigate(nextPath, { replace: true }); }} /> : null}
                  {cfg?.microsoftEnabled ? <MicrosoftAuthCard presentation="sign-in" onSignedIn={() => { navigate(nextPath, { replace: true }); }} /> : null}
                </Box>
              </Box>
            ) : null}
          </>
        )}
      </Paper>
    </Box>
  );
}
