import React, { useEffect, useState } from 'react'
import { Form, Formik } from "formik";
import * as Yup from "yup";
import { useDispatch } from 'react-redux'

import { Link, useNavigate, useParams } from 'react-router-dom'
import siteLinks from '../../links/siteLinks'
import { useMutation } from '@tanstack/react-query';
import { completeRegistration, verifyEmail } from '../../services/services';
import { updateUserDetails } from '../../store/UserDetails'

import { IoMdArrowDropdown } from "react-icons/io";

const validationSchema = Yup.object().shape({
    country: Yup.string().required("Username is required"),
    username: Yup.string().min(3, "Minimum 3 characters")
      .max(50, "Maximum 50 characters")
      .required("Username is required"),
      password: Yup.string().required("Password is required"),
      confirmpassword: Yup.string().required("Confirm Password is required").oneOf([Yup.ref('password')], 'Passwords must match')
  })

  const initialValues = {
    username: '',
    password: '',
    country: '',
    confirmpassword: '',
  };

export default function CSignup() {

    const {jwt} = useParams()
    
    const dispatch = useDispatch()

    const navigate = useNavigate()

    const [user, setUser] = useState(null)

// API to verify email link
  const verifyLink = useMutation({
    mutationFn: (fields) => {
        return verifyEmail(fields)
    },
    onSuccess: (res) => {
        setUser(res.data)
    },
    // onError: (err) => {
    //     console.log('err', err)
    // }
  })

  const cSignup = useMutation({
    mutationFn: (fields) => {
        return completeRegistration(fields)
    },
    onSuccess: (res) => {
        if(res?.data?.resultCode != '0'){
            throw({message: res?.data?.resultDescription})
        }
        const {token, room, uid} = res?.data
        if(!token || !room){
            throw({message: 'something went wrong, try again!'})
        }
        localStorage.setItem('token', token)
        localStorage.setItem('room', room)
        localStorage.setItem('uid', uid)
        dispatch(updateUserDetails({ ...res?.data }));
        navigate(siteLinks.start, {replace: true}) // later add redux to dispatch state
    },
    // onError: (err) => {
    //     console.log('err', err)
    // }
  })
  
  const completeSignup = (values) => {
    let reqData = {
        country : values.country,    
        username: values.username,
        password: values.password,
        verify_link: jwt
    }
    cSignup.mutate(reqData)
  }

  useEffect(()=>{
    if(!jwt){
        return navigate(siteLinks.login, {replace: true})
    }
    verifyLink.mutate({verify_link: jwt})
  }, [])

  return (
    <div className="app">
        <div className="app-wrap">
            <div className="app-contant">
                <div className="vh-100 bg-white custom-bg">
                    <div className="container-fluid p-0">
                        <div className="row no-gutters justify-content-center">
                        <div className="col-11 col-sm-6 col-lg-5 col-xxl-4 align-self-center order-2 order-sm-1" style={{maxWidth: '520px'}}>
                            <div className="mt-5 d-flex">
                                <div className="bg-white register p-5">
                                    <h1 className="mb-2">{process.env.REACT_APP_PANEL_NAME}</h1>
                                    {/* <p>Welcome, Enter your password.</p> */}
                                    <div
                                    >
                                        <div className='mt-2'>
                                            <div className="row">
                                                {verifyLink.isPending ?
                                                    <div className='col-12'>
                                                        <div className="rounded-2 d-flex flex-column justify-content-center align-items-center" style={{height: '200px', backgroundColor: '#F2FAF7'}}>
                                                            <div className="col-12 d-flex flex-column justify-content-center align-items-center">
                                                                <p className='text-black'>loading...</p>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    : verifyLink.isSuccess ?
                                                        <div className='col-12'>
                                                            <Formik
                                                                initialValues={initialValues}
                                                                validationSchema={validationSchema}
                                                                onSubmit={completeSignup}
                                                            >
                                                                {(props) => {
                                                                return (
                                                                    <Form className='mt-2'>
                                                                        <div className="row">
                                                                            <>
                                                                                <div className="col-12">
                                                                                    <div className="form-group">
                                                                                        <label className={`text-black fw-bold control-label`}>Email: {user?.user?.email}</label>
                                                                                        {/* <input type="text" name='firstname' className="form-control" placeholder="First Name" value={props.values.firstname} onChange={props.handleChange} /> */}
                                                                                    </div>
                                                                                </div>
                                                                                <div className="col-12">
                                                                                    <div className="form-group" data-select2-id="7">
                                                                                        <label className={`text-black fw-bold control-label ${(props.errors.country && props.touched.country) && 'text-danger'}`}>Country*</label>
                                                                                        <div className='position-relative'>
                                                                                            <select className="js-basic-single form-control select2-hidden-accessible" name="country" data-select2-id="1" tabIndex="-1" aria-hidden="true" value={props.values.country} onChange={props.handleChange}>
                                                                                                <option value="" data-select2-id="3">Select</option>
                                                                                                {user?.country?.list && user?.country?.list?.map(item => (
                                                                                                    <option key={item.code} value={item.code} data-select2-id="3">{item?.description}</option>
                                                                                                ))}
                                                                                            </select>
                                                                                            <IoMdArrowDropdown className='position-absolute w-auto' style={{top: '50%', right: '2px', transform: 'translateY(-50%)'}} />
                                                                                        </div>
                                                                                    </div>
                                                                                </div>
                                                                                <div className="col-12">
                                                                                    <div className="form-group">
                                                                                        <label className={`text-black fw-bold control-label ${(props.errors.username && props.touched.username) && 'text-danger'}`}>Username*</label>
                                                                                        <input type="username" name='username' className="form-control" placeholder="Username" value={props.values.username} onChange={props.handleChange} />
                                                                                    </div>
                                                                                </div>
                                                                                <div className="col-12">
                                                                                    <div className="form-group">
                                                                                        <label className={`text-black fw-bold control-label ${(props.errors.password && props.touched.password) && 'text-danger'}`}>Password*</label>
                                                                                        <input type="password" name='password' className="form-control" placeholder="password" value={props.values.password} onChange={props.handleChange} />
                                                                                    </div>
                                                                                </div>
                                                                                <div className="col-12">
                                                                                    <div className="form-group">
                                                                                        <label className={`text-black fw-bold control-label`}>Confirm Password* <span className={`${(props.errors.confirmpassword && props.touched.confirmpassword) && 'text-danger'}`}>{(props.errors.confirmpassword && props.touched.confirmpassword) && props.errors.confirmpassword}</span></label>
                                                                                        <input type="password" name='confirmpassword' className="form-control" placeholder="confirmpassword" value={props.values.confirmpassword} onChange={props.handleChange} />
                                                                                    </div>
                                                                                </div>
                                                                                
                                                                                {/* <div className="col-12">
                                                                                    <div className="form-check">
                                                                                        <input name='isChecked' className="form-check-input" type="checkbox" id="gridCheck" value={props.values.isChecked} onChange={props.handleChange} />
                                                                                        <label className="form-check-label" htmlFor="gridCheck">
                                                                                            I accept terms & policy
                                                                                        </label>
                                                                                    </div>
                                                                                    <span className={`${(props.errors.isChecked && props.touched.isChecked) && 'text-danger'}`}>{props.errors.isChecked}</span>
                                                                                </div> */}

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

                                                                                <div className="col-12 mt-3 text-end">
                                                                                    <button type='submit' className="btn btn-primary text-uppercase">{cSignup.isPending ? 'loading...' : 'Continue'}</button>
                                                                                </div>
                                                                            </>
                                                                        </div>
                                                                    </Form>
                                                                );
                                                                }}
                                                            </Formik>
                                                        </div>
                                                    :
                                                        <div className='col-12'>
                                                            <div className="rounded-2 d-flex flex-column justify-content-center align-items-center" style={{height: '200px', backgroundColor: '#F2FAF7'}}>
                                                                <div className="col-12 d-flex flex-column justify-content-center align-items-center">
                                                                    <p className='text-danger'>{verifyLink?.error?.message}</p>
                                                                </div>
                                                            </div>
                                                        </div>
                                                }

                                                <div className="col-12 mt-3 text-center">
                                                    <Link to={siteLinks.signup} className='text-primary' style={{color: '#6FCAEF'}}>Need help with logging in or signing up?</Link>
                                                </div>
                                                
                                                <div className="col-12 mt-3 text-center">
                                                    <p>Read our Privacy Statement</p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        {/* <div className="custom-bg col-sm-6 col-xxl-9 col-lg-7 b-gradient o-hidden order-1 order-sm-2">
                            <div className="row align-items-center h-100">
                                <div className="col-7 mx-auto ">
                                    <img className="img-fluid" src={LoginImg} alt="" />
                                </div>
                            </div>
                        </div> */}
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
  )
}
