import React, { useEffect, useRef, useState } from "react";
import { Box, Typography, Avatar, Button, Alert, TextField, Card } from "@mui/material";
import Typed from "typed.js";
import imageone from "../../images/kineticAdminPanelBg.png";
import logo from "../../images/kineticlogo1.png";

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

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 ForgotPassword: React.FC = () => {
  const [username, setUsername] = useState("");
  const [new_pwd, setNewPwd] = useState("");
  const [conf_new_pwd, setConfNewPwd] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [message, setMessage] = useState<string | null>(null); 
  const [loading, setLoading] = useState(false);

  const handleForgotPassword = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(null);
    setMessage(null); // Reset message before request
    setLoading(true);

    try {
      const response = await fetch(API_URL, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ username, new_pwd, conf_new_pwd }),
      });

      const data = await response.json(); 

      if (!response.ok) {
        throw new Error(data.message || "Invalid username or password.");
      }

      setMessage(data.message || "Password reset request sent to your superior"); 
    } 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>

        {/* Display success or error messages */}
        {message && <Alert severity="success">{message}</Alert>}
        {error && <Alert severity="error">{error}</Alert>}

        <Box component="form" sx={{ display: "flex", flexDirection: "column", gap: 2 }} onSubmit={handleForgotPassword}>
          <TextField
            label="Username"
            variant="outlined"
            fullWidth
            required
            value={username}
            onChange={(e) => setUsername(e.target.value)}
          />
          <TextField
            label="Enter New Password"
            type="password"
            variant="outlined"
            fullWidth
            required
            value={new_pwd}
            onChange={(e) => setNewPwd(e.target.value)}
          />
          <TextField
            label="Confirm New Password"
            type="password"
            variant="outlined"
            fullWidth
            required
            value={conf_new_pwd}
            onChange={(e) => setConfNewPwd(e.target.value)}
          />
          <Typography variant="body2" sx={{ textAlign: "right", mb: 1 }}>
            <a href="/login" style={{ color: "#61A143", textDecoration: "none" }}>
              Login
            </a>
          </Typography>
          <Button
            type="submit"
            variant="contained"
            fullWidth
            disabled={loading}
            sx={{
              mt: 2,
              color: "white",
              background: "#61A143",
              "&:hover": { background: "#4a8a3a" },
            }}
          >
            {loading ? "Processing..." : "Reset Password"}
          </Button>
        </Box>
      </Card>
    </Box>
  );
};

export default ForgotPassword;
