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

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

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

import { api } from "../api";
import { setAuthToken, setRememberMePref, getRememberMePref } from "../auth";
import GoogleAuthCard from "../components/GoogleAuthCard";
import { useToast } from "../toast";
import { useI18n } from "../i18n/I18nProvider";

type AuthConfig = {
  requireAuth: boolean;
  googleEnabled: boolean;
  localEnabled: boolean;
  allowRegistration: boolean;
};

export default function LoginPage() {
  const { toast } = useToast();
  const { t } = useI18n();
  const navigate = useNavigate();
  const location = useLocation() as any;

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

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [rememberMe, setRememberMe] = useState(() => getRememberMePref());
  const [requestingReset, setRequestingReset] = useState(false);

  const nextPath = (location?.state?.from as string | undefined) ?? "/jobs";

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

  async function submit(mode: "login" | "register") {
    setLoading(true);
    try {
      const url = mode === "register" ? "/auth/register" : "/auth/login";
      const res = await api.post<{ accessToken: string; tokenType: string }>(url, { email, password });
      setRememberMePref(rememberMe);
      setAuthToken(res.data.accessToken, { remember: rememberMe });
      toast(t("signedIn"), "success");
      navigate(nextPath, { replace: true });
    } catch (e: any) {
      const msg = e?.response?.data || e?.message || t("loginFailed");
      toast(String(msg), "error");
    } finally {
      setLoading(false);
    }
  }

  async function requestPasswordReset() {
    if (!email.trim()) {
      toast(t("loginResetEmailRequired"), "error");
      return;
    }

    setRequestingReset(true);
    try {
      await api.post("/auth/request-password-reset", { email: email.trim() });
      toast(t("loginResetRequested"), "success");
    } catch (e: any) {
      const msg = e?.response?.data || e?.message || t("loginResetRequestFailed");
      toast(String(msg), "error");
    } finally {
      setRequestingReset(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: 3 }}>
        <Typography variant="h5" sx={{ fontWeight: 900, mb: 0.5 }}>
          {t("signInTitle")}
        </Typography>
        <Typography sx={{ color: "text.secondary", mb: 2 }}>
          {cfg?.requireAuth ? t("authRequired") : t("authOptional")}
        </Typography>

        <Tabs value={tab} onChange={(_, v) => setTab(v)} sx={{ mb: 2 }}>
          <Tab label={t("emailAndPassword")} />
          <Tab label={t("google")} />
        </Tabs>

        {tab === 0 && (
          <Box component="form" onSubmit={(e) => { e.preventDefault(); void submit("login"); }} sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}>
            <TextField label={t("profileEmail")} value={email} onChange={(e) => setEmail(e.target.value)} autoComplete="email" fullWidth />
            <TextField label={t("profileCurrentPassword")} value={password} onChange={(e) => setPassword(e.target.value)} autoComplete={allowReg ? "new-password" : "current-password"} type="password" fullWidth />
            <FormControlLabel
              control={<Checkbox checked={rememberMe} onChange={(e) => setRememberMe(e.target.checked)} />}
              label={t("rememberMe")}
            />

            <Box sx={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 1, flexWrap: "wrap", mt: 0.5 }}>
              <Button type="button" variant="text" onClick={() => void requestPasswordReset()} disabled={loading || requestingReset}>
                {requestingReset ? t("loginRequestingReset") : t("forgotPassword")}
              </Button>
              <Box sx={{ display: "flex", gap: 1, justifyContent: "flex-end" }}>
                {allowReg && (
                  <Button type="button" variant="outlined" disabled={loading} onClick={() => void submit("register")}>
                    {t("createAccount")}
                  </Button>
                )}
                <Button type="submit" variant="contained" disabled={loading}>
                  {t("signInTitle")}
                </Button>
              </Box>
            </Box>
          </Box>
        )}

        {tab === 1 && <GoogleAuthCard onSignedIn={() => { navigate(nextPath, { replace: true }); }} />}
      </Paper>
    </Box>
  );
}
