import React, { useState } from "react";
import {
  TextField,
  Button,
  Typography,
  Snackbar,
  Alert,
  Box,
  Grid,
} from "@mui/material";
import loginpageimg from "../../images/loginPageimg.jpg";
import { useNavigate } from "react-router-dom";

const UserLogin: React.FC = () => {
  const [useremail, setUserEmail] = useState("");
  const [password, setPassword] = useState("");
  const [responseMessage, setResponseMessage] = useState<string | null>(null);
  const [severity, setSeverity] = useState<"success" | "error">("success");
  const [error, setError] = useState("");

  const navigate = useNavigate();

  const handleLogin = async (event: React.FormEvent) => {
    event.preventDefault();

    const credentials = {
      useremail,
      password,
    };

    try {
      const response = await fetch("http://localhost:3000/users/login", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(credentials),
      });
      if (response.ok) {
        const jsonData = await response.json();
        const decodedToken = JSON.parse(atob(jsonData.token.split(".")[1]));
        console.log("Decoded Token:", decodedToken);

        localStorage.setItem("decodedToken", JSON.stringify(decodedToken));
        localStorage.setItem("token", jsonData.token);
        // localStorage.setItem("user", JSON.stringify(jsonData));
        navigate("../home");
      } else {
        setError("Invalid username or password");
      }
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const data = await response.json();

      if (data.token) {
        localStorage.setItem("token", data.token);
      }

      setResponseMessage(data.message || "Login successful");
      setSeverity("success");
      navigate("/home");
    } catch (error) {
      setResponseMessage("Error logging in");
      setSeverity("error");
    }
  };

  const handleCloseSnackbar = () => {
    setResponseMessage(null);
  };

  return (
    <Box
      sx={{
        position: "fixed",
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundImage: `url(${loginpageimg})`,
        backgroundSize: "cover",
        backgroundPosition: "center",
        backgroundRepeat: "no-repeat",
        overflow: "hidden",
      }}
    >
      <Grid
        container
        alignItems="center"
        justifyContent="center"
        sx={{
          height: "100%",
        }}
      >
        <Grid
          item
          xs={12}
          sm={8}
          md={4}
          sx={{
            backgroundColor: "rgba(255, 255, 255, 0.8)",
            padding: 4,
            borderRadius: 2,
          }}
        >
          <Typography variant="h5" gutterBottom>
            Loginnssss
          </Typography>
          <form onSubmit={handleLogin}>
            <TextField
              fullWidth
              label="Email"
              value={useremail}
              onChange={(e) => setUserEmail(e.target.value)}
              margin="normal"
              required
            />
            <TextField
              fullWidth
              label="Password"
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              margin="normal"
              required
            />
            <Button
              type="submit"
              fullWidth
              variant="contained"
              color="primary"
              sx={{ mt: 2 }}
            >
              Login
            </Button>
          </form>
        </Grid>
      </Grid>

      <Snackbar
        open={!!responseMessage}
        autoHideDuration={6000}
        onClose={handleCloseSnackbar}
      >
        <Alert
          onClose={handleCloseSnackbar}
          severity={severity}
          sx={{ width: "100%" }}
        >
          {responseMessage}
        </Alert>
      </Snackbar>
    </Box>
  );
};

export default UserLogin;
