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 { updateLinks } from "../../services/services";
import queryKeys from '../../services/queryKeys';


const linksValidationSchema = Yup.object().shape({
    facebook_url: Yup.string().matches(/^https:\/\/.+/,"URL must start with https://"),
    twitter_url: Yup.string().matches(/^https:\/\/.+/,"URL must start with https://"),
    blogger_url: Yup.string().matches(/^https:\/\/.+/,"URL must start with https://"),
    google_url: Yup.string().matches(/^https:\/\/.+/,"URL must start with https://"),
    linked_url: Yup.string().matches(/^https:\/\/.+/,"URL must start with https://"),
    website_url: Yup.string().matches(/^https:\/\/.+/,"URL must start with https://"),
})

export default function LinksForm({data}) {
    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 LINKS MUTATION
    const updateLinksMutation = useMutation({
        mutationFn: (fields) => {
            return updateLinks(fields)
        },
        onSuccess: (res) => {
            if(res.data.resultCode != '0'){
                throw({message: res?.data?.resultDescription ? res?.data?.resultDescription : 'En error occured'})
            }
        },
        onSettled: ()=>{
            setTimeout(() => {
                dismissModal() //CLOSE MODAL HERE
                queryClient.refetchQueries({
                    queryKey: [...queryKeys.profile_data], // type: 'active', // exact: true,
                })
                updateLinksMutation.reset()
            }, 3000);
        }
    })
    

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

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

  return (
    <>
        <Formik
            initialValues={intialData}
            validationSchema={linksValidationSchema}
            onSubmit={handleSetInfoToUpdate}
        >
            {(props) => {
            return (
                <Form className=''>            
                    <div className="form-group">
                        <label htmlFor="fb">Facebook URL: {(props.errors.facebook_url && props.touched.facebook_url) && <span className="text-danger">{props.errors.facebook_url}</span>}</label>
                        <input type="text" className="form-control" name="facebook_url" value={props.values?.facebook_url} onChange={props.handleChange} />
                    </div>
                    <div className="form-group">
                        <label htmlFor="tr">Twitter URL: {(props.errors.twitter_url && props.touched.twitter_url) && <span className="text-danger">{props.errors.twitter_url}</span>}</label>
                        <input type="text" className="form-control" name="twitter_url" value={props.values?.twitter_url} onChange={props.handleChange} />
                    </div>

                    <div className="form-group">
                        <label htmlFor="br">Blogger URL: {(props.errors.blogger_url && props.touched.blogger_url) && <span className="text-danger">{props.errors.blogger_url}</span>}</label>
                        <input type="text" className="form-control" name="blogger_url" value={props.values?.blogger_url} onChange={props.handleChange} />
                    </div>

                    <div className="form-group">
                        <label htmlFor="go">Google+ URL: {(props.errors.google_url && props.touched.google_url) && <span className="text-danger">{props.errors.google_url}</span>}</label>
                        <input type="text" className="form-control" name="google_url" value={props.values?.google_url} onChange={props.handleChange} />
                    </div>

                    <div className="form-group">
                        <label htmlFor="li">LinkedIn URL: {(props.errors.linked_url && props.touched.linked_url) && <span className="text-danger">{props.errors.linked_url}</span>}</label>
                        <input type="text" className="form-control" name="linked_url" value={props.values?.linked_url} onChange={props.handleChange} />
                    </div>

                    <div className="form-group">
                        <label htmlFor="we">Website URL: {(props.errors.website_url && props.touched.website_url) && <span className="text-danger">{props.errors.website_url}</span>}</label>
                        <input type="text" className="form-control" name="website_url" value={props.values?.website_url} onChange={props.handleChange} />
                    </div>
                    <div style={{textAlign: "right"}}>
                        <button type="submit" className="btn btn-primary">Update Links
                        </button>
                    </div>
                </Form>
            );
            }}
        </Formik>

        {/* Vertical Center Modal */}
        <div ref={modalRef} className="modal fade" id="modal_links" 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>
                        {(updateLinksMutation.error || updateLinksMutation.isSuccess) && (
                        <div className="col-12">
                            <p className={`p-2 text-center ${updateLinksMutation.isSuccess ? 'text-success' : 'text-danger'}`}>
                                {updateLinksMutation.isSuccess ? 'Updated Successfully' : updateLinksMutation.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={updateLinksMutation.isSuccess} onClick={proceed}>{updateLinksMutation.isPending ? 'Updating...' : 'Update'}</button>
                    </div>
                </div>
            </div>
        </div>
        {/* END of Vertical Center Modal */}
    </>
  )
}
