import {Form, Formik} from "formik";
import * as Yup from "yup";
import {useMutation} from '@tanstack/react-query';
import {setExternalURL} from '../../../services/services';
import { useState } from "react";

const validationSchema = Yup.object().shape({
    url: Yup.string().required("URL is required").matches(/^https?:\/\/[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-]+\.[a-zA-Z]+/, 'Must be like: https://example.mysite.com'),
})

// const initialValues = {
//     url: '',
// };

const URLConfiguration = ({productData}) => {

    const [externalURLChanged, setExternalURLChanged] = useState(true)

    const initialValues = {
        url: productData?.external_url || '',
    };

    let defaultUrl = 'https://' + productData?.internal_url
    let externalUrl = productData?.external_url

     const handleExternalURLChanged = (e) => {
        if(e.target.value == externalUrl){
            setExternalURLChanged(true)
        }else{
            setExternalURLChanged(false)
        }
    }

    // API to set url
    const setURL = useMutation({
        mutationFn: (fields) => {
            return setExternalURL(fields)
        },
        onSuccess: (res) => {
            if (res.data.resultCode != '0') {
                // throw({message: res?.data?.resultDescription})
                throw({message: 'Something went wrong!'})
            }
        },
        onSettled: () => {
            setTimeout(() => {
                setURL.reset()
            }, 3000)
        }
        // onError: (err) => {
        //     console.log('err', err)
        // }
    })

    const handleSubmit = (values) => {
        let reqData = {
            token: localStorage.getItem('token'), // USER TOKEN
            uid: localStorage.getItem('uid'), // USER UID
            subscription_uid: productData?.subscription_uid,
            external_url: values.url
        }
        setURL.mutate(reqData)
    }

    return <>
        <div className="card card-statistics">
            <div className="card-header">
                <div className="card-heading">
                    <h4 className="card-title" style={{textTransform: 'none'}}>{defaultUrl}</h4>
                </div>
            </div>
            {/*<div className="card-body">*/}
            {/*    <div className="form-group">*/}
            {/*        /!*<label htmlFor="exampleInputEmail1">Email address</label>*!/*/}
            {/*        <input type="email" className="form-control"*/}
            {/*               aria-describedby="defaultUrlHelp" value={defaultUrl} readOnly={true} />*/}
            {/*    </div>*/}
            {/*</div>*/}
        </div>

        <Formik
            initialValues={initialValues}
            validationSchema={validationSchema}
            onSubmit={handleSubmit}
        >
            {(props) => {
                return (
                    <Form className='w-full'>
                        <div className="card card-statistics" style={{backgroundColor: '#b6e5ef'}}>
                            <div className="card-header">
                                <div className="card-heading">
                                    <h4 className="card-title" style={{textTransform: 'none'}}>Set your own URL</h4>
                                </div>
                            </div>
                            <div className="card-body">
                                <div className="form-group">
                                    <label htmlFor="exampleInputEmail1">Enter your full URL <span
                                        className={`${(props.errors.url && props.touched.url) && 'text-danger'}`}>{props.errors.url}</span></label>
                                    <input value={props.values.url} onChange={(e)=>{props.handleChange(e); handleExternalURLChanged(e)}} type="text"
                                           className="form-control" id="url" aria-describedby="url"
                                           placeholder="https://example.mysite.com"/>
                                </div>
                                <div style={{width: '100%', textAlign: 'right'}}>
                                    <button 
                                        type="submit" 
                                        disabled={setURL.isPending || externalURLChanged}
                                        className="btn btn-primary"
                                    >
                                        {setURL.isPending ? 'Loading...' : 'Submit'}
                                    </button>
                                </div>
                            </div>

                            {setURL.error &&
                                <div className="col-12">
                                    <p className='text-danger'>{setURL.error.message}</p>
                                </div>
                            }

                            {setURL.isSuccess &&
                                <div className="col-12">
                                    <p className='text-success'>{'Completed successfully'}</p>
                                </div>
                            }
                            <div style={{backgroundColor: '#94b8c0', borderRadius: '10px', padding: '10px'}}>
                                Final steps to configure your URL:<br/>
                                DNS:<br/>
                                DNS:<br/>
                                DNS:<br/>

                            </div>
                        </div>
                    </Form>
                );
            }}
        </Formik>

    </>
}

export default URLConfiguration