import React, { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import { useDispatch } from 'react-redux'

import LoginImg from '../../assets/bg/login.svg'

import { Link, useNavigate } from 'react-router-dom'
import siteLinks from '../../links/siteLinks'
import { loginUser } from '../../services/services'
import { updateUserDetails } from '../../store/UserDetails'

export default function Login() {

  const dispatch = useDispatch()

  const navigate = useNavigate()

  const [fields, setFields] = useState({
    username: '',
    password: ''
  })

  const handleChange = ({target:{name, value}}) => {
    setFields(prev => ({...prev, [name]:value}))
  }

  const login = useMutation({
    mutationFn: (fields) => {
        if(!fields.username || !fields.password){
            throw new Error('Please provide all fields marked *')
        }
        return loginUser('panel/auth/login', fields)
    },
    onError: (error) => {
        console.log(error)
    },
      onSuccess: (res) => {
        const {token} = res?.data?.data
        if(token){
            localStorage.setItem('token', token)
            const data = {token}
            dispatch(updateUserDetails({ ...data }));
            navigate('/dash') // later add redux to dispatch state
        }
    }
  })

  return (
    <div className="app">
        <div className="app-wrap">
            <div className="app-contant">
                <div className="bg-white">
                    <div className="container-fluid p-0">
                        <div className="row no-gutters">
                            <div className="col-sm-6 col-lg-5 col-xxl-3  align-self-center order-2 order-sm-1">
                                <div className="d-flex align-items-center h-100-vh">
                                    <div className="login p-50">
                                        <h1 className="mb-2">MERMS Panel</h1>
                                        <p>Welcome back, please login to your account.</p>
                                        <form className="mt-3 mt-sm-5">
                                            <div className="row">
                                                <div className="col-12">
                                                    <div className="form-group">
                                                        <label className="control-label">User Name*</label>
                                                        <input name='username' value={fields.username} onChange={handleChange} type="text" className="form-control" placeholder="Username" />
                                                    </div>
                                                </div>
                                                <div className="col-12">
                                                    <div className="form-group">
                                                        <label className="control-label">Password*</label>
                                                        <input name='password' value={fields.password} onChange={handleChange} type="password" className="form-control" placeholder="Password" />
                                                    </div>
                                                </div>
                                                <div className="col-12">
                                                    <div className="d-block d-sm-flex  align-items-center">
                                                        <div className="form-check">
                                                            <input className="form-check-input" type="checkbox" id="gridCheck" />
                                                            <label className="form-check-label" htmlFor="gridCheck">
                                                                Remember Me
                                                            </label>
                                                        </div>
                                                        <Link to={siteLinks.forgetpwd} className="ml-auto">Forgot Password ?</Link>
                                                    </div>
                                                </div>
                                                {login.error &&
                                                <>
                                                 <div className="col-12  mt-3">
                                                    <p className='text-danger'>{login.error.message}</p>
                                                </div>
                                                </>
                                                }
                                                <div className="col-12 mt-3 text-end">
                                                    <button type='button' onClick={()=>{login.mutate(fields)}} className="btn btn-primary text-uppercase">{login.isPending ? 'loading...' : 'Sign In'}</button>
                                                </div>
                                                <div className="col-12  mt-3">
                                                    <p>Don't have an account ?<Link to={siteLinks.signup}> Sign Up</Link></p>
                                                </div>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                            <div className="col-sm-6 col-xxl-9 col-lg-7 bg-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>
  )
}
