import LockOutlinedIcon from "@mui/icons-material/LockOutlined";
import {
  Alert,
  Avatar,
  Box,
  Button,
  Container,
  Paper,
  TextField,
  Typography
} from "@mui/material";
import { useMutation } from "@tanstack/react-query";
import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { useEffect, useMemo } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { z } from "zod";
import { useTranslation } from "react-i18next";

import { useAuth } from "../contexts/AuthContext";

type FormValues = {
  username: string;
  password: string;
};

export default function LoginPage() {
  const { login, authEnabled, isAuthenticated } = useAuth();
  const navigate = useNavigate();
  const location = useLocation();
  const { t } = useTranslation();

  const schema = useMemo(
    () =>
      z.object({
        username: z.string().min(1, t("login.usernameRequired")),
        password: z.string().min(1, t("login.passwordRequired"))
      }),
    [t]
  );

  const {
    handleSubmit,
    register,
    formState: { errors }
  } = useForm<FormValues>({
    resolver: zodResolver(schema)
  });

  const mutation = useMutation({
    mutationFn: ({ username, password }: FormValues) => login(username, password),
    onSuccess: () => {
      const redirectTo = (location.state as { from?: Location })?.from?.pathname ?? "/dashboard";
      navigate(redirectTo, { replace: true });
    }
  });

  useEffect(() => {
    if (!authEnabled || isAuthenticated) {
      navigate("/dashboard", { replace: true });
    }
  }, [authEnabled, isAuthenticated, navigate]);

  return (
    <Container component="main" maxWidth="xs">
      <Box
        sx={{
          marginTop: 12,
          display: "flex",
          flexDirection: "column",
          alignItems: "center"
        }}
      >
        <Paper elevation={3} sx={{ p: 4, borderRadius: 4, width: "100%" }}>
          <Box display="flex" flexDirection="column" alignItems="center" mb={2}>
            <Avatar sx={{ m: 1, bgcolor: "primary.main" }}>
              <LockOutlinedIcon />
            </Avatar>
            <Typography component="h1" variant="h5" fontWeight={600}>
              {t("login.title")}
            </Typography>
            <Typography variant="body2" color="text.secondary">
              {t("login.welcome")}
            </Typography>
          </Box>

          {mutation.isError && (
            <Alert severity="error" sx={{ mb: 2 }}>
              {(mutation.error as Error).message || t("login.error")}
            </Alert>
          )}

          <Box component="form" onSubmit={handleSubmit((values) => mutation.mutate(values))}>
            <TextField
              margin="normal"
              fullWidth
              label={t("login.username")}
              autoComplete="username"
              autoFocus
              {...register("username")}
              error={Boolean(errors.username)}
              helperText={errors.username?.message}
            />
            <TextField
              margin="normal"
              fullWidth
              label={t("login.password")}
              type="password"
              autoComplete="current-password"
              {...register("password")}
              error={Boolean(errors.password)}
              helperText={errors.password?.message}
            />
            <Button
              type="submit"
              fullWidth
              variant="contained"
              sx={{ mt: 3, mb: 2 }}
              disabled={mutation.isPending}
            >
              {mutation.isPending ? t("login.checking") : t("login.submit")}
            </Button>
            {!authEnabled && (
              <Alert severity="info">{t("login.disabled")}</Alert>
            )}
          </Box>
        </Paper>
      </Box>
    </Container>
  );
}
