import React, { useRef, useState } from 'react'
import { Form, Formik } from "formik";
import * as Yup from "yup";
import { Modal } from "bootstrap";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { updateProfile } from "../../services/services";
import queryKeys from '../../services/queryKeys';
import { useDispatch } from 'react-redux';
import { updateUserDetails } from '../../store/UserDetails'

const profileValidationSchema = Yup.object().shape({
    firstname: Yup.string().required("firstname is required"),
    lastname: Yup.string().required("lastname is required"),
    email: Yup.string().required("email is required"),
    account_name: Yup.string().required("account name is required"),
    phone: Yup.string().required("phone is required"),
    full_address: Yup.string().required("full address is required"),
})

export default function ProfileForm({data}) {

    const dispatch = useDispatch()

    const modalRef = useRef(null)

    const queryClient = useQueryClient()
    
    const [intialData] = useState(data)

    const [infoToUpdate, setInfoToUpdate] = useState({})

    const dismissModal = () => {
        const body = document.querySelector('body')
        body.removeAttribute('style')
        // body.classList.toggle('modal-open')

        const modalBackdrop = document.querySelectorAll('.modal-backdrop')
        modalBackdrop.forEach(item => {
            if (item) {
                item.remove();
            }
        })
        
        const modal = Modal.getInstance(modalRef.current);
        modal && modal.hide();
    };

      // UPDATE PROFILE MUTATION
    const updateProfileMutation = useMutation({
        mutationFn: (fields) => {
            return updateProfile(fields)
        },
        onSuccess: (res) => {
            if(res.data.resultCode != '0'){
                throw({message: res?.data?.resultDescription ? res?.data?.resultDescription : 'An error occured'})
            }
            const account_name = res?.data?.personal_data?.account_name
            dispatch(updateUserDetails({ account_name }));
        },
        onSettled: ()=>{
            setTimeout(() => {
                dismissModal() //CLOSE MODAL HERE
                queryClient.refetchQueries({
                    queryKey: [...queryKeys.profile_data], // type: 'active', // exact: true,
                })
                updateProfileMutation.reset()
            }, 3000);
        }
    })
    

    const handleSetInfoToUpdate = (values, helpers) => {
        delete values.email
        delete values.country
        setInfoToUpdate(values)
        var modal = new Modal(document.getElementById('modal'));
        modal.show();
    }

    const proceed = () => {
        let reqData = {
            token: localStorage.getItem('token'), // USER TOKEN
            uid: localStorage.getItem('uid'), // USER UID
            ...infoToUpdate
        }
        updateProfileMutation.mutate(reqData)
    }

  return (
    <>
        <Formik
            initialValues={intialData}
            validationSchema={profileValidationSchema}
            onSubmit={handleSetInfoToUpdate}
        >
            {(props) => {
            return (
                <Form className=''>
                    <div className="form-row">
                        <div className="form-group col-md-12">
                            <label htmlFor="name1">First Name {(props.errors.firstname && props.touched.firstname) && <span className="text-danger">{props.errors.firstname}*</span>}</label>
                            <input type="text" className="form-control" name="firstname" value={props.values?.firstname} onChange={props.handleChange} />
                        </div>
                        <div className="form-group col-md-12">
                            <label htmlFor="name1">Last Name {(props.errors.lastname && props.touched.lastname) && <span className="text-danger">{props.errors.lastname}*</span>}</label>
                            <input type="text" className="form-control" name="lastname" value={props.values?.lastname} onChange={props.handleChange} />
                        </div>
                        <div className="form-group col-md-12">
                            <label htmlFor="name1">Account Name {(props.errors.account_name && props.touched.account_name) && <span className="text-danger">{props.errors.account_name}*</span>}</label>
                            <input type="text" className="form-control" name="account_name" value={props.values?.account_name} onChange={props.handleChange} />
                        </div>
                        <div className="form-group col-md-12">
                            <label htmlFor="phone1">Phone Number {(props.errors.phone && props.touched.phone) && <span className="text-danger">{props.errors.phone}*</span>}</label>
                            <input type="text" className="form-control" name="phone" value={props.values?.phone} onChange={props.handleChange} />
                        </div>
                        <div className="form-group col-md-12">
                            <label htmlFor="email1">Email {(props.errors.email && props.touched.email) && <span className="text-danger">{props.errors.email}*</span>}</label>
                            <input type="text" className="form-control" name="email" readOnly value={props.values?.email} onChange={props.handleChange} />
                        </div>
                    </div>
                    <div className="form-group">
                        <label htmlFor="add1">Address {(props.errors.full_address && props.touched.full_address) && <span className="text-danger">{props.errors.full_address}*</span>}</label>
                        <input type="text" className="form-control" name="full_address" value={props.values?.full_address} onChange={props.handleChange} />
                    </div>
                    <div style={{textAlign: "right"}}>
                        <button type="submit" className="btn btn-primary">Update Profile
                        </button>
                    </div>
                </Form>
            );
            }}
        </Formik>

        {/* Vertical Center Modal */}
        <div ref={modalRef} className="modal fade" id="modal" tabIndex="-1" role="dialog" aria-hidden="true">
            <div className="modal-dialog modal-dialog-centered" role="document">
                <div className="modal-content">
                    <div className="modal-header">
                        {/* <h5 className="modal-title" style={{fontSize: '18px'}} id="verticalCenterTitle">{'productTitle'}</h5> */}
                        <button type="button" className="close" data-bs-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div className="modal-body">
                        <h5 className="text-center" style={{fontSize: '18px'}}>Are you sure, you want to update?</h5>
                        {(updateProfileMutation.error || updateProfileMutation.isSuccess) && (
                        <div className="col-12">
                            <p className={`p-2 text-center ${updateProfileMutation.isSuccess ? 'text-success' : 'text-danger'}`}>
                                {updateProfileMutation.isSuccess ? 'Updated Successfully' : updateProfileMutation.error.message}
                            </p>
                        </div>
                        )}
                    </div>
                    <div className="modal-footer">
                        <button type="button" className="btn btn-danger" data-bs-dismiss="modal">Cancel</button>
                        <button type="button" className="btn btn-primary" disabled={updateProfileMutation.isSuccess} onClick={proceed}>{updateProfileMutation.isPending ? 'Updating...' : 'Update'}</button>
                    </div>
                </div>
            </div>
        </div>
        {/* END of Vertical Center Modal */}
    </>
  )
}
