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

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

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

import { api, getApiErrorMessage } from "../api";
import { useToast } from "../toast";
import { useI18n } from "../i18n/I18nProvider";

export default function ResetPasswordPage() {
  const { toast } = useToast();
  const { t } = useI18n();
  const navigate = useNavigate();

  const [email, setEmail] = useState("");
  const [token, setToken] = useState("");
  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [fieldErrors, setFieldErrors] = useState<{ newPassword?: string; confirmPassword?: string }>({});

  useEffect(() => {
    const params = new URLSearchParams(window.location.search);
    setEmail(params.get("email") || "");
    setToken(params.get("token") || "");
  }, []);

  const missingResetInfo = !email || !token;

  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 }}>
          {t("resetPasswordTitle")}
        </Typography>
        <Typography sx={{ color: "text.secondary", mb: 2 }}>
          {t("resetPasswordBody")}
        </Typography>

        <Box
          component="form"
          onSubmit={(e) => {
            e.preventDefault();
            if (missingResetInfo) {
              toast(t("missingResetLinkInfo"), "error");
              return;
            }
            const errors: { newPassword?: string; confirmPassword?: string } = {};
            if (!newPassword || newPassword.length < 8) errors.newPassword = t("passwordTooShort");
            if (confirmPassword !== newPassword) errors.confirmPassword = t("passwordsDoNotMatch");
            setFieldErrors(errors);
            if (Object.keys(errors).length > 0) return;

            setLoading(true);
            api
              .post("/auth/reset-password", { email, token, newPassword })
              .then(() => {
                toast(t("passwordResetSuccess"), "success");
                navigate("/login", { replace: true });
              })
              .catch((e2: any) => {
                toast(getApiErrorMessage(e2, t("resetFailed")), "error");
              })
              .finally(() => setLoading(false));
          }}
          sx={{ display: "flex", flexDirection: "column", gap: 1.5 }}
        >
          {missingResetInfo ? <Alert severity="warning">{t("missingResetLinkInfo")}</Alert> : null}
          <TextField label={t("profileEmail")} type="email" value={email} onChange={(e) => setEmail(e.target.value)} disabled={!missingResetInfo} fullWidth />
          <TextField
            label={t("profileNewPassword")}
            type="password"
            value={newPassword}
            onChange={(e) => { setNewPassword(e.target.value); setFieldErrors((f) => ({ ...f, newPassword: undefined, confirmPassword: undefined })); }}
            autoComplete="new-password"
            error={Boolean(fieldErrors.newPassword)}
            helperText={fieldErrors.newPassword || t("passwordTooShort")}
            fullWidth
          />
          <TextField
            label={t("confirmPassword")}
            type="password"
            value={confirmPassword}
            onChange={(e) => { setConfirmPassword(e.target.value); setFieldErrors((f) => ({ ...f, confirmPassword: undefined })); }}
            autoComplete="new-password"
            error={Boolean(fieldErrors.confirmPassword)}
            helperText={fieldErrors.confirmPassword}
            fullWidth
          />

          <Box sx={{ display: "flex", justifyContent: "flex-end", gap: 1, mt: 1 }}>
            <Button type="button" variant="outlined" onClick={() => navigate("/login")} disabled={loading}>
              {t("backToLogin")}
            </Button>
            <Button type="submit" variant="contained" disabled={loading || missingResetInfo}>
              {t("updatePassword")}
            </Button>
          </Box>
        </Box>
      </Paper>
    </Box>
  );
}
