import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useRouter } from 'next/router';
import { setPageTitle, loadUserTheme } from '../../store/themeConfigSlice';
import BlankLayout from '@/components/Layouts/BlankLayout';
import Link from 'next/link';
import Image from 'next/image';
import RedirectHome from '@/components/RedirectHome';
import Swal from 'sweetalert2';
import { useGoogleLogin } from '@react-oauth/google';
import { IRootState } from '@/store';
import { setUser } from '@/store/userConfigSlice';
import { coloredToast } from '@/lib/toast';

const LoginCover = () => {
    const dispatch = useDispatch();
    useEffect(() => {
        dispatch(setPageTitle('Login Dashboard'));
    }, []);
    const router = useRouter();

    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [progressLogin, setProgressLogin] = useState(false);

    const submitForm = async (e: any) => {
        e.preventDefault();
        setProgressLogin(true);
        if (!email) {
            // show toast if email not filled
            coloredToast('warning', 'Email must be filled');
            setProgressLogin(false);
            return;
        }
        if (!password) {
            // show toast if password not filled
            coloredToast('warning', 'Password must be filled');
            setProgressLogin(false);
            return;
        }

        try {
            const api_url = process.env.API_URL;
            const payload = {
                email,
                password,
                role: 'administrator',
            };

            // login credential
            const response = await fetch(`${api_url}api/users/login`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(payload),
                credentials: 'include', // Include this option
            });
            const res = await response.json();

            // condition if login rejected
            if (!response.ok) {
                coloredToast('warning', res.message);
                setProgressLogin(false);
                return;
            }
            dispatch(setUser(res.user.id));
            dispatch(loadUserTheme(String(res.user.id)));
        } catch (error) {
            coloredToast('danger', 'something went wrong');
        }
        setProgressLogin(false);
        router.push('/');
    };

    const loginByGoogle = useGoogleLogin({
        onSuccess: async (tokenResponse) => {
            console.log(tokenResponse);
            const access_token = tokenResponse.access_token;
            const response = await fetch('https://www.googleapis.com/oauth2/v3/userinfo', { method: 'GET', headers: { Authorization: 'Bearer ' + access_token } });
            const userInfo = await response.json();
            if (userInfo) {
                const { email, name } = userInfo;
                if (email && name) {
                    try {
                        const payload = {
                            email,
                            name,
                            role: 'administrator',
                        };
                        const api_url = process.env.API_URL;
                        const responseLoginGoogle = await fetch(`${api_url}api/users/auth/google`, {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            credentials: 'include', // Include this option
                            body: JSON.stringify(payload),
                        });
                        const res = await responseLoginGoogle.json();

                        if (!responseLoginGoogle.ok) {
                            coloredToast('warning', res.message);
                            return;
                        }
                        coloredToast('success', 'login by google successfully');
                        dispatch(setUser(res.user.id));
                        dispatch(loadUserTheme(String(res.user.id)));
                        router.push('/');
                    } catch (error) {
                        coloredToast('danger', 'something went wrong');
                    }
                } else {
                    coloredToast('warning', 'login failed');
                }
            }
        },
        onError: (errorResponse) => {
            console.log(errorResponse);
            coloredToast('warning', 'login failed');
        },
    });

    return (
        <RedirectHome>
            <div>
                <div className="absolute inset-0">
                    <Image src="/assets/images/auth/bg-gradient.png" width={500} height={500} alt="image" className="h-full w-full object-cover" />
                </div>
                <div className="relative flex min-h-screen items-center justify-center bg-[url(/assets/images/auth/map.png)] bg-cover bg-center bg-no-repeat px-6 py-10 dark:bg-[#060818] sm:px-16">
                    <Image width={500} height={500} src="/assets/images/auth/coming-soon-object1.png" alt="image" className="absolute left-0 top-1/2 h-full max-h-[893px] -translate-y-1/2" />
                    <Image width={500} height={500} src="/assets/images/auth/coming-soon-object2.png" alt="image" className="absolute left-24 top-0 h-40 md:left-[30%]" />
                    <Image width={500} height={500} src="/assets/images/auth/coming-soon-object3.png" alt="image" className="absolute right-0 top-0 h-[300px]" />
                    <Image width={500} height={500} src="/assets/images/auth/polygon-object.svg" alt="image" className="absolute bottom-0 end-[28%]" />
                    <div className="relative flex w-full max-w-[1502px] flex-col justify-between overflow-hidden rounded-md bg-white/60 backdrop-blur-lg dark:bg-black/50 lg:min-h-[758px] lg:flex-row lg:gap-10 xl:gap-0">
                        <div className="relative hidden w-full items-center justify-center bg-[linear-gradient(225deg,rgba(239,18,98,1)_0%,rgba(67,97,238,1)_100%)] p-5 lg:inline-flex lg:max-w-[835px] xl:-ms-28 ltr:xl:skew-x-[14deg] rtl:xl:skew-x-[-14deg]">
                            <div className="absolute inset-y-0 w-8 from-primary/10 via-transparent to-transparent ltr:-right-10 ltr:bg-gradient-to-r rtl:-left-10 rtl:bg-gradient-to-l xl:w-16 ltr:xl:-right-20 rtl:xl:-left-20"></div>
                            <div className="ltr:xl:-skew-x-[14deg] rtl:xl:skew-x-[14deg]">
                                <Link href="/" className="ms-10 block w-48 lg:w-72">
                                    <Image width={500} height={500} src="/assets/images/auth/Aurum Logo Light.png" alt="Logo" className="w-full" />
                                </Link>
                                <div className="mt-24 hidden w-full max-w-[430px] lg:block">
                                    <Image width={500} height={500} src="/assets/images/auth/login.svg" alt="Cover Image" className="w-full" />
                                </div>
                            </div>
                        </div>
                        <div className="relative flex w-full flex-col items-center justify-center gap-6 px-4 pb-16 pt-6 sm:px-6 lg:max-w-[667px]">
                            <div className="flex w-full max-w-[440px] items-center gap-2 lg:absolute lg:end-6 lg:top-6 lg:max-w-full">
                                <Link href="/" className="block w-8 lg:hidden">
                                    <Image width={500} height={500} src="/assets/images/logo-au-black.png" alt="Logo" className="mx-auto w-10" />
                                </Link>
                            </div>
                            <div className="w-full max-w-[440px] lg:mt-16">
                                <div className="mb-10">
                                    <h1 className="text-3xl font-extrabold uppercase !leading-snug text-primary md:text-4xl">Sign in</h1>
                                    <p className="text-base font-bold leading-normal text-white-dark">Enter your email and password to login</p>
                                </div>
                                <form className="space-y-5 dark:text-white" onSubmit={submitForm}>
                                    <div>
                                        <label htmlFor="Email">Email</label>
                                        <div className="relative text-white-dark">
                                            <input
                                                id="Email"
                                                type="email"
                                                placeholder="Enter Email"
                                                className="form-input ps-10 placeholder:text-white-dark"
                                                onChange={(event) => setEmail(event.target.value)}
                                                value={email}
                                            />
                                            <span className="absolute start-4 top-1/2 -translate-y-1/2">
                                                <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
                                                    <path
                                                        opacity="0.5"
                                                        d="M10.65 2.25H7.35C4.23873 2.25 2.6831 2.25 1.71655 3.23851C0.75 4.22703 0.75 5.81802 0.75 9C0.75 12.182 0.75 13.773 1.71655 14.7615C2.6831 15.75 4.23873 15.75 7.35 15.75H10.65C13.7613 15.75 15.3169 15.75 16.2835 14.7615C17.25 13.773 17.25 12.182 17.25 9C17.25 5.81802 17.25 4.22703 16.2835 3.23851C15.3169 2.25 13.7613 2.25 10.65 2.25Z"
                                                        fill="currentColor"
                                                    />
                                                    <path
                                                        d="M14.3465 6.02574C14.609 5.80698 14.6445 5.41681 14.4257 5.15429C14.207 4.89177 13.8168 4.8563 13.5543 5.07507L11.7732 6.55931C11.0035 7.20072 10.4691 7.6446 10.018 7.93476C9.58125 8.21564 9.28509 8.30993 9.00041 8.30993C8.71572 8.30993 8.41956 8.21564 7.98284 7.93476C7.53168 7.6446 6.9973 7.20072 6.22761 6.55931L4.44652 5.07507C4.184 4.8563 3.79384 4.89177 3.57507 5.15429C3.3563 5.41681 3.39177 5.80698 3.65429 6.02574L5.4664 7.53583C6.19764 8.14522 6.79033 8.63914 7.31343 8.97558C7.85834 9.32604 8.38902 9.54743 9.00041 9.54743C9.6118 9.54743 10.1425 9.32604 10.6874 8.97558C11.2105 8.63914 11.8032 8.14522 12.5344 7.53582L14.3465 6.02574Z"
                                                        fill="currentColor"
                                                    />
                                                </svg>
                                            </span>
                                        </div>
                                    </div>
                                    <div>
                                        <label htmlFor="Password">Password</label>
                                        <div className="relative text-white-dark">
                                            <input
                                                id="Password"
                                                type="password"
                                                placeholder="Enter Password"
                                                className="form-input ps-10 placeholder:text-white-dark"
                                                value={password}
                                                onChange={(event) => setPassword(event.target.value)}
                                            />
                                            <span className="absolute start-4 top-1/2 -translate-y-1/2">
                                                <svg width="18" height="18" viewBox="0 0 18 18" fill="none">
                                                    <path
                                                        opacity="0.5"
                                                        d="M1.5 12C1.5 9.87868 1.5 8.81802 2.15901 8.15901C2.81802 7.5 3.87868 7.5 6 7.5H12C14.1213 7.5 15.182 7.5 15.841 8.15901C16.5 8.81802 16.5 9.87868 16.5 12C16.5 14.1213 16.5 15.182 15.841 15.841C15.182 16.5 14.1213 16.5 12 16.5H6C3.87868 16.5 2.81802 16.5 2.15901 15.841C1.5 15.182 1.5 14.1213 1.5 12Z"
                                                        fill="currentColor"
                                                    />
                                                    <path
                                                        d="M6 12.75C6.41421 12.75 6.75 12.4142 6.75 12C6.75 11.5858 6.41421 11.25 6 11.25C5.58579 11.25 5.25 11.5858 5.25 12C5.25 12.4142 5.58579 12.75 6 12.75Z"
                                                        fill="currentColor"
                                                    />
                                                    <path
                                                        d="M9 12.75C9.41421 12.75 9.75 12.4142 9.75 12C9.75 11.5858 9.41421 11.25 9 11.25C8.58579 11.25 8.25 11.5858 8.25 12C8.25 12.4142 8.58579 12.75 9 12.75Z"
                                                        fill="currentColor"
                                                    />
                                                    <path
                                                        d="M12.75 12C12.75 12.4142 12.4142 12.75 12 12.75C11.5858 12.75 11.25 12.4142 11.25 12C11.25 11.5858 11.5858 11.25 12 11.25C12.4142 11.25 12.75 11.5858 12.75 12Z"
                                                        fill="currentColor"
                                                    />
                                                    <path
                                                        d="M5.0625 6C5.0625 3.82538 6.82538 2.0625 9 2.0625C11.1746 2.0625 12.9375 3.82538 12.9375 6V7.50268C13.363 7.50665 13.7351 7.51651 14.0625 7.54096V6C14.0625 3.20406 11.7959 0.9375 9 0.9375C6.20406 0.9375 3.9375 3.20406 3.9375 6V7.54096C4.26488 7.51651 4.63698 7.50665 5.0625 7.50268V6Z"
                                                        fill="currentColor"
                                                    />
                                                </svg>
                                            </span>
                                        </div>
                                    </div>
                                    <button type="submit" disabled={progressLogin} className="btn btn-gradient !mt-6 w-full border-0 uppercase shadow-[0_10px_20px_-10px_rgba(67,97,238,0.44)]">
                                        {progressLogin ? (
                                            <>
                                                <svg
                                                    viewBox="0 0 24 24"
                                                    width="24"
                                                    height="24"
                                                    stroke="currentColor"
                                                    strokeWidth="1.5"
                                                    fill="none"
                                                    strokeLinecap="round"
                                                    strokeLinejoin="round"
                                                    className="h-5 w-5 animate-spin text-white-dark"
                                                >
                                                    <line x1="12" y1="2" x2="12" y2="6"></line>
                                                    <line x1="12" y1="18" x2="12" y2="22"></line>
                                                    <line x1="4.93" y1="4.93" x2="7.76" y2="7.76"></line>
                                                    <line x1="16.24" y1="16.24" x2="19.07" y2="19.07"></line>
                                                    <line x1="2" y1="12" x2="6" y2="12"></line>
                                                    <line x1="18" y1="12" x2="22" y2="12"></line>
                                                    <line x1="4.93" y1="19.07" x2="7.76" y2="16.24"></line>
                                                    <line x1="16.24" y1="7.76" x2="19.07" y2="4.93"></line>
                                                </svg>
                                            </>
                                        ) : (
                                            'Sign in'
                                        )}
                                    </button>
                                </form>

                                {/* Google login disabled — API returns 403
                                <div className="relative my-7 text-center md:mb-9">
                                    <span className="absolute inset-x-0 top-1/2 h-px w-full -translate-y-1/2 bg-white-light dark:bg-white-dark"></span>
                                    <span className="relative bg-white px-2 font-bold uppercase text-white-dark dark:bg-dark dark:text-white-light">or</span>
                                </div>
                                <div className="mb-10 md:mb-[60px]">
                                    <ul className="flex justify-center gap-3.5">
                                        <li>
                                            <div
                                                onClick={() => loginByGoogle()}
                                                className="inline-flex h-8 w-8 cursor-pointer items-center justify-center rounded-full p-0 transition hover:scale-110"
                                                style={{ background: 'linear-gradient(135deg, rgba(239, 18, 98, 1) 0%, rgba(67, 97, 238, 1) 100%)' }}
                                            >
                                                <svg width="14" height="14" viewBox="0 0 14 14" fill="none">
                                                    <path
                                                        fillRule="evenodd"
                                                        clipRule="evenodd"
                                                        d="M13.8512 7.15912C13.8512 6.66275 13.8066 6.18548 13.7239 5.72729H7.13116V8.43503H10.8984C10.7362 9.31003 10.243 10.0514 9.50162 10.5478V12.3041H11.7639C13.0875 11.0855 13.8512 9.29094 13.8512 7.15912Z"
                                                        fill="white"
                                                    />
                                                </svg>
                                            </div>
                                        </li>
                                    </ul>
                                </div>
                                */}
                                <div className="mb-10 md:mb-[60px]" />
                                <div className="text-center dark:text-white">
                                    Don&apos;t have an account ?&nbsp;
                                    <Link href="/auth/register" className="uppercase text-primary underline transition hover:text-black dark:hover:text-white">
                                        SIGN UP
                                    </Link>
                                </div>
                            </div>
                            <p className="absolute bottom-6 w-full text-center dark:text-white">© {new Date().getFullYear()}.AURUM LAB All Rights Reserved.</p>
                        </div>
                    </div>
                </div>
            </div>
        </RedirectHome>
    );
};
LoginCover.getLayout = (page: any) => {
    return <BlankLayout>{page}</BlankLayout>;
};
export default LoginCover;
