import React, { useEffect, useState } from 'react'
import { useDispatch } from 'react-redux'
import { useLocation, useNavigate, Link } 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"),
  password: Yup.string().required("password is required").min(6, 'must be upto 6 characters').max(12, 'must not exceed 12 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)
            // localStorage.setItem('room', room)
            const data = {jwt_token}
            dispatch(updateUserDetails({ ...data, ...user }));
          }
          navigate(RouteLinks.homePage, {state:{proceed:'true'}}) // later add redux to dispatch state
    }
  })

  // const handleLogin = () => {
  //   setLoading(true)
  //   const data = {name: 'dummy'}
  //   localStorage.setItem('token', 'token')
  //   dispatch(updateUserDetails({ ...data }));
  //   setTimeout(()=>{
  //     navigate(RouteLinks.homePage, {replace:true})
  //   },500)
  // }

  //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>

                    {/* social login */}
                    <div className='grid grid-cols-2 gap-4 text-sm'>
                      <div className='px-4 py-2 flex gap-2 items-center justify-center text-black-body font-medium border border-slate-300/50 rounded-md hover:text-primary hover:bg-sky-50 cursor-pointer'>
                        <Icons name='google' />
                        <span>Sign in with Google</span>
                      </div>
                      <div className='px-4 py-2 flex gap-2 items-center justify-center text-black-body font-medium border border-slate-300/50 rounded-md hover:text-primary hover:bg-sky-50 cursor-pointer'>
                        <Icons name='apple' />
                        <span>Sign in with Apple</span>
                      </div>
                    </div>

                    <div className='relative h-[1px] bg-slate-300/50'>
                      <p className='absolute left-1/2 -translate-x-1/2 top-1/2 -translate-y-1/2 bg-white p-4 text-12 text-slate-500'>Or with email</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>

                    {/* <p className='text-sm text-center font-medium text-slate-500'>Not yet a member? <span className='text-primary'>Sign Up</span></p> */}

                    <div className='flex justify-end gap-4 mt-6 text-[13px] font-medium'>
                      <Link className='text-primary' to=''>Terms</Link>
                      <Link className='text-primary' to=''>Plans</Link>
                      <Link className='text-primary' to=''>Contact Us</Link>
                    </div>


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