import React, { useEffect, useState } from "react";
import {useParams} from 'react-router-dom';
import axios from "axios";
import EditUser from './EditUser';

export default function EditUserHelper() {
    let { id } = useParams();
    const [error, setError] = useState('');
    const [data, setData] = useState(null);

    useEffect(() => {
        axios.get(`/api/admin/user/${id}`, {
        headers: {
            Authorization: 'Bearer ' + localStorage.getItem('accessToken')
        }
    }).then((response) => {
            let newData = response.data;
            newData.role = newData.roles.map(role => {
                return parseRole(role);
            })
            setData(newData);
        })
        .catch((error) => {
            if(error.response.data.message) {
                setError(error.response.data.message);
            } else {
                setError("An internal error occurred. Please go back")
            }
        });
    }, [id]);


    return data ? <EditUser preloadedValues={data}/> : ({error}? <span className="text-danger">{error}</span> : <div>Loading...</div>)
    

    function parseRole(role){
        switch(role.id){
            case 3:
                return "admin";
            case 2:
                return "mod";
            case 1:
                return "user";
            default:
                return null;
        }
    }
}

 