import React, { useState } from 'react';
import axios from "axios";
import { useNavigate } from "react-router-dom";
import { useForm } from 'react-hook-form';
import '../styles/Admin.css'
import { Modal, Button } from 'react-bootstrap';
import { toast } from 'react-toastify';
import {Link} from 'react-router-dom';


export default function EditUser({preloadedValues}) {
    let navigate = useNavigate();
    const [error, setError] = useState([]);

    const [formData, setFormData] = useState({});
    const [show, setShow] = useState(false);

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

    const {register, handleSubmit, formState: {errors} } = useForm({
        defaultValues: preloadedValues
 
   });

    const handleClose = (event) => {
        if(event.target.value === "true"){
            sendData(formData);
        }
        setShow(false)
    };


    const onSubmit = (data) => {
        if(data.provisionAccess === true && data.role.includes('admin')){
        // if(true){
                setShow(true);
            setFormData(data);
        } else {
          sendData(data);
        }
    };

    const sendData = (data) => {
            if(typeof data.role == "string"){
                data.role = [data.role]
            }
            axios.put(`/api/admin/user/`, data, {
            headers: {
                Authorization: 'Bearer ' + localStorage.getItem('accessToken')
            }
            }).then((response) => {
                successAlert();
                navigate("/admin/users");
            })
            .catch((error) => {
                setError(error.response.data.error ?? error.response.data.message ?? "There was a problem");

            });  
    }

    return (
        <>
        <div className="container border border-1">
        <h3>Edit User</h3>
        <span className="text-danger unstyled">{error}</span>
        <form onSubmit={handleSubmit(onSubmit)}>
            <div className="form-group ">
            <p className="text-danger">{errors.username?.message}</p>
            <label>Username:</label>
            <input 
            className="form-control col-3 mb-3" type="text" name="username" {...register ("username", {
                required: "username is required",
                minLength: {value: 3, message: "Username must be at least 3 characters"},
                maxLength: {value: 20, message: "Username cannot be more than 20 characters"} 
                })} 
               />
            
            <p className="text-danger">{errors.firstName?.message}</p>
            <label>First Name:</label>
            <input 
            className="form-control col-3 mb-3" type="text" name="firstName" {...register ("firstName", {
                required: "First name is required",
                minLength: {value: 1, message: "Name must be at least 1 character"},
                maxLength: {value: 50, message: "Name must be a maximum of 50 characters"} 
                })} 
                />

            <p className="text-danger">{errors.lastName?.message}</p>
            <label>Last Name:</label>
            <input 
            className="form-control col-3 mb-3" type="text" name="firstName" {...register ("lastName", {
                required: "Last name is required",
                minLength: {value: 1, message: "Name must be at least 1 character"},
                maxLength: {value: 50, message: "Name must be a maximum of 50 characters"} 
                })} 
                />

            <p className="text-danger">{errors.email?.message}</p>
            <label>Email:</label>
            <input 
            className="form-control col-3 mb-3" type="email" name="email" {...register ("email", {
                required: "Last name is required",
                minLength: {value: 3, message: "Email must be at least 1 character"},
                maxLength: {value: 50, message: "Email must be a maximum of 50 characters"} 
                })} 
                />

            
            <label>User Roles:</label>
            <select className = "form-select" name="role" {...register ("role", {
                required: "Role is required", 
            })}>
                <option value="user">user</option>
                <option value="admin">administrator</option>
            </select>

            <p className="text-danger">{errors.status?.message}</p>
            

            <Link to={"/admin/users"}><button className="btn btn-secondary green-btn m-2">Back to Users</button></Link>
            <button type="submit" className="btn btn-primary">Update User</button>
            </div>
        </form>
    </div>

    <Modal centered show={show} onHide={handleClose}>
        <Modal.Header closeButton value={false} onClick={handleClose}>
        <Modal.Title>Cancel User's Subscription</Modal.Title>
        </Modal.Header>
        <Modal.Body>Converting this user's role to administrator will cancel their active subscription. Are you sure you wish to proceed?</Modal.Body>
        <Modal.Footer>
            <Button value={false} variant="secondary" onClick={handleClose}>
                Not right now
            </Button>
            <Button value={true} variant="danger" onClick={handleClose}>
                Continue with Update
            </Button>
        </Modal.Footer>
    </Modal>
    </>
    )
}