'use client';

import { useState, useEffect } from "react";
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { InfoIcon, GlobeIcon, ChevronDownIcon, ArrowLeft } from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuRadioGroup, DropdownMenuRadioItem } from "@/components/ui/dropdown-menu"
import { useTranslation } from '@/i18n/client'
import { useRouter, useParams, usePathname, useSearchParams } from 'next/navigation';
import { signIn, useSession } from 'next-auth/react';
import { buttonVariants } from "@/components/ui/button"
import Link from "next/link"
import { useFormState } from 'react-dom';
import {
    InputOTP,
    InputOTPGroup,
    InputOTPSlot,
} from "@/components/ui/input-otp"
import { requestPasswordResetAction } from "@/lib/users/auth/partners-auth";
import { checkEmailAndStartAuth, resendEmailOtp } from "@/lib/users/auth/email-auth";
import Loading from "../common/loading/loading";
import { VideoBackground } from "@/components/common/video-background";

// 배경 영상 목록
const BACKGROUND_VIDEOS = [
    '/background-videos/1.yard.mp4',
    '/background-videos/2.SN2635_LNGC_CARDIFF.mp4',
    '/background-videos/3.SN2628_CONT_WAN HAI.mp4',
    '/background-videos/4.SN2612_LNGC_KGL.mp4',
    '/background-videos/5.SN2596_LNGC_JP MORGAN.mp4',
    '/background-videos/6.2235_FLNG_ENI_CORAL.mp4',
    '/background-videos/7.2126_FLNG_PETRONAS.mp4',
];

