import React, { useState } from "react";
import axios from "axios";
import { useNavigate } from "react-router-dom";
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as Yup from 'yup';
import 'react-toastify/dist/ReactToastify.css';
import { toast } from 'react-toastify';



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

  const validationSchema = Yup.object().shape({
    firstName: Yup.string().min(1).max(50).required("You must input a first name"),
    lastName: Yup.string().min(1).max(50).required("You must input a last name"),
    username: Yup.string().min(3).max(20).required("You must input a username"),
    email: Yup.string().min(3).max(50).required("You must input a email").email('Must be a valid email'),
    password: Yup.string().max(40, 'Password cannot exceed 40 characters'),
    confirmPassword: Yup.string().oneOf([Yup.ref('password'), null], 'Passwords must match')

  });

  const successAlert = () => {
    toast.success("Your profile information was updated!", {
      position: "top-center",
      autoClose: 2000,
      hideProgressBar: false,
      closeOnClick: true,
      pauseOnHover: false,
      draggable: true,
      progress: undefined,
    })
  };

  const { register, handleSubmit, formState } = useForm({
    defaultValues: {
      username: preloadedValues.username,
      email: preloadedValues.email,
      firstName: preloadedValues.firstName,
      lastName: preloadedValues.lastName,
      password: "",
      confirmPassword: ""
    },
    resolver: yupResolver(validationSchema)

  });
  const { errors } = formState;


  const onSubmit = (data) => {

    axios.put(`/api/profile`, data, {
      headers: {
        Authorization: 'Bearer ' + localStorage.getItem('accessToken')
      }
    }).then((response) => {
      successAlert();
      navigate("/account");
    })
      .catch((error) => {
        setError(error.response.data.error ?? error.response.data.message ?? "There was a problem");

      });
  };


  return (
    <div className="container full-vh">
      <div class="card m-5">
        <h5 class="card-header nav-bg">Edit Profile</h5>
        <div class="card-body">
          <form onSubmit={handleSubmit(onSubmit)}>
            <div className="form-group ">
              <p className="text-danger">{errors.username?.message}</p>
              <label>Username:</label>
              <p>{preloadedValues.username}</p>
              <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")}
              />
              <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")}
              />
              <p className="text-danger">{errors.lastName?.message}</p>
              <label>Last Name:</label>
              <input
                className="form-control col-3 mb-3" type="text" name="lastName" {...register("lastName")}
              />
              <p className="text-danger">{errors.password?.message}</p>
              <label>Password:</label>
              <input
                className="form-control col-3 mb-3" type="password" name="password" {...register("password")}
              />
              <p className="text-danger">{errors.confirmPassword?.message}</p>
              <label>Confirm Password:</label>
              <input
                className="form-control col-3 mb-3" type="password" name="confirmPassword" {...register("confirmPassword")}
              />
              <button type="submit" className="btn btn-primary">Update Profile</button>
              <span className="text-danger">{error}</span>
            </div>
          </form>
        </div>
      </div>
    </div>
  )
}

export default Profile