import React, { useEffect, useRef, useState } from "react";
import {
  Box,
  Typography,
  Avatar,
  Button,
  Divider,
  InputAdornment,
  TextField,
  Card,
  Alert,
} from "@mui/material";
import { AccountCircle } from "@mui/icons-material";
import GoogleIcon from "@mui/icons-material/Google";
import Typed from "typed.js";
import imageone from "../../images/kineticAdminPanelBg.png";
import logo from "../../images/kineticlogo1.png";
import { useNavigate } from "react-router-dom";

const API_URL = "https://kineticgreen-backend.navigolabs.com/user/login";

const AnimatedText: React.FC = () => {
  const typedRef = useRef<HTMLSpanElement | null>(null);
  const typedInstance = useRef<Typed | null>(null);

  useEffect(() => {
    if (typedRef.current) {
      typedInstance.current = new Typed(typedRef.current, {
        strings: ["Trucks", "Automobiles", "Diagnostics"],
        typeSpeed: 50,
        backSpeed: 30,
        loop: true,
      });
    }
    return () => typedInstance.current?.destroy();
  }, []);

  return (
    <div
      style={{
        textAlign: "center",
        marginTop: "10px",
        fontWeight: "bold",
        fontSize: "2rem",
        color: "#61A143",
      }}
    >
      <span ref={typedRef} />
    </div>
  );
};

const LoginPage: React.FC = () => {
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  useEffect(() => {
    const token = localStorage.getItem("token");
    if (token) {
      const decodedToken = JSON.parse(atob(token.split(".")[1]));
      if (
        decodedToken.role?.role_name === "KineticAdmin" ||
        decodedToken.role?.role_name === "SuperAdmin"
      ) {
        window.location.href = "/home";
      }
    }
  }, []);

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setLoading(true);

    try {
      const response = await fetch(API_URL, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ username, password }),
      });
      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("Invalid username or password.");
      }

      const data = await response.json();
      const { token } = data;

      if (!token) {
        throw new Error("Invalid server response.");
      }

      const decodedToken = JSON.parse(atob(token.split(".")[1]));
      console.log("Decoded Token:", decodedToken);

      localStorage.setItem("decodedToken", JSON.stringify(decodedToken));

      const hasKineticAdminPermissions =
        decodedToken.role?.permissions.includes("viewKineticAdmin") ||
        decodedToken.role?.permissions.includes("manageKineticAdmin");
      const hasSuperAdminPermissions =
        decodedToken.role?.permissions.includes("viewsuperAdmin") ||
        decodedToken.role?.permissions.includes("managesuperAdmin");

      if (hasKineticAdminPermissions || hasSuperAdminPermissions) {
        localStorage.setItem("token", token);
        localStorage.setItem("user", JSON.stringify(decodedToken));
        alert("Login successful!");
        window.location.href = "/home";
      } else {
        throw new Error("You do not have permission to access this system.");
      }
    } catch (error: any) {
      setError(error.message);
    } finally {
      setLoading(false);
    }
  };
  return (
    <Box
      sx={{
        justifyContent: "center",
        alignItems: "center",
        height: "100vh",
        display: "flex",
        backgroundImage: `url(${imageone})`,
        backgroundPosition: "left center",
        backgroundSize: "100%",
        backgroundRepeat: "no-repeat",
        backgroundColor: "rgba(0, 0, 0, 0.72)",
      }}
    >
      <Card
        sx={{
          width: "400px",
          padding: 4,
          boxShadow: 6,
          borderRadius: 8,
          backgroundColor: "#ffffff",
          backdropFilter: "blur(5px)",
          border: "1px solid rgba(255, 255, 255, 0.3)",
        }}
      >
        <Box sx={{ mb: 3, textAlign: "center" }}>
          <Avatar
            sx={{ bgcolor: "#61A143", width: 56, height: 56, margin: "0 auto" }}
          >
            <img
              src={logo}
              alt="Logo"
              style={{ width: "40px", height: "40px", borderRadius: "50%" }}
            />
          </Avatar>
          <Typography variant="h5" sx={{ mt: 2, fontWeight: "bold" }}>
            KINETIC
          </Typography>
          <AnimatedText />
        </Box>

        {error && <Alert severity="error">{error}</Alert>}

        <Box
          component="form"
          sx={{ display: "flex", flexDirection: "column", gap: 2 }}
          onSubmit={handleLogin}
        >
          <TextField
            label="Username"
            variant="outlined"
            fullWidth
            required
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            // InputProps={{
            //   endAdornment: (
            //     <InputAdornment position="start">
            //       <AccountCircle />
            //     </InputAdornment>
            //   ),
            // }}
          />
          <TextField
            label="Password"
            type="password"
            variant="outlined"
            fullWidth
            required
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />
          <Typography variant="body2" sx={{ textAlign: "right", mb: 1 }}>
            <span
              onClick={() => navigate("/forgotpassword")}
              style={{
                color: "#61A143",
                textDecoration: "none",
                cursor: "pointer",
              }}
            >
              Forgot Password?
            </span>
          </Typography>
          <Button
            type="submit"
            variant="contained"
            fullWidth
            disabled={loading}
            sx={{
              mt: 2,
              color: "white",
              background: "#61A143",
              "&:hover": { background: "#4a8a3a" },
            }}
          >
            {loading ? "Logging in..." : "Login"}
          </Button>
        </Box>

        {/* <Divider sx={{ my: 2 }}>OR</Divider>

        <Button
          variant="outlined"
          fullWidth
          startIcon={<GoogleIcon />}
          sx={{
            textTransform: "none",
            color: "#61A143",
            borderColor: "#61A143",
            "&:hover": { backgroundColor: "#61A143", borderColor: "#4a8a3a", color: "white" },
          }}
          onClick={() => alert("Google Login not implemented yet")}
        >
          Login with Google
        </Button> */}
      </Card>
    </Box>
  );
};

export default LoginPage;
