'use client'
import {useContext, useEffect, useState} from 'react';
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {faEnvelope, faWifi, faCloudArrowUp} from "@fortawesome/free-solid-svg-icons";
import LoginForm from "@/app/login/login/LoginForm";
import SocialForm from "@/app/login/login/SocialForm";
import {useTranslations} from "next-intl";
import {LangContext} from "@/context/LangContext";
import System from "@/lib/models/System";

export default function LoginPage() {
    const t = useTranslations();
    const {lang, setLang} = useContext(LangContext);
    const [showOfflineWarning, setShowOfflineWarning] = useState(false);
    const [isOnline, setIsOnline] = useState(true);

    const toggleLanguage = () => {
        const newLang = lang === 'fr' ? 'en' : 'fr';
        setLang(newLang);
        System.setCookie('lang', newLang, 365);
    };

    useEffect(() => {
        async function checkFirstConnectionAndNetwork() {
            // Check if we're in Electron
            if (!window.electron) {
                return;
            }

            try {
                // Check if token exists (first connection)
                const token = await window.electron.getToken();
                const hasToken = !!token;

                // Check network status
                const online = navigator.onLine;
                setIsOnline(online);

                // Show warning if first connection AND offline
                if (!hasToken && !online) {
                    setShowOfflineWarning(true);
                }
            } catch (error) {
                console.error('Error checking first connection:', error);
            }
        }

        checkFirstConnectionAndNetwork();

        // Listen for online/offline events
        const handleOnline = () => {
            setIsOnline(true);
            setShowOfflineWarning(false);
        };
        const handleOffline = async () => {
            setIsOnline(false);
            // Check if token exists
            if (window.electron) {
                const token = await window.electron.getToken();
                if (!token) {
                    setShowOfflineWarning(true);
                }
            }
        };

        window.addEventListener('online', handleOnline);
        window.addEventListener('offline', handleOffline);

        return () => {
            window.removeEventListener('online', handleOnline);
            window.removeEventListener('offline', handleOffline);
        };
    }, []);

    return (
        <main className="flex min-h-screen flex-col items-center justify-center bg-background text-textPrimary p-4">
            <div className="w-full max-w-md px-4 py-10">
                <div className="flex justify-center mb-8">
                    <div className="w-[90%] max-w-[320px] relative">
                        <img
                            src="/logo.png"
                            alt="ERitors"
                            className="object-contain"
                            style={{width: 320, height: 107}}
                        />
                    </div>
                </div>

                {/* Offline warning notification */}
                {showOfflineWarning && (
                    <div className="mb-6 bg-gradient-to-r from-orange-500/20 to-amber-500/20 border border-orange-500/40 rounded-xl p-4 shadow-lg shadow-orange-500/10">
                        <div className="flex items-start gap-3">
                            <div className="flex-shrink-0 mt-0.5">
                                <div className="relative">
                                    <FontAwesomeIcon icon={faWifi} className="w-5 h-5 text-orange-400" />
                                    <div className="absolute inset-0 w-6 h-0.5 bg-orange-400 rotate-45 top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2"></div>
                                </div>
                            </div>
                            <div className="flex-1">
                                <h3 className="font-semibold text-orange-200 mb-1 flex items-center gap-2">
                                    <FontAwesomeIcon icon={faCloudArrowUp} className="w-4 h-4" />
                                    {t('loginPage.offlineWarning.title')}
                                </h3>
                                <p className="text-sm text-orange-300/90 leading-relaxed">
                                    {t('loginPage.offlineWarning.message')}
                                </p>
                            </div>
                        </div>
                    </div>
                )}

                <div
                    className="bg-tertiary rounded-2xl overflow-hidden shadow-xl shadow-primary/10 w-full relative">
                    <button
                        onClick={toggleLanguage}
                        className="absolute right-4 top-4 z-10 flex items-center gap-2 px-3 py-2 bg-secondary border border-gray-dark rounded-lg hover:bg-tertiary transition-colors"
                        aria-label="Toggle language"
                    >
                        <span
                            className={`text-sm font-medium ${lang === 'fr' ? 'text-primary' : 'text-muted'}`}>FR</span>
                        <span className="text-muted">/</span>
                        <span
                            className={`text-sm font-medium ${lang === 'en' ? 'text-primary' : 'text-muted'}`}>EN</span>
                    </button>
                    <div
                        className="absolute top-0 left-0 right-0 h-2 bg-gradient-to-r from-primary to-info pointer-events-none"></div>
                    <div
                        className="absolute -top-10 -left-10 w-40 h-40 bg-gradient-to-br from-primary/20 to-transparent rounded-full blur-xl pointer-events-none"></div>
                    <div
                        className="absolute -bottom-10 -right-10 w-40 h-40 bg-gradient-to-br from-info/20 to-transparent rounded-full blur-xl pointer-events-none"></div>
                    
                    <div className="p-6 sm:p-8">
                        <div className="text-center mb-8">
                            <h1 className="text-2xl sm:text-3xl font-bold mb-2 font-['ADLaM Display']">{t('loginPage.title')}</h1>
                            <p className="text-muted">{t('loginPage.welcome')}</p>
                        </div>
                        <LoginForm/>
                        <div className="relative my-6">
                            <div className="absolute inset-0 flex items-center">
                                <div className="w-full border-t border-gray-dark"></div>
                            </div>
                            <div className="relative flex justify-center">
                                <span className="px-3 bg-tertiary text-muted text-sm">{t('loginPage.orSocial')}</span>
                            </div>
                        </div>
                        <div className="flex justify-center gap-3 mb-6">
                            <a
                                href="/login/register"
                                className="flex items-center justify-center w-14 h-14 bg-gradient-to-r from-primary to-info hover:shadow-lg hover:shadow-primary/20 text-textPrimary rounded-xl transition-all"
                                aria-label="Register with email"
                            >
                                <FontAwesomeIcon icon={faEnvelope} className="w-6 h-6 text-textPrimary"/>
                            </a>
                            <SocialForm/>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    );
}