import {useEffect, useState} from 'react';
import Checkbox from '../../Components/common/Checkbox';
import InputError from '../../Components/common/InputError';
import InputLabel from '../../Components/common/InputLabel';
import PrimaryButton from '../../Components/common/PrimaryButton';
import TextInput from '../../Components/common/TextInput';
import {Link, useNavigate} from "react-router-dom";
import bgTexture from '../../assets/images/LoginPageTexture.png'
import * as yup from "yup"
import LoadingTemplate from "../../Components/common/LoadingTemplate";
import LoginApi from "../../api/LoginApi";

export default function Login() {

    const [loading, setLoading] = useState(false) // api loading state
    const [notProvided, setNotProvided] = useState(true) // required field state
    const [errors, setErrors] = useState([]) // fields errors state
    const [data, setData] = useState({
        email: '',
        password: ''
    }) // email password states
    const navigate = useNavigate();

    // check required fields and keep button disabled
    useEffect(() => {
        setNotProvided(data.email.length === 0 || data.password.length === 0)
    }, [data])

    // validation function for email
    const validation = async () => {
        const dataSchema = yup.object().shape({
            data:  yup.object().shape({
                email: yup.string().required('لطفا ایمیل خود را وارد کنید').email("ایمیل صحیح نمی باشد"),
                password: yup.string().min(8, 'رمز عبور حداقل 8 رقم می باشد').required('لطفا رمز خود را وارد کنید')
            })
        })

        try {
            await dataSchema.validate({data}, {abortEarly: false})
            setErrors([])
            return true
        } catch (error) {
            setErrors(error.errors)
            return false
        }
    }

    const handleLogin = async (e) => {
        e.preventDefault()
        const valid = await validation()
        if (valid) {
            setLoading(true)
            const response = await LoginApi(data.email, data.password)
            if (response?.status === 200) {
                setErrors([])
                navigate('/panel')
            } else if (response?.status === 422) {
                setErrors(['!ایمیل یا رمز عبور اشتباه می باشد'])
            } else {
                setErrors(['خطایی رخ داده است، لطفا با پشتیبانی تماس بگیرید'])
            }
            setLoading(false)
        }
    };

    const handleChange = (e) => {
        setData({
            ...data,
            [e.target.name]: e.target.value
        })
    }

    return (
        <div className="min-h-screen flex flex-col sm:justify-center items-center pt-6 sm:pt-0 bg-gray-100">
            <img alt={''} src={bgTexture} className={'min-h-screen h-[100vh] w-[100%] absolute object-fit'}/>
            <div className="w-full sm:max-w-md mt-6 px-6 py-4 bg-white shadow-sm overflow-hidden sm:rounded-xl z-10">
                <h1 className={"text-2xl text-black text-right my-3 font-[dana] font-black"}>.خوش آمدید</h1>
                <h2 className={"text-sm font-normal font-[Vazirmatn] text-gray-400 text-right mb-8"}>لطفا اطلاعات خود را وارد کنید</h2>
                <form>
                    <div>
                        <InputLabel className={"justify-end font-[Vazirmatn] font-normal text-gray-400 mb-2 mr-2 "} htmlFor="email" value="ایمیل" />

                        <TextInput
                            readOnly={loading}
                            id="email"
                            type="text"
                            name="email"
                            value={data.email}
                            className="mt-1 py-3 font-[Vazirmatn] flex text-right w-full placeholder:text-sm placeholder-gray-400 border-gray-200 "
                            placeholder={'ایمیل خود را وارد کنید'}
                            autoComplete="email"
                            isFocused={true}
                            onChange={handleChange}
                        />
                    </div>

                    <div className="mt-4">
                        <InputLabel className={"justify-end font-normal font-[Vazirmatn] text-gray-400 mb-2 mr-2 "} htmlFor="password" value="رمز عبور" />

                        <TextInput
                            readOnly={loading}
                            id="password"
                            type="password"
                            name="password"
                            value={data.password}
                            className="mt-1 py-3 font-[Vazirmatn] text-gray-500 font-black tracking-[0.3rem] flex text-right w-full border-gray-200 "
                            autoComplete="current-password"
                            onChange={handleChange}
                        />
                    </div>

                    <div className="flex flex-row-reverse justify-between mt-4 mb-5">
                        <label className="flex items-center">
                            <span className="mr-2 text-sm font-[Vazirmatn] text-gray-400">مرا به خاطر بسپار</span>
                            <Checkbox
                                name="remember"
                            />
                        </label>
                        <Link className={"text-sm font-[Vazirmatn]"} to={'reset'}>رمز عبور خود را فراموش کرده اید؟</Link>
                    </div>
                    {
                        errors.map((error, index) => (
                            <InputError key={index} message={error} className="mt-3 font-[dana]" />
                        ))
                    }
                    <div className="flex items-center justify-center mt-4">
                        <LoadingTemplate loading={loading} marginLeft={'-12px'}>
                            <PrimaryButton
                                className="mt-5 mb-7 font-[Vazirmatn] w-full justify-center py-3 pb-4 text-md"
                                disabled={loading || notProvided}
                                onClick={handleLogin}
                            >
                                ورود
                            </PrimaryButton>
                        </LoadingTemplate>
                    </div>
                </form>
            </div>
        </div>
    );
}