export function LoginForm() {
    const params = useParams() || {};
    const pathname = usePathname() || '';
    const router = useRouter();
    const searchParams = useSearchParams();

    const lng = params.lng as string;
    const { t, i18n } = useTranslation(lng, 'login');
    const { toast } = useToast();
    const { data: session, status } = useSession();

    // 상태 관리
    const [isFirstAuthLoading, setIsFirstAuthLoading] = useState(false);
    const [showForgotPassword, setShowForgotPassword] = useState(false);

    // MFA 관련 상태
    const [showMfaForm, setShowMfaForm] = useState(false);
    const [mfaToken, setMfaToken] = useState('');
    const [tempAuthKey, setTempAuthKey] = useState('');
    const [mfaUserId, setMfaUserId] = useState<number | null>(null);
    const [mfaUserEmail, setMfaUserEmail] = useState('');
    const [mfaUserName, setMfaUserName] = useState(''); // Email OTP 전송 시 필요
    const [mfaCountdown, setMfaCountdown] = useState(0);
    const [mfaType, setMfaType] = useState<'sms' | 'email'>('sms'); // MFA 타입

    // 이메일 기반 인증 상태
    const [emailInput, setEmailInput] = useState('');
    const [showPasswordInput, setShowPasswordInput] = useState(false);
    const [isWhitelistedEmail, setIsWhitelistedEmail] = useState(false);

    // 일반 로그인 폼 데이터
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');

    const [isMfaLoading, setIsMfaLoading] = useState(false);
    const [isSmsLoading, setIsSmsLoading] = useState(false);

    // 서버 액션 상태
    const [passwordResetState, passwordResetAction] = useFormState(requestPasswordResetAction, {
        success: false,
        error: undefined,
        message: undefined,
    });

    // 호스트명 확인 상태 추가
    const [isDataRoomHost, setIsDataRoomHost] = useState(false);

    // 컴포넌트 마운트 시 호스트명 확인
    useEffect(() => {
        if (typeof window !== 'undefined') {
            const hostname = window.location.hostname;
            setIsDataRoomHost(hostname.includes('shidataroom'));
        }
    }, []);

    // // 영문 페이지에서 S-Gips 로그인 비활성화 시 기본 로그인 방법 설정
    // useEffect(() => {
    //     if (lng === 'en' && loginMethod === 'sgips') {
    //         setLoginMethod('username');
    //     }
    // }, [lng, loginMethod]);

    // 이미 로그인된 사용자 리다이렉트 처리
    useEffect(() => {
        if (status === 'authenticated' && session?.user) {
            const callbackUrlParam = searchParams?.get('callbackUrl');

            if (callbackUrlParam) {
                try {
                    // URL 객체로 파싱
                    const callbackUrl = new URL(callbackUrlParam);

                    // pathname + search만 사용 (호스트 제거)
                    const relativeUrl = callbackUrl.pathname + callbackUrl.search;
                    router.push(relativeUrl);
                } catch {
                    // 유효하지 않은 URL이면 그대로 사용 (이미 상대 경로일 수 있음)
                    router.push(callbackUrlParam);
                }
            } else {
                if (session.user.ownerCompanyId) {
                    router.push(`/${lng}/partners/data-room`);

                } else {
                    router.push(`/${lng}/partners/dashboard`);

                }
            }
        }
    }, [status, session, router, lng, searchParams]);

    const handleChangeLanguage = (lang: string) => {
        const segments = pathname.split('/');
        segments[1] = lang;
        router.push(segments.join('/'));
    };

    const currentLanguageText = i18n.language === 'ko' ? t('languages.korean') : t('languages.english');

    // 세분화된 에러 메시지 처리 함수
    const getErrorMessage = (error: { errorCode?: string; message?: string }) => {
        const errorCode = error.errorCode;

        if (!errorCode) {
            return error.message || t('authenticationFailed');
        }

        switch (errorCode) {
            case 'INVALID_CREDENTIALS':
                return t('invalidCredentials');
            case 'ACCOUNT_LOCKED':
                return t('accountLocked');
            case 'ACCOUNT_DEACTIVATED':
                return t('accountDeactivated');
            case 'RATE_LIMITED':
                return t('rateLimited');
            case 'VENDOR_NOT_FOUND':
                return t('vendorNotFound');
            case 'SYSTEM_ERROR':
                return t('systemError');
            default:
                return error.message || t('authenticationFailed');
        }
    };

    const goToVendorRegistration = () => {
        router.push(`/${lng}/partners/repository`);
    };

    // MFA 카운트다운 효과
    useEffect(() => {
        if (mfaCountdown > 0) {
            const timer = setTimeout(() => setMfaCountdown(mfaCountdown - 1), 1000);
            return () => clearTimeout(timer);
        }
    }, [mfaCountdown]);

    // 서버 액션 결과 처리
    useEffect(() => {
        if (passwordResetState.success && passwordResetState.message) {
            toast({
                title: t('resetLinkSent'),
                description: passwordResetState.message,
            });
            setShowForgotPassword(false);
        } else if (passwordResetState.error) {
            toast({
                title: t('errorTitle'),
                description: passwordResetState.error,
                variant: 'destructive',
            });
        }
    }, [passwordResetState, toast, t]);

    // 1차 인증 수행 (공통 함수)
    const performFirstAuth = async (username: string, password: string, provider: 'email' | 'sgips') => {
        try {
            const response = await fetch('/api/auth/first-auth', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    username,
                    password,
                    provider
                }),
            });

            const result = await response.json();

            if (!response.ok) {
                // 세분화된 에러 메시지 처리
                const error = new Error(result.error || t('authenticationFailed')) as Error & { errorCode?: string };
                error.errorCode = result.errorCode;
                throw error;
            }

            return result;
        } catch (error) {
            console.error('First auth error:', error);
            throw error;
        }
    };

    // SMS 토큰 전송
    const handleSendSms = async (userIdParam?: number) => {
        const targetUserId = userIdParam || mfaUserId;
        if (!targetUserId || mfaCountdown > 0) return;

        setIsSmsLoading(true);
        try {
            const requestBody: { userId: number } = { userId: targetUserId };

            const response = await fetch('/api/auth/send-sms', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(requestBody),
            });

            if (response.ok) {
                setMfaCountdown(60);
                toast({
                    title: t('smsSent'),
                    description: t('smsCodeSent'),
                });
            } else {
                const errorData = await response.json();
                toast({
                    title: t('errorTitle'),
                    description: errorData.message || t('smsFailure'),
                    variant: 'destructive',
                });
            }
        } catch (error) {
            console.error('SMS send error:', error);
            toast({
                title: t('errorTitle'),
                description: t('smsError'),
                variant: 'destructive',
            });
        } finally {
            setIsSmsLoading(false);
        }
    };

    // Email OTP 전송/재전송
    const handleSendEmail = async (userIdParam?: number, emailParam?: string, userNameParam?: string) => {
        const targetUserId = userIdParam || mfaUserId;
        const targetEmail = emailParam || mfaUserEmail;
        const targetUserName = userNameParam || mfaUserName;

        if (!targetUserId || mfaCountdown > 0) return;

        setIsSmsLoading(true);
        try {
            // 서버 액션 사용
            const result = await resendEmailOtp(targetUserId, targetEmail, targetUserName);

            if (result.success) {
                setMfaCountdown(60);
                toast({
                    title: t('emailOtpSentTitle'),
                    description: t('emailOtpSentTo', { email: targetEmail }),
                });
            } else {
                toast({
                    title: t('errorTitle'),
                    description: result.error || t('emailOtpSendFailed'),
                    variant: 'destructive',
                });
            }
        } catch (error) {
            console.error('Email OTP send error:', error);
            toast({
                title: t('errorTitle'),
                description: t('emailOtpSendError'),
                variant: 'destructive',
            });
        } finally {
            setIsSmsLoading(false);
        }
    };

    // MFA 토큰 검증 및 최종 로그인
    const handleMfaSubmit = async (e: React.FormEvent) => {
        e.preventDefault();

        if (!mfaToken || mfaToken.length !== 6) {
            toast({
                title: t('errorTitle'),
                description: t('enterSixDigitCode'),
                variant: 'destructive',
            });
            return;
        }

        if (!tempAuthKey) {
            toast({
                title: t('errorTitle'),
                description: t('authSessionExpired'),
                variant: 'destructive',
            });
            setShowMfaForm(false);
            return;
        }

        setIsMfaLoading(true);

        try {
            // NextAuth의 credentials-mfa 프로바이더로 최종 인증 (mfaType 포함)
            const result = await signIn('credentials-mfa', {
                userId: mfaUserId,
                smsToken: mfaToken,
                tempAuthKey: tempAuthKey,
                mfaType: mfaType, // 'sms' 또는 'email'
                redirect: false,
            });

            if (result?.ok) {
                toast({
                    title: t('authenticationComplete'),
                    description: t('loginCompleted'),
                });

                // 콜백 URL 처리
                const callbackUrlParam = searchParams?.get('callbackUrl');
                if (callbackUrlParam) {
                    try {
                        const callbackUrl = new URL(callbackUrlParam);
                        const relativeUrl = callbackUrl.pathname + callbackUrl.search;
                        router.push(relativeUrl);
                    } catch {
                        router.push(callbackUrlParam);
                    }
                } else {
                    router.push(`/${lng}/partners/dashboard`);
                }
            } else {
                let errorMessage = t('invalidAuthCode');

                if (result?.error) {
                    switch (result.error) {
                        case 'CredentialsSignin':
                            errorMessage = t('authCodeExpired');
                            break;
                        case 'AccessDenied':
                            errorMessage = t('accessDenied');
                            break;
                        default:
                            errorMessage = t('mfaAuthFailed');
                    }
                }

                toast({
                    title: t('errorTitle'),
                    description: errorMessage,
                    variant: 'destructive',
                });
            }
        } catch (error) {
            console.error('MFA verification error:', error);
            toast({
                title: t('errorTitle'),
                description: t('mfaAuthError'),
                variant: 'destructive',
            });
        } finally {
            setIsMfaLoading(false);
        }
    };

    // 이메일 제출 핸들러 (1단계)
    const handleEmailSubmit = async (e: React.FormEvent) => {
        e.preventDefault();

        if (!emailInput) {
            toast({
                title: t('errorTitle'),
                description: t('pleaseEnterEmail'),
                variant: 'destructive',
            });
            return;
        }

        setIsFirstAuthLoading(true);

        try {
            // 이메일 화이트리스트 확인 및 인증 시작
            const result = await checkEmailAndStartAuth(emailInput);

            if (!result.success) {
                const errorMessage = getErrorMessage(
                    { errorCode: result.errorCode, message: result.error }
                );

                toast({
                    title: t('errorTitle'),
                    description: errorMessage,
                    variant: 'destructive',
                });
                return;
            }

            if (result.isWhitelisted) {
                // 화이트리스트 이메일: 바로 Email MFA로 이동
                setIsWhitelistedEmail(true);
                setMfaUserId(result.userId!);
                setMfaUserEmail(emailInput);
                setMfaUserName(result.userName || '');
                setTempAuthKey(result.tempAuthKey!);
                setMfaType('email');
                setShowMfaForm(true);

                toast({
                    title: t('emailVerification'),
                    description: t('emailOtpSentTo', { email: emailInput }),
                });
            } else {
                // 일반 이메일: 패스워드 입력 필요
                setIsWhitelistedEmail(false);
                setUsername(emailInput);
                setShowPasswordInput(true);

                toast({
                    title: t('passwordInput'),
                    description: t('pleaseEnterPassword'),
                });
            }
        } catch (error: unknown) {
            console.error('Email submit error:', error);

            toast({
                title: t('errorTitle'),
                description: t('emailVerificationError'),
                variant: 'destructive',
            });
        } finally {
            setIsFirstAuthLoading(false);
        }
    };

    // 패스워드 제출 핸들러 (2단계 - 화이트리스트 아닌 경우)
    const handlePasswordSubmit = async (e: React.FormEvent) => {
        e.preventDefault();

        if (!password) {
            toast({
                title: t('errorTitle'),
                description: t('pleaseEnterPassword'),
                variant: 'destructive',
            });
            return;
        }

        setIsFirstAuthLoading(true);

        try {
            // 1차 인증 수행 (패스워드 검증)
            const authResult = await performFirstAuth(username, password, 'email');

            if (authResult.success) {
                // 패스워드 인증 성공 -> SMS MFA로 진행
                toast({
                    title: t('firstAuthComplete'),
                    description: t('proceedingSmsAuth'),
                });

                // MFA 화면으로 전환
                setTempAuthKey(authResult.tempAuthKey);
                setMfaUserId(authResult.userId);
                setMfaUserEmail(authResult.email);
                setMfaUserName(authResult.userName || '');
                setMfaType('sms');
                setShowMfaForm(true);

                // SMS 자동 전송
                setTimeout(() => {
                    handleSendSms(authResult.userId);
                }, 500);

                toast({
                    title: t('smsAuthRequired'),
                    description: t('sendingCodeToPhone'),
                });
            }
        } catch (error: unknown) {
            console.error('Password submit error:', error);

            const errorMessage = getErrorMessage(
                error as { errorCode?: string; message?: string }
            );

            toast({
                title: t('errorTitle'),
                description: errorMessage,
                variant: 'destructive',
            });
        } finally {
            setIsFirstAuthLoading(false);
        }
    };


    // MFA 화면 또는 패스워드 입력에서 뒤로 가기
    const handleBackToLogin = () => {
        // MFA 화면인 경우
        if (showMfaForm) {
            // 화이트리스트 이메일인 경우 이메일 입력으로 돌아감
            if (isWhitelistedEmail) {
                setShowMfaForm(false);
                setMfaToken('');
                setTempAuthKey('');
                setMfaUserId(null);
                setMfaUserEmail('');
                setMfaUserName('');
                setMfaType('email');
                setMfaCountdown(0);
                setIsWhitelistedEmail(false);
            } else {
                // 일반 이메일인 경우 패스워드 입력으로 돌아감
                setShowMfaForm(false);
                setMfaToken('');
                setTempAuthKey('');
                setMfaUserId(null);
                setMfaUserEmail('');
                setMfaUserName('');
                setMfaType('sms');
                setMfaCountdown(0);
                setShowPasswordInput(true);
            }
        } else if (showPasswordInput) {
            // 패스워드 입력 화면인 경우 이메일 입력으로 돌아감
            setShowPasswordInput(false);
            setPassword('');
            setUsername('');
        }
    };

    // 세션 로딩 중이거나 이미 인증된 상태에서는 로딩 표시
    if (status === 'loading') {
        return (
            <Loading message={t('loading')} />
        );
    }

    // 이미 인증된 상태에서는 빈 화면 (리다이렉트 중)
    if (status === 'authenticated' && session?.user) {
        return (
            <Loading message={t('redirecting')} />
        );
    }

    return (
        <div className="relative flex h-screen w-full items-center justify-start overflow-hidden">
            {/* 전체 화면 배경 영상 */}
            <VideoBackground 
                videos={BACKGROUND_VIDEOS} 
                overlayClassName="bg-black/50"
                showCacheStatus={process.env.NODE_ENV === 'development'}
            />

            {/* 로그인 카드 */}
            <div className="relative z-20 w-full max-w-md ml-8 md:ml-16 lg:ml-24">
                {/* 불투명한 카드 배경 */}
                <div className="bg-card rounded-lg shadow-2xl overflow-hidden border border-border">
                    {/* 헤더 */}
                    <div className="px-6 py-4 border-b bg-gradient-to-r from-blue-600 to-blue-700">
                        <div className="flex items-center justify-between text-white">
                            <div className="flex items-center space-x-2">
                                {/* <Ship className="w-5 h-5" /> */}
                                <span className="text-lg font-bold">{isDataRoomHost ? "Data Room" : "eVCP"}</span>
                            </div>
                            {!isDataRoomHost && (
                                <Link
                                    href="/partners/repository"
                                    className={cn(
                                        buttonVariants({ variant: "ghost" }),
                                        "text-white hover:bg-white/20 hover:text-white"
                                    )}
                                >
                                    <InfoIcon className="w-4 h-4 mr-1" />
                                    {t('registerVendor')}
                                </Link>
                            )}
                        </div>
                    </div>

                    {/* 로그인 폼 컨텐츠 */}
                    <div className="p-8">
                        <div className="flex flex-col gap-6">
                            {/* Header */}
                            <div className="flex flex-col items-center text-center">
                                    {!showMfaForm ? (
                                        <>
                                       
                                            <h1 className="text-2xl font-bold text-foreground">{isDataRoomHost ? t('loginMessageDataRoom') :t('loginMessage')}</h1>
                                            <p className="text-xs text-muted-foreground mt-2">
                                                {isDataRoomHost?t('loginDescriptionDataRoom') :t('loginDescription')}
                                            </p>
                                        </>
                                    ) : (
                                        <>
                                            <div className="flex items-center justify-center w-12 h-12 rounded-full bg-blue-100 dark:bg-blue-900/30 mb-4">
                                                {mfaType === 'email' ? '📧' : '🔐'}
                                            </div>
                                            <h1 className="text-2xl font-bold text-foreground">
                                                {mfaType === 'email' ? t('emailVerification') : t('smsVerification')}
                                            </h1>
                                            <p className="text-sm text-muted-foreground mt-2">
                                                {mfaType === 'email'
                                                    ? t('emailOtpSentTo', { email: mfaUserEmail })
                                                    : t('firstAuthCompleteFor', { email: mfaUserEmail })
                                                }
                                            </p>
                                            <p className="text-xs text-muted-foreground mt-1">
                                                {mfaType === 'email'
                                                    ? t('enterSixDigitEmailCode')
                                                    : t('enterSixDigitCodeInstructions')}
                                            </p>
                                        </>
                                    )}
                                </div>

                                {/* 로그인 폼 또는 MFA 폼 */}
                                {!showMfaForm ? (
                                    <>
                                        {/* Login Form */}
                                        <>
                                            {!showPasswordInput ? (
                                                // 1단계: 이메일만 입력
                                                    <form onSubmit={handleEmailSubmit} className="grid gap-4">
                                                        <div className="grid gap-2">
                                                            <Input
                                                                id="email"
                                                                type="email"
                                                                placeholder={t('emailPlaceholder')}
                                                                required
                                                                className="h-10"
                                                                value={emailInput}
                                                                onChange={(e) => setEmailInput(e.target.value)}
                                                                disabled={isFirstAuthLoading}
                                                                autoFocus
                                                            />
                                                        </div>
                                                        <Button
                                                            type="submit"
                                                            className="w-full"
                                                            variant="samsung"
                                                            disabled={isFirstAuthLoading || !emailInput}
                                                        >
                                                            {isFirstAuthLoading ? t('authenticating') : t('next')}
                                                        </Button>
                                                    </form>
                                                ) : (
                                                    // 2단계: 패스워드 입력
                                                    <div className="space-y-4">
                                                        {/* 뒤로 가기 버튼 */}
                                                        <div className="flex items-center justify-start">
                                                            <Button
                                                                type="button"
                                                                variant="ghost"
                                                                size="sm"
                                                                onClick={handleBackToLogin}
                                                                className="text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300"
                                                            >
                                                                <ArrowLeft className="w-4 h-4 mr-1" />
                                                                {t('backToLogin')}
                                                            </Button>
                                                        </div>

                                                        {/* 이메일 표시 */}
                                                        <div className="bg-muted p-3 rounded-lg">
                                                            <p className="text-sm text-muted-foreground mb-1">{t('loginEmail')}</p>
                                                            <p className="text-sm font-medium text-foreground">{emailInput}</p>
                                                        </div>

                                                        {/* 패스워드 입력 폼 */}
                                                        <form onSubmit={handlePasswordSubmit} className="grid gap-4">
                                                            <div className="grid gap-2">
                                                                <Input
                                                                    id="password"
                                                                    type="password"
                                                                    placeholder={t('password')}
                                                                    required
                                                                    className="h-10"
                                                                    value={password}
                                                                    onChange={(e) => setPassword(e.target.value)}
                                                                    disabled={isFirstAuthLoading}
                                                                    autoFocus
                                                                />
                                                            </div>
                                                            <Button
                                                                type="submit"
                                                                className="w-full"
                                                                variant="samsung"
                                                                disabled={isFirstAuthLoading || !password}
                                                            >
                                                                {isFirstAuthLoading ? t('authenticating') : t('login')}
                                                            </Button>
                                                        </form>
                                                    </div>
                                                )}
                                        </>

                                        {/* Additional Links */}
                                        <div className="flex flex-col gap-2 text-center">
                                            {/* 신규 업체 등록은 항상 표시 */}
                                            {!isDataRoomHost && (
                                                <Button
                                                    type="button"
                                                    variant="link"
                                                    className="text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 text-sm"
                                                    onClick={goToVendorRegistration}
                                                >
                                                    {t('newVendor')}
                                                </Button>
                                            )}

                                            {/* 비밀번호 찾기는 패스워드 입력 단계에서만 표시 */}
                                            {showPasswordInput && (
                                                <Button
                                                    type="button"
                                                    variant="link"
                                                    className="text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300 text-sm"
                                                    onClick={() => setShowForgotPassword(true)}
                                                >
                                                    {t('forgotPassword')}
                                                </Button>
                                            )}
                                        </div>
                                    </>
                                ) : (
                                    /* MFA 입력 폼 */
                                    <div className="space-y-6">
                                        {/* 뒤로 가기 버튼 */}
                                        <div className="flex items-center justify-start">
                                            <Button
                                                type="button"
                                                variant="ghost"
                                                size="sm"
                                                onClick={handleBackToLogin}
                                                className="text-blue-600 hover:text-blue-800 dark:text-blue-400 dark:hover:text-blue-300"
                                            >
                                                <ArrowLeft className="w-4 h-4 mr-1" />
                                                {t('backToLogin')}
                                            </Button>
                                        </div>

                                        {/* OTP 재전송 섹션 (SMS/Email) */}
                                        <div className="bg-muted p-4 rounded-lg">
                                            <h3 className="text-sm font-medium text-foreground mb-2">
                                                {t('resendCode')}
                                            </h3>
                                            <p className="text-xs text-muted-foreground mb-3">
                                                {mfaType === 'email'
                                                    ? t('didNotReceiveEmail')
                                                    : t('didNotReceiveCode')}
                                            </p>
                                            <Button
                                                onClick={() => {
                                                    if (mfaType === 'email') {
                                                        handleSendEmail();
                                                    } else {
                                                        handleSendSms();
                                                    }
                                                }}
                                                disabled={isSmsLoading || mfaCountdown > 0}
                                                variant="outline"
                                                size="sm"
                                                className="w-full"
                                                type="button"
                                            >
                                                {isSmsLoading ? (
                                                    t('sending')
                                                ) : mfaCountdown > 0 ? (
                                                    t('resendAvailable', { seconds: mfaCountdown })
                                                ) : (
                                                    mfaType === 'email' ? t('resendEmailOtp') : t('resendCode')
                                                )}
                                            </Button>
                                        </div>

                                        {/* SMS 토큰 입력 폼 */}
                                        <form onSubmit={handleMfaSubmit} className="space-y-6">
                                            <div className="space-y-4">
                                                <div className="text-center">
                                                    <label className="block text-sm font-medium text-foreground mb-3">
                                                        {t('enterSixDigitCode')}
                                                    </label>
                                                    <div className="flex justify-center">
                                                        <InputOTP
                                                            maxLength={6}
                                                            value={mfaToken}
                                                            onChange={(value) => setMfaToken(value)}
                                                        >
                                                            <InputOTPGroup>
                                                                <InputOTPSlot index={0} />
                                                                <InputOTPSlot index={1} />
                                                                <InputOTPSlot index={2} />
                                                                <InputOTPSlot index={3} />
                                                                <InputOTPSlot index={4} />
                                                                <InputOTPSlot index={5} />
                                                            </InputOTPGroup>
                                                        </InputOTP>
                                                    </div>
                                                </div>
                                            </div>

                                            <Button
                                                type="submit"
                                                className="w-full"
                                                variant="samsung"
                                                disabled={isMfaLoading || mfaToken.length !== 6}
                                            >
                                                {isMfaLoading ? t('authenticating') : t('authenticationComplete')}
                                            </Button>
                                        </form>

                                        {/* 도움말 */}
                                        <div className="bg-yellow-50 dark:bg-yellow-900/20 p-3 rounded-lg border border-yellow-200 dark:border-yellow-800">
                                            <div className="flex">
                                                <div className="flex-shrink-0">
                                                    ⚠️
                                                </div>
                                                <div className="ml-2">
                                                    <h4 className="text-xs font-medium text-yellow-800 dark:text-yellow-300">
                                                        {t('didNotReceiveCode')}
                                                    </h4>
                                                    <div className="mt-1 text-xs text-yellow-700 dark:text-yellow-400">
                                                        <ul className="list-disc list-inside space-y-1">
                                                            <li>{t('checkPhoneNumber')}</li>
                                                            <li>{t('checkSpamFolder')}</li>
                                                            <li>{t('useResendButton')}</li>
                                                        </ul>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                )}

                                {/* 비밀번호 재설정 다이얼로그 */}
                                {showForgotPassword && !showMfaForm && (
                                    <div className="fixed inset-0 bg-black/50 dark:bg-black/70 flex items-center justify-center z-50">
                                        <div className="bg-card rounded-lg p-6 w-full max-w-md mx-4 border border-border">
                                            <div className="flex justify-between items-center mb-4">
                                                <h3 className="text-lg font-semibold text-foreground">{t('resetPassword')}</h3>
                                                <button
                                                    onClick={() => {
                                                        setShowForgotPassword(false);
                                                    }}
                                                    className="text-muted-foreground hover:text-foreground"
                                                >
                                                    ✕
                                                </button>
                                            </div>
                                            <form action={passwordResetAction} className="space-y-4">
                                                <div>
                                                    <p className="text-sm text-muted-foreground mb-3">
                                                        {t('resetDescription')}
                                                    </p>
                                                    <Input
                                                        name="email"
                                                        type="email"
                                                        placeholder={t('emailAddress')}
                                                        required
                                                    />
                                                </div>
                                                <div className="flex gap-2">
                                                    <Button
                                                        type="button"
                                                        variant="outline"
                                                        className="flex-1"
                                                        onClick={() => {
                                                            setShowForgotPassword(false);
                                                        }}
                                                    >
                                                        {t('cancel')}
                                                    </Button>
                                                    <Button
                                                        type="submit"
                                                        className="flex-1"
                                                    >
                                                        {t('sendResetLink')}
                                                    </Button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                )}

                                {/* Language Selector - MFA 화면에서는 숨김 */}
                                {!showMfaForm && (
                                    <div className="text-center text-sm mx-auto">
                                        <DropdownMenu>
                                            <DropdownMenuTrigger asChild>
                                                <Button variant="ghost" className="flex items-center gap-2">
                                                    <GlobeIcon className="h-4 w-4" />
                                                    <span>{currentLanguageText}</span>
                                                    <ChevronDownIcon className="h-4 w-4" />
                                                </Button>
                                            </DropdownMenuTrigger>
                                            <DropdownMenuContent align="end">
                                                <DropdownMenuRadioGroup
                                                    value={i18n.language}
                                                    onValueChange={(value) => handleChangeLanguage(value)}
                                                >
                                                    <DropdownMenuRadioItem value="en">
                                                        {t('languages.english')}
                                                    </DropdownMenuRadioItem>
                                                    <DropdownMenuRadioItem value="ko">
                                                        {t('languages.korean')}
                                                    </DropdownMenuRadioItem>
                                                </DropdownMenuRadioGroup>
                                            </DropdownMenuContent>
                                        </DropdownMenu>
                                    </div>
                                )}

                            {/* Terms - MFA 화면에서는 숨김 */}
                            {!showMfaForm && (
                                <div className="text-balance text-center text-xs text-muted-foreground [&_a]:underline [&_a]:underline-offset-4 hover:[&_a]:text-primary mt-4">
                                    {t("agreement")}{" "}
                                    <Link
                                        href={`/${lng}/privacy`}
                                        className="underline underline-offset-4 hover:text-primary"
                                    >
                                        {t("privacyPolicy")}
                                    </Link>
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    )
}