"use client";

import { setToken } from "@/utils/get-token";
import axios from 'axios';
import { Link } from 'react-router-dom';
import { FormEvent, useState } from 'react';

import { Bomb, Eye, EyeClosed, Loader } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Checkbox } from '@/components/ui/checkbox';
import { Button } from '@/components/ui/button';

import { useMutation } from '@tanstack/react-query';
import { useLanguage } from '@/store/language-context';
import { useToast } from '@/hooks/use-toast';

const Login = () => {
    const { URL } = useLanguage();
    const { t } = useTranslation();
    const { toast } = useToast();

    const [data, setData] = useState({
        email: '',
        password: ''
    });
    const [showPassword, setShowPassword] = useState(false);

    const loginFnc = useMutation({
        mutationKey: ['user-profile'],
        mutationFn: async (e: FormEvent<HTMLFormElement>) => {
            e.preventDefault();
            const response = await axios.post(`${URL}/login`, {
                email: data.email,
                password: data.password,
            });
            if (response.status !== 200) throw new Error(t('custom.incorrect'))
            return response.data;
        },

        onSuccess: (response) => {
            toast({
                variant: 'success',
                title: (
                    <p>
                        🎉 {t('custom.done')}
                    </p>
                ),
                description: t('custom.done-desc')
            });
            setToken(response?.data?.token);
            localStorage.setItem("user", JSON.stringify(response?.data));
            localStorage.setItem("isLoggedIn", "true");
            window.history.back();
        },

        onError: () => {
            toast({
                variant: "destructive",
                title: (
                    <div className='flex items-center gap-2'>
                        <Bomb size={19} />
                        <p>
                            {t('custom.failed')}
                        </p>
                    </div>
                ),
                description: t('custom.err')
            });
        }
    });

    return (
        <section className='grid place-items-center lg:min-h-dvh w-full mt-5'>
            <section className='grid place-items-center w-full'>
                <div className='text-center my-8'>
                    <p className='text-3xl text-secondary-tw'>
                        {t('hello')}
                    </p>
                    <p className='text-2xl text-primary-tw'>
                        {t('routes.login')}
                    </p>
                </div>
                <form className='w-full space-y-4' onSubmit={(e) => loginFnc.mutate(e)}>
                    <div className='space-y-1 w-full'>
                        <div className='inline-flex gap-2 items-center'>
                            <Label htmlFor='email' className='text-gray-500 text-base'>{t('contact.email')}</Label>
                            {(loginFnc.error as any)?.response?.data?.message?.toLowerCase()?.includes('email not')
                                &&
                                <>
                                    {
                                        (loginFnc.error as any)?.response?.data?.message?.toLowerCase()?.includes('email not') ?
                                            <span className='text-red-600 text-sm'>
                                                {t('register.no-email-err')}
                                            </span>
                                            :
                                            <span className='text-red-600 text-sm'>
                                                {t('register.invalid')}
                                            </span>
                                    }
                                </>
                            }
                        </div>
                        <Input
                            id='email'
                            type='email'
                            placeholder={t('footer.enter-email')}
                            value={data.email ?? ''}
                            onChange={(e) => setData(prev => ({ ...prev, email: e.target.value }))}
                            className='w-full focus:ring-secondary-tw text-common-text bg-[#F5F5F5]'
                            aria-invalid={loginFnc.isError}
                            required
                        />
                    </div>
                    <div className='space-y-1 w-full relative'>
                        <div className='inline-flex gap-2 items-center'>
                            <Label htmlFor='password' className='text-gray-500 text-base'>{t('contact.password')}</Label>
                            {(loginFnc.error as any)?.response?.data?.message?.includes('password')
                                &&
                                <span className='text-red-600 text-sm'>
                                    {t('register.invalid')}
                                </span>
                            }
                        </div>
                        <Input
                            id='password'
                            type={showPassword ? 'text' : 'password'}
                            placeholder={t('footer.enter-pass')}
                            value={data.password ?? ''}
                            onChange={(e) => setData(prev => ({ ...prev, password: e.target.value }))}
                            className='w-full focus:ring-secondary-tw text-common-text'
                            aria-invalid={loginFnc.isError}
                            required
                        />
                        <Button
                            type='button'
                            className='absolute top-[25px] h-9 end-1 bg-gray-200 transition-all'
                            variant='outline'
                            onClick={() => setShowPassword((prev: boolean) => !prev)}>
                            {showPassword ? <Eye /> : <EyeClosed />}
                        </Button>
                    </div>
                    <div className='flex items-center justify-between'>
                        <div className='flex items-center gap-1'>
                            <Checkbox id='remember-me' className=' data-[state=checked]:bg-secondary-tw data-[state=checked]:text-white rounded' />
                            <Label htmlFor='remember-me' className='text-secondary-tw'>{t('custom.remember')}</Label>
                        </div>
                        <div>
                            <Link to={'/forget-password'} className='text-[#768C88]'>
                                {t('profile.forget')}
                            </Link>
                        </div>
                    </div>
                    <Button
                        type='submit'
                        variant='outline'
                        className='w-full bg-primary-tw text-white'
                        disabled={loginFnc.isPending}
                    >
                        {loginFnc.isPending ?
                            <>
                                <Loader className='animate-spin' />
                                {t('custom.checking')}
                            </>
                            :
                            t('custom.check')}
                    </Button>
                </form>
            </section>
        </section>
    );
};

export default Login;