import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {faApple, faFacebookF, faGoogle} from "@fortawesome/free-brands-svg-icons";
import React, {useContext, useEffect} from "react";
import System from "@/lib/models/System";
import {AlertContext} from "@/context/AlertContext";
import {configs} from "@/lib/configs";
import {SessionContext, SessionContextProps} from "@/context/SessionContext";
import {useTranslations} from "next-intl";
import {LangContext, LangContextProps} from "@/context/LangContext";

export default function SocialForm() {
    const {errorMessage} = useContext(AlertContext);
    const {setSession} = useContext<SessionContextProps>(SessionContext)
    const t = useTranslations();
    const {lang} = useContext<LangContextProps>(LangContext)
    const isElectron = typeof window !== 'undefined' && !!window.electron;

    useEffect((): void => {
        // Skip URL parsing in Electron (OAuth is handled via BrowserWindow)
        if (isElectron) return;

        const params = new URLSearchParams(window.location.search);
        const provider: string | null = params.get('provider');
        if (!provider) {
            return;
        }
        const code: string | null = params.get('code');
        if (!code) {
            return;
        }
        if (provider === 'google') {
            handleGoogleLogin(code).then();
            return;
        }
        if (provider === 'facebook') {
            const state: string | null = params.get('state');
            if (!state) {
                return;
            }
            handleFacebookLogin(code, state).then();
            return;
        }
        if (provider === 'apple') {
            const state: string | null = params.get('state');
            if (!state) {
                return;
            }
            handleAppleLogin(code, state).then();
            return;
        }
    }, []);
    
    async function handleLoginSuccess(token: string): Promise<void> {
        if (window.electron) {
            await window.electron.setToken(token);
            window.electron.loginSuccess(token);
        } else {
            System.setCookie('token', token, 30);
            setSession({isConnected: true, user: null, accessToken: token});
        }
    }

    async function handleFacebookLogin(code: string, state: string): Promise<void> {
        if (code && state) {
            const response: string = await System.postToServer<string>(`auth/facebook`, {
                code: code,
                state: state,
            }, lang);
            if (!response) {
                errorMessage(t('socialForm.error.connection'));
                return;
            }
            await handleLoginSuccess(response);
        }
    }

    async function handleGoogleLogin(code: string): Promise<void> {
        if (code) {
            const response: string = await System.postToServer<string>(`auth/google`, {
                code: code,
            }, lang);
            if (!response) {
                errorMessage(t('socialForm.error.connection'));
                return;
            }
            await handleLoginSuccess(response);
        }
    }

    async function handleAppleLogin(code: string, state: string): Promise<void> {
        if (code && state) {
            const response: string = await System.postToServer<string>(`auth/apple`, {
                code: code,
                state: state,
            }, lang);
            if (!response) {
                errorMessage(t('socialForm.error.connection'));
                return;
            }
            await handleLoginSuccess(response);
        }
    }
    
    async function handleOAuthClick(provider: 'google' | 'facebook' | 'apple'): Promise<void> {
        if (!window.electron) return;

        try {
            const result = await window.electron.oauthLogin(provider, configs.baseUrl);

            if (!result.success) {
                if (result.error !== 'Window closed by user') {
                    errorMessage(t('socialForm.error.connection'));
                }
                return;
            }

            if (result.code) {
                if (provider === 'google') {
                    await handleGoogleLogin(result.code);
                } else if (provider === 'facebook' && result.state) {
                    await handleFacebookLogin(result.code, result.state);
                } else if (provider === 'apple' && result.state) {
                    await handleAppleLogin(result.code, result.state);
                }
            }
        } catch (error) {
            errorMessage(t('socialForm.error.connection'));
        }
    }

    return (
        <div className="flex justify-center gap-3">
            <button
                onClick={() => handleOAuthClick('facebook')}
                className="flex items-center justify-center w-14 h-14 bg-[#1877F2] hover:bg-opacity-90 text-textPrimary rounded-xl transition-colors cursor-pointer"
                aria-label="Login with Facebook"
            >
                <FontAwesomeIcon icon={faFacebookF} className="w-6 h-6 text-textPrimary"/>
            </button>

            <button
                onClick={() => handleOAuthClick('google')}
                className="flex items-center justify-center w-14 h-14 bg-white hover:bg-opacity-90 text-[#4285F4] rounded-xl transition-colors cursor-pointer"
                aria-label="Login with Google"
            >
                <FontAwesomeIcon icon={faGoogle} className="w-6 h-6 text-[#4285F4]"/>
            </button>

            <button
                onClick={() => handleOAuthClick('apple')}
                className="flex items-center justify-center w-14 h-14 bg-black hover:bg-opacity-90 text-white rounded-xl transition-colors cursor-pointer"
                aria-label="Login with Apple"
            >
                <FontAwesomeIcon icon={faApple} className="w-6 h-6 text-white"/>
            </button>
        </div>
    )
}
