import React, {useCallback, useEffect, useMemo, useState} from "react";
import BreadcrumbComBS from "../breadcrumb/BreadcrumbComBS";
// import { useLocation } from "react-router-dom";
import { Form, Formik } from "formik";
import * as Yup from "yup";
import {useMutation, useQuery} from "@tanstack/react-query";
import getImage from "../../utils/getImage";
import {IoMdArrowDropdown} from "react-icons/io";
import {completeProfile, getCommonPractice} from '../../services/services';
import siteLinks from "../../links/siteLinks";
import {useLocation, useNavigate} from "react-router-dom";
import {updateUserDetails} from "../../store/UserDetails";
import {useDispatch} from "react-redux";


const validationSchema = Yup.object().shape({
    practice: Yup.string().required("Required"),
    specialization: Yup.string().when('practice', {
        is: (value) => typeof value === 'string' && value.trim().length > 0,
        then: (schema) => schema.required('Required'),
        otherwise: (schema) => schema,
    }),
    introduction: Yup.string().min(1, "Minimum 1 character").max(50, "Maximum 50 characters"),
    url_name: Yup.string().min(6, "Minimum 6 characters").max(16, "Maximum 16 characters").required("Required").matches(
    /^[a-zA-Z0-9]+$/, // Regex for alphanumeric characters
    'Must contain only alphanumeric characters' // Custom error message
    ),
})


