import {useState} from 'react'
import {useDispatch} from 'react-redux'
import {useNavigate} from 'react-router-dom'
import {useMutation} from '@tanstack/react-query'
import {Formik, Form} from 'formik'
import * as Yup from "yup";

import InputText from '../InputText'
import {updateUserDetails} from "../../store/UserDetails";
import {loginUser} from '../../services/siteServices'

import RouteLinks from '../../RouteLinks'
// import Icons from '../Icons'


const initialValues = {
    username: "",
    password: "",
};

// To get the validation schema
const validationSchema = Yup.object().shape({
    username: Yup.string().required("username is required").min(6, 'must be upto 6 characters').max(25, 'must not exceed 25 characters'),
    password: Yup.string().required("password is required").min(6, 'must be upto 6 characters').max(25, 'must not exceed 25 characters'),
});

export default function LoginCom() {

    const dispatch = useDispatch()
    const navigate = useNavigate()

    const [loading, setLoading] = useState(false)

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

    //FUNCTION TO HANDLE LOGIN
    const handleSubmit = (values, helper) => {
        login.mutate(values)
        // handleLogin()
    };

    return (
        <>
            <div
                className={`h-screen bg-sky-300 flex flex-col items-center justify-center bg-[url('./assets/login-bg.jpg')] bg-cover bg-center bg-no-repeat`}>
                <div
                    className='p-4 sm:p-8 w-full max-w-7xl mx-auto grid gap-8 grid-cols-1 md:grid-cols-3 lg:grid-cols-2'>
                    <div className='col-span-1 md:col-span-2 lg:col-span-1 h-full'>
                        <Formik
                            initialValues={initialValues}
                            validationSchema={validationSchema}
                            onSubmit={handleSubmit}
                        >
                            {(props) => (
                                <Form>
                                    <div
                                        className='flex flex-col gap-8 w-full bg-white rounded-xl p-16 sm:px-20 sm:py-16 shadow'>
                                        <div className='w-full flex flex-col gap-1 items-center'>
                                            <h1 className='text-2xl md:text-3xl font-bold text-black-body'>Sign In</h1>
                                            <p className='text-sm font-medium text-slate-500'>Welcome back, please login
                                                to your account</p>
                                        </div>

                                        <div className='flex flex-col gap-6'>
                                            <div className='relative text-input flex flex-col gap-2'>
                                                <p className='absolute left-0 -top-4 text-red-500 text-10'>
                                                    {(props.errors.username && props.touched.username) ? props.errors.username : ''}
                                                </p>
                                                <InputText
                                                    id='username'
                                                    placeholder='Username'
                                                    name='username'
                                                    value={props.values.username}
                                                    handleChange={props.handleChange}
                                                />
                                            </div>
                                            <div className='relative text-input flex flex-col gap-2 mb-10'>
                                                <p className='absolute left-0 -top-4 text-red-500 text-10'>
                                                    {(props.errors.password && props.touched.password) ? props.errors.password : ''}
                                                </p>
                                                <InputText
                                                    id='password'
                                                    placeholder='Password'
                                                    name='password'
                                                    type='password'
                                                    value={props.values.password}
                                                    handleChange={props.handleChange}
                                                />
                                                {/* <p className='text-sm text-end font-medium text-primary'>Forget password ?</p> */}
                                            </div>
                                            <div className='h-10 mb-10'>
                                                <button type='submit' disabled={login.isPending}
                                                        className='w-full h-full bg-primary text-white font-bold rounded-md'>{login.isPending || loading ? 'loading...' : 'Login'}</button>
                                            </div>

                                            {login.error &&
                                                <>
                                                    <div className="w-full text-center">
                                                        <p className='text-red-500 text-sm'>{login.error.message}</p>
                                                    </div>
                                                </>
                                            }
                                        </div>

                                        <div className='flex justify-end gap-4 mt-6 text-[18px] font-medium'>
                                            MERMS Integrated Support System
                                        </div>
                                    </div>
                                </Form>
                            )}
                        </Formik>
                    </div>
                </div>
            </div>
        </>
    )
}
