import { useState } from "react";
import { loginWithAppPassword, getToken, logout } from "../../auth";
import { useNavigate } from "react-router-dom"; // Import de useNavigate pour la redirection
import {
  Box,
  Button,
  Card,
  CardContent,
  TextField,
  Typography,
  Container,
  Avatar,
} from "@mui/material";
import LockOutlinedIcon from "@mui/icons-material/LockOutlined";

function TestLogin() {
  const [username, setUsername] = useState("");
  const [appPassword, setAppPassword] = useState("");
  const [token, setToken] = useState(getToken());
  const navigate = useNavigate(); // Hook pour la navigation

  const handleLogin = async (e) => {
    e.preventDefault();
    const newToken = await loginWithAppPassword(username, appPassword);
    if (newToken) {
      setToken(newToken);
    } else {
      alert("Échec de la connexion !");
    }
  };

  const handleLogout = () => {
    logout();
    setToken(null);
  };

  return (
    <Box
      sx={{
        backgroundImage: "url('https://source.unsplash.com/random/1600x900?technology')",
        backgroundSize: "cover",
        backgroundPosition: "center",
        minHeight: "100vh",
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
      }}
    >
      <Container maxWidth="xs">
        <Card
          sx={{
            padding: 4,
            boxShadow: 6,
            borderRadius: 3,
            textAlign: "center",
            backdropFilter: "blur(10px)",
            backgroundColor: "rgba(255, 255, 255, 0.8)",
          }}
        >
          <CardContent>
            <Avatar sx={{ margin: "auto", backgroundColor: "#0e467f" }}>
              <LockOutlinedIcon />
            </Avatar>
            <Typography variant="h5" sx={{ fontWeight: "bold", mt: 2 }}>
              {token ? "Bienvenue !" : "Connexion"}
            </Typography>

            {token ? (
              <>
                <Button
                  variant="contained"
                  color="primary"
                  onClick={() => navigate("/admin/dashboard")}
                  sx={{ mt: 3, width: "100%" }}
                >
                  Accéder au tableau de bord
                </Button>
                <Button
                  variant="contained"
                  color="error"
                  onClick={handleLogout}
                  sx={{ mt: 2, width: "100%" }}
                >
                  Déconnexion
                </Button>
              </>
            ) : (
              <form onSubmit={handleLogin}>
                <TextField
                  label="Nom d'utilisateur"
                  fullWidth
                  margin="normal"
                  variant="outlined"
                  value={username}
                  onChange={(e) => setUsername(e.target.value)}
                  required
                />
                <TextField
                  label="Mot de passe d'application"
                  fullWidth
                  margin="normal"
                  variant="outlined"
                  type="password"
                  value={appPassword}
                  onChange={(e) => setAppPassword(e.target.value)}
                  required
                />
                <Button
                  type="submit"
                  variant="contained"
                  color="primary"
                  sx={{ mt: 3, width: "100%" }}
                >
                  Se connecter
                </Button>
              </form>
            )}
          </CardContent>
        </Card>
      </Container>
    </Box>
  );
}

export default TestLogin;