import axios from "axios";
import { useNavigate } from 'react-router-dom';
import { useEffect, useState } from "react";
import { useParams } from 'react-router-dom';
import React from 'react';
import Button from '@mui/material/Button';
import {Link} from 'react-router-dom';
import 'react-toastify/dist/ReactToastify.css';
import { toast } from 'react-toastify';

function DeleteUser() {
    let navigate = useNavigate();
    let { id } = useParams();
    const [user, setUser] = useState({});
    const [error, setError] = useState([]);

    const successAlert = () => {
        toast.success("User has been deleted!", {
            position: "top-center",
            autoClose: 2000,
            hideProgressBar: false,
            closeOnClick: true,
            pauseOnHover: false,
            draggable: true,
            progress: undefined,
        });
    }

    useEffect(() => {
        axios.get(`/api/admin/user/${id}`, {
        headers: {
            Authorization: 'Bearer ' + localStorage.getItem('accessToken')
        }
    }).then((response) => {
            console.log(response.data)
            setUser(response.data);
        })
        .catch((error) => {
            setError(error.response.data.error ?? error.response.data.message ?? "There was a problem");
        });
    }, [id]);

    const deleteUser = (id) => {
        axios.delete(`/api/admin/user/${id}`, {
        headers: {
            Authorization: 'Bearer ' + localStorage.getItem('accessToken')
        }
    }).then((response) => {
            successAlert();
            console.log(response.data);
            navigate("/admin/users");
        })
        .catch((error) => {
            setError(error.response.data.error ?? error.response.data.message ?? "There was a problem");
        });

    };

  return (
    <div className="container">
                    <span className="text-danger list-unstyled">{error}</span>
<div className="card">
  <div className="card-body">
    <h5 className="card-title">Are you sure you want to delete this user?</h5>
    <h6 className="card-subtitle mb-2 text-muted">Username: {user.username}</h6>
    <h6 className="card-subtitle mb-2 text-muted">Email: {user.email}</h6>
    <h6 className="card-subtitle mb-2 text-muted">First Name: {user.firstName}</h6>
    <h6 className="card-subtitle mb-2 text-muted">Last Name: {user.lastName}</h6>
    <Link to={"/admin/users"}><button className="btn btn-secondary green-btn m-2">Back to Users</button></Link>
    <Button className="bg-danger text-white" onClick={() => { deleteUser(id) }}>Delete</Button>
  </div>
</div>
</div>
  )
}

export default DeleteUser