'use client';
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import GoogleIcon from '../../../../public/icons/google.svg';
import { InputField } from '@/components/ui/inputfield';
import { useAuthContext } from '@/lib/contexts/Auth.context';
import { useRouter } from 'next/navigation';
export default function LoginForm({ redirectTo }: { redirectTo?: string }) {
    const handleGoogleLogin = () => {
        window.location.href = `${API_URL}/api/auth/google/login`;
    };

    const API_URL = process.env.NEXT_PUBLIC_API_URL;
    const [errors, setErrors] = useState<any>({});
    const [loading, setLoading] = useState(false);
    const { setUser } = useAuthContext();
    const router = useRouter();
    const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault();
        setLoading(true);
        setErrors({});

        const formData = new FormData(e.currentTarget);
        const emailOrUsername =
            formData.get('emailOrUsername')?.toString() || '';
        const password = formData.get('password')?.toString() || '';

        const newErrors: any = {};
        if (!emailOrUsername)
            newErrors.emailOrUsername = 'Введите никнейм или email';
        if (!password) newErrors.password = 'Введите пароль';

        if (Object.keys(newErrors).length > 0) {
            setErrors(newErrors);
            setLoading(false);
            return;
        }

        const body = new URLSearchParams();
        body.append('username', emailOrUsername);
        body.append('password', password);

        try {
            const res = await fetch(`${API_URL}/api/auth/login`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: body.toString(),
                credentials: 'include',
            });

            if (!res.ok) {
                setErrors({ general: 'Неверный логин или пароль' });
                return;
            } else {
                const meRes = await fetch(`${API_URL}/api/me`, {
                    credentials: 'include',
                });
                if (!meRes.ok) throw new Error('Failed to fetch user');
                const meData = await meRes.json();
                setUser(meData.authenticated ? meData.user : null);
                if (redirectTo) router.push(redirectTo);
            }
        } catch (err) {
            setErrors({ general: 'Ошибка при авторизации' });
        } finally {
            setLoading(false);
        }
    };

    return (
        <form
            onSubmit={handleSubmit}
            className="flex flex-col gap-5 min-w-[310px] w-fit"
        >
            <Button
                type="button"
                onClick={handleGoogleLogin}
                className="w-full bg-white hover:bg-white hover:text-black"
            >
                <GoogleIcon />
                <span className="text-black">Войти через Google</span>
            </Button>

            <div className="flex flex-col gap-2.5">
                <div className="flex flex-col">
                    <InputField
                        placeholder="Никнейм или почта"
                        name="emailOrUsername"
                    />
                    {errors.emailOrUsername && (
                        <p className="text-red pl-5 text-[12px] leading-[16px] mt-[5px]">
                            {errors.emailOrUsername}
                        </p>
                    )}
                </div>

                <div className="flex flex-col">
                    <InputField
                        isPassword
                        placeholder="Пароль"
                        name="password"
                    />
                    {!errors.password && errors.general && (
                        <p className="text-red pl-5 text-[12px] leading-[16px] mt-[5px]">
                            {errors.general}
                        </p>
                    )}
                </div>
            </div>

            <Button type="submit" className="w-full" disabled={loading}>
                {loading ? 'Вход...' : 'Войти'}
            </Button>
        </form>
    );
}