export default function ProfileCompleteCom() {

    const dispatch = useDispatch()

    const navigate = useNavigate()

    const {state: {redirectLink}} = useLocation()

    const [practices, setPractices] = useState([])
    const [specialties, setSpecialties] = useState([])

    const [initialValues, setInitialValues] = useState({
        practice: '',
        specialization: '',
        introduction: '',
        url_name: ''
    })

    const handleUpdateSpecialties = (e) => {
        setInitialValues(prev => ({...prev, specialization: ''}))
        const specialtiesArr = practices.filter(item => item.practice == e.target.value)[0]?.specialties
        setSpecialties(specialtiesArr)
    }


    const mutation = useMutation({
        mutationFn: (fields) => {
            const {practice, specialization, url_name} = fields
            if (!practice || !specialization || !url_name) {
                throw new Error('Please Select both Practice, Specialization and Enter URL_Name')
            }
            return completeProfile(fields)
        },
        onError: () => {
            setTimeout(() => {
                mutation.reset()
            }, 4000)
        },
        onSuccess: (res) => {
            if (res.data.resultCode != '0') {
                throw({message: res?.data?.resultDescription})
            }
            dispatch(updateUserDetails({profile_completed: res?.data?.profile_completed}));
            setTimeout(() => {
                navigate(redirectLink)
            }, 2000)
            // console.log('res', res)
        }
    })

    const commonPractices = useMutation({ // FUNCTION TO GET COMMON PRACTICES
        mutationFn: (fields) => {
            return getCommonPractice(fields)
        },
        onError: () => {
            setPractices([])
        },
        onSuccess: (res) => {
            if (!res?.data) {
                return setPractices([])
            }
            let returnPractices = Object.entries(res?.data).filter(([key, value]) => typeof value == 'object')?.map(item => item[1])
            setPractices(returnPractices)
        }
    })

    const handleCompleteProfile = (values) => { // FUNCTION TO COMPLETE PROFILE
        let reqData = {
            token: localStorage.getItem('token'), // USER TOKEN
            uid: localStorage.getItem('uid'), // USER UID
            ...values
        }
        mutation.mutate(reqData)
    }

    useEffect(() => {
        let reqData = {
            token: localStorage.getItem('token'), // USER TOKEN
            uid: localStorage.getItem('uid') // USER UID
        }
        commonPractices.mutate(reqData)
    }, [])

    return <>

        <BreadcrumbComBS title='Tell us more about your practice.' paths={['Dashboard', 'Profile']}/>

        {commonPractices?.isFetching ?
            <>
                <div className="row">
                    <div className="col-12">
                        <p className='text-mute'>Loading...</p>
                    </div>
                </div>
            </>
            : commonPractices?.isError ?
                <div className="row">
                    <div className="col-12">
                        <p className='text-danger'>{commonPractices?.error?.message}</p>
                    </div>
                </div>
                :
                <div className="row pt-1">
                    <div className="col-md-6 m-b-30">
                        <div className="card card-statistics h-100 mb-0" style={{borderRadius: '10px'}}>
                            {/* <div className="card-header d-flex align-items-center justify-content-between">
                            <div className="card-heading">
                                <h4 className="card-title">My Product URLs</h4>
                            </div>
                        </div> */}
                            {/* <div style={{minHeight: '400px'}}></div> */}
                            <div className="card-body">
                                <div className='h-100 row flex-column'>
                                    {/* <div className="row"> */}
                                    <Formik
                                        initialValues={initialValues}
                                        validationSchema={validationSchema}
                                        onSubmit={handleCompleteProfile}
                                        enableReinitialize={true}
                                    >
                                        {(props) => {
                                        return (
                                            <Form className='mt-2'>
                                                <>
                                                    <div className="">
                                                        <div className="form-group position-relative">
                                                            <label className={`text-black fw-bold control-label`}>Practice : <span className="text-danger">{(props.errors.practice && props.touched.practice) && props.errors.practice}</span></label>
                                                            <div className="position-relative">
                                                                {/* <select onChange={props.handleChange} name='practice' value={props.values.practice} className="form-control">
                                                                    <option value=''>Select</option>
                                                                    {practices.map((practice, index)=>(
                                                                        <option key={index} value={practice.practice}>{practice.practice}</option>
                                                                    ))}
                                                                </select> */}
                                                                <select 
                                                                        onChange={(e) => {props.handleChange(e); props.setFieldValue('specialization', ''); handleUpdateSpecialties(e)}} 
                                                                        name='practice'
                                                                        value={props.values.practice} className="form-control">
                                                                    <option value=''>Select</option>
                                                                    {practices.map((practice, index) => (
                                                                        <option key={index}
                                                                                value={practice.practice}>{practice.practice}</option>
                                                                    ))}
                                                                </select>
                                                                <IoMdArrowDropdown className='position-absolute w-auto' style={{
                                                                    top: '50%',
                                                                    right: '2px',
                                                                    transform: 'translateY(-50%)'
                                                                }}/>
                                                            </div>
                                                        </div>
                                                    </div>

                                                    <div className="">
                                                        <div className="form-group">
                                                            <label className={`text-black fw-bold control-label`}>Your
                                                                Specialization : <span className="text-danger">{(props.errors.specialization && props.touched.specialization) && props.errors.specialization}</span></label>
                                                            <div className="position-relative">
                                                                <select onChange={props.handleChange} name='specialization'
                                                                        value={props.values.specialization}
                                                                        className="form-control">
                                                                    <option value=''>Select</option>
                                                                    {specialties.map((specialty, index) => (
                                                                        <option key={index} value={specialty}>{specialty}</option>
                                                                    ))}
                                                                </select>
                                                                <IoMdArrowDropdown className='position-absolute w-auto' style={{
                                                                    top: '50%',
                                                                    right: '2px',
                                                                    transform: 'translateY(-50%)'
                                                                }}/>
                                                            </div>
                                                        </div>
                                                    </div>

                                                    <div className="">
                                                        <div className="form-group position-relative">
                                                            <label className={`text-black fw-bold control-label`}>Other General Information : <span className="text-danger">{(props.errors.introduction && props.touched.introduction) && props.errors.introduction}</span></label>
                                                            <textarea name='introduction' rows={5} style={{resize: 'none'}}
                                                                    className="form-control" value={props.values.introduction}
                                                                    onChange={props.handleChange}/>
                                                        </div>
                                                    </div>

                                                    <div className="">
                                                        <div className="form-group position-relativ'e">
                                                            {/*<label className={`text-black fw-bold control-label`}>What we use this*/}
                                                            {/*    information for :</label>*/}
                                                            <div style={{
                                                                fontSize: '14px',
                                                                borderRadius: '10px',
                                                                backgroundColor: 'aliceblue',
                                                                fontWeight: 'bolder',
                                                                padding: '15px'
                                                            }}>
                                                                MERMS A.I. agents use the information supplied to help generate
                                                                useful entries for your product settings.
                                                            </div>
                                                        </div>
                                                    </div>

                                                    <div className="">
                                                        <div className="form-group position-relative">
                                                            <label className={`text-black fw-bold control-label`}>URL Name : <span className="text-danger">{(props.errors.url_name && props.touched.url_name) && props.errors.url_name}</span></label>
                                                            <div className="position-relative d-flex flex-column flex-xxl-row" style={{gap: '10px'}}>
                                                                {/* <select onChange={handlePracticeChange} name='url_name'
                                                                        value={initialValues.url_name} className="form-control">
                                                                    <option value=''>Select</option>
                                                                    {practices.map((practice, index) => (
                                                                        <option key={index}
                                                                                value={practice.practice}>{practice.practice}</option>
                                                                    ))}
                                                                </select>
                                                                <IoMdArrowDropdown className='position-absolute w-auto' style={{
                                                                    top: '50%',
                                                                    right: '2px',
                                                                    transform: 'translateY(-50%)'
                                                                }}/> */}
                                                                <input
                                                                    className="form-control"
                                                                    onChange={props.handleChange} name='url_name'
                                                                    value={props.values.url_name}
                                                                    minLength={6}
                                                                    maxLength={16}
                                                                />
                                                                <p className="border-radius-10 p-2 border border-warning"
                                                                style={{fontSize: "1.0rem"}}>We use the URL Name to form part of
                                                                    your default URL when we configure
                                                                    a new URL for your products. You can always change your product
                                                                    URL. <br/>
                                                                    <b>Example : <span style={{color: 'red'}}>url_name</span>.product.mermsemr.com
                                                                    </b>
                                                                </p>
                                                            </div>
                                                        </div>
                                                    </div>

                                                    {(mutation.isError || mutation.isSuccess) &&
                                                        <>
                                                            <div className="">
                                                                <p className={`${mutation.isSuccess ? 'text-success' : 'text-danger'}`}>{mutation.isSuccess ? 'Completed successfully, redirecting...' : mutation.error.message}</p>
                                                            </div>
                                                        </>
                                                    }

                                                    <div className="mt-auto text-end">
                                                        <button type='submit'
                                                                className="btn btn-primary text-uppercase">{mutation.isPending ? 'loading...' : 'Continue'}</button>
                                                    </div>
                                                </>
                                            </Form>
                                        );
                                        }}
                                    </Formik>
                                    {/* </div> */}
                                </div>
                            </div>
                        </div>
                    </div>
                    <div className="col-md-6 m-b-30">
                        <div className="text-center img-block left-column wow fadeInRight">
                            <img className="img-fluid" src={getImage('tell-us-more.png')} alt="content-image"/>
                        </div>
                    </div>
                </div>
        }
    </>;

}