'use client';

/**
 * 로그인 페이지 컴포넌트
 * 
 * Google 로그인을 통해 InsuWiki에 접근합니다.
 */

import { useAuth } from '@/contexts/AuthContext';
import { useRouter, useSearchParams } from 'next/navigation';
import { useEffect, useState, Suspense } from 'react';
import { isInAppBrowser, redirectToExternalBrowser } from '@/lib/browserUtils';
import { toast } from 'sonner';

function LoginContent() {
    const { user, loading, signInWithGoogle } = useAuth();
    const router = useRouter();
    const searchParams = useSearchParams();
    const [error, setError] = useState<string | null>(null);
    const [isSigningIn, setIsSigningIn] = useState(false);
    const [inAppError, setInAppError] = useState(false);

    useEffect(() => {
        // 인앱 브라우저 체크
        if (isInAppBrowser()) {
            setInAppError(true);
            // Android라면 즉시 Chrome 실행 시도
            if (typeof navigator !== 'undefined' && /android/i.test(navigator.userAgent)) {
                redirectToExternalBrowser();
            }
        }
    }, []);

    useEffect(() => {
        if (!loading && user) {
            // 1. URL Query Param에서 returnUrl 확인 (크로스 브라우저 호환)
            const returnUrlParam = searchParams.get('returnUrl');
            // 2. sessionStorage에서 확인 (같은 브라우저 내 이동)
            const returnUrlSession = sessionStorage.getItem('redirectUrl');

            const destination = returnUrlParam || returnUrlSession || '/';

            // 로그인 후 리다이렉트
            router.push(destination);

            // 사용한 세션 스토리지 정리
            if (returnUrlSession) sessionStorage.removeItem('redirectUrl');
        }
    }, [user, loading, router, searchParams]);

    const handleGoogleLogin = async () => {
        // 인앱 브라우저에서 강제로 로그인 시도 못하게 막음
        if (inAppError) {
            redirectToExternalBrowser(); // 다시 시도
            return;
        }

        setIsSigningIn(true);
        setError(null);
        try {
            await signInWithGoogle();
        } catch (err) {
            setError('로그인에 실패했습니다. 다시 시도해 주세요.');
            console.error(err);
        } finally {
            setIsSigningIn(false);
        }
    };

    const copyUrlToClipboard = () => {
        if (typeof window !== 'undefined') {
            navigator.clipboard.writeText(window.location.href);
            toast.success('주소가 복사되었습니다. Chrome이나 Safari 등 외부 브라우저에서 열어주세요.');
        }
    };


    if (loading) {
        return (
            <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-100">
                <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-indigo-600"></div>
            </div>
        );
    }

    // 인앱 브라우저 감지 시 안내 화면
    if (inAppError) {
        return (
            <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-100 p-6">
                <div className="bg-white p-8 rounded-2xl shadow-xl max-w-md w-full mx-auto text-center space-y-6">
                    <div className="flex justify-center">
                        <div className="bg-amber-100 p-4 rounded-full">
                            <svg className="w-12 h-12 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
                            </svg>
                        </div>
                    </div>

                    <div>
                        <h2 className="text-xl font-bold text-gray-800 mb-2">외부 브라우저 권장</h2>
                        <p className="text-gray-600 text-sm leading-relaxed">
                            현재 접속하신 환경(카카오톡, 네이버 등)에서는 보안 정책으로 인해 Google 로그인이 제한될 수 있습니다.
                        </p>
                        <p className="text-indigo-600 font-semibold mt-2 text-sm">
                            Chrome 또는 Safari에서 다시 열어주세요.
                        </p>
                    </div>

                    <div className="space-y-3 pt-2">
                        <button
                            onClick={redirectToExternalBrowser}
                            className="w-full flex items-center justify-center space-x-2 py-3 px-4 rounded-lg shadow-md text-white bg-indigo-600 hover:bg-indigo-700 active:bg-indigo-800 transition-all transform hover:-translate-y-0.5"
                        >
                            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                            </svg>
                            <span>외부 브라우저로 열기 (Android)</span>
                        </button>

                        <button
                            onClick={copyUrlToClipboard}
                            className="w-full flex items-center justify-center space-x-2 py-3 px-4 border border-gray-200 rounded-lg shadow-sm text-gray-700 bg-white hover:bg-gray-50 active:bg-gray-100 transition-colors"
                        >
                            <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3" />
                            </svg>
                            <span>현재 주소 복사하기</span>
                        </button>
                    </div>
                </div>
            </div>
        );
    }

    return (
        <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-100 p-4">
            <div className="bg-white p-8 rounded-2xl shadow-xl max-w-md w-full mx-auto">
                {/* 로고 영역 */}
                <div className="text-center mb-8">
                    <h1 className="text-4xl font-bold text-indigo-600 mb-2">InsuWiki</h1>
                    <p className="text-gray-600">보험 지식 공유 플랫폼</p>
                </div>

                {/* 구글 로그인 버튼 */}
                <button
                    onClick={handleGoogleLogin}
                    disabled={isSigningIn}
                    className="w-full flex items-center justify-center space-x-2 py-3 px-4 border border-gray-300 rounded-lg shadow-sm bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition-colors disabled:opacity-50 disabled:cursor-not-allowed group"
                >
                    {isSigningIn ? (
                        <div className="w-6 h-6 border-2 border-indigo-600 border-t-transparent rounded-full animate-spin"></div>
                    ) : (
                        <>
                            <svg className="w-5 h-5 group-hover:scale-110 transition-transform" viewBox="0 0 24 24">
                                <path
                                    fill="#4285F4"
                                    d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
                                />
                                <path
                                    fill="#34A853"
                                    d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
                                />
                                <path
                                    fill="#FBBC05"
                                    d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"
                                />
                                <path
                                    fill="#EA4335"
                                    d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
                                />
                            </svg>
                            <span className="font-medium text-gray-700">Google 계정으로 로그인</span>
                        </>
                    )}
                </button>

                {/* 에러 메시지 */}
                {error && (
                    <div className="mt-4 p-3 bg-red-50 border border-red-200 rounded-lg text-red-600 text-sm text-center">
                        {error}
                    </div>
                )}

                {/* 안내 문구 */}
                <div className="mt-8 text-center text-sm text-gray-500">
                    <p>화이트리스트에 등록된 사용자만 접근 가능합니다.</p>
                    <p className="mt-1 hover:text-indigo-600 transition-colors cursor-pointer">문의: 관리자에게 연락하세요.</p>
                </div>
            </div>
        </div>
    );
}

export default function LoginPage() {
    return (
        <Suspense fallback={
            <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-100">
                <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-indigo-600"></div>
            </div>
        }>
            <LoginContent />
        </Suspense>
    );
}
