'use client';

import { useState } from 'react';
import { createBrowserClient } from '@supabase/ssr'
import { useRouter } from 'next/navigation';
import Link from 'next/link';

export default function LoginPage() {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [isSignUp, setIsSignUp] = useState(false);
    const [loading, setLoading] = useState(false);
    const router = useRouter();

    const supabase = createBrowserClient(
        process.env.NEXT_PUBLIC_SUPABASE_URL!,
        process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!
    );

    const handleAuth = async (e: React.FormEvent) => {
        e.preventDefault();
        setLoading(true);

        if (isSignUp) {
            const { data, error } = await supabase.auth.signUp({
                email,
                password,
                options: {
                    emailRedirectTo: `${window.location.origin}/auth/callback`,
                }
            });
            if (error) {
                alert('회원가입 실패: ' + error.message);
            } else if (data.user && data.user.identities && data.user.identities.length === 0) {
                alert('이미 가입된 이메일입니다. 로그인해주세요.');
            } else {
                alert('가입이 완료되었습니다! 이메일 인증 후 로그인해주세요.');
                setIsSignUp(false);
            }
        } else {
            const { error } = await supabase.auth.signInWithPassword({
                email,
                password,
            });
            if (error) {
                alert('로그인 실패: ' + error.message);
            } else {
                router.push('/mypage');
                router.refresh();
            }
        }
        setLoading(false);
    };

    const handleSocialLogin = async (provider: 'google' | 'kakao') => {
        const { error } = await supabase.auth.signInWithOAuth({
            provider,
            options: {
                redirectTo: `${window.location.origin}/auth/callback`,
            },
        });
        if (error) alert('소셜 로그인 오류: ' + error.message);
    };

    return (
        <div className="min-h-screen cosmic-pattern flex items-center justify-center p-4">
            <div className="w-full max-w-md">
                {/* 로고 */}
                <Link href="/" className="flex items-center justify-center space-x-2 mb-8">
                    <div className="w-12 h-12 bg-gradient-to-br from-[#d4af37] to-[#F3E7E3] rounded-lg flex items-center justify-center shadow-lg">
                        <span className="text-[#173658] text-2xl font-bold">사</span>
                    </div>
                    <span className="text-white text-2xl font-bold">사주포춘</span>
                </Link>

                <div className="glass-panel-light rounded-2xl shadow-2xl p-8">
                    <div className="text-center mb-8">
                        <h1 className="text-3xl font-bold text-[#173658] mb-2">
                            {isSignUp ? '회원가입' : '로그인'}
                        </h1>
                        <p className="text-[#5d6d7e]">사주 기록을 저장하고 언제든 다시 확인하세요</p>
                    </div>

                    <form onSubmit={handleAuth} className="space-y-4 mb-6">
                        <div>
                            <label htmlFor="email" className="block text-sm font-bold text-[#173658] mb-2">
                                이메일 주소
                            </label>
                            <input
                                id="email"
                                type="email"
                                placeholder="name@example.com"
                                className="w-full px-4 py-3 rounded-lg border-2 border-[#173658]/20 focus:ring-2 focus:ring-[#173658] focus:border-[#173658] outline-none transition bg-white"
                                value={email}
                                onChange={(e) => setEmail(e.target.value)}
                                required
                            />
                        </div>
                        <div>
                            <label htmlFor="password" className="block text-sm font-bold text-[#173658] mb-2">
                                비밀번호
                            </label>
                            <input
                                id="password"
                                type="password"
                                placeholder="••••••••"
                                className="w-full px-4 py-3 rounded-lg border-2 border-[#173658]/20 focus:ring-2 focus:ring-[#173658] focus:border-[#173658] outline-none transition bg-white"
                                value={password}
                                onChange={(e) => setPassword(e.target.value)}
                                required
                                minLength={6}
                            />
                        </div>
                        <button
                            type="submit"
                            disabled={loading}
                            className="w-full bg-[#173658] hover:bg-[#1e426a] text-white font-bold py-3 px-4 rounded-lg transition disabled:opacity-50 shadow-lg hover:shadow-xl"
                        >
                            {loading ? '처리 중...' : (isSignUp ? '회원가입' : '로그인')}
                        </button>
                    </form>

                    <div className="text-center mb-6">
                        <button
                            type="button"
                            className="text-sm text-[#173658] hover:text-[#1e426a] font-bold"
                            onClick={() => setIsSignUp(!isSignUp)}
                        >
                            {isSignUp ? '이미 계정이 있으신가요? 로그인' : '계정이 없으신가요? 회원가입'}
                        </button>
                    </div>

                    <div className="relative my-6">
                        <div className="absolute inset-0 flex items-center">
                            <div className="w-full border-t border-[#173658]/20"></div>
                        </div>
                        <div className="relative flex justify-center text-sm">
                            <span className="px-2 bg-white text-[#5d6d7e]">또는 소셜 로그인</span>
                        </div>
                    </div>

                    <div className="grid grid-cols-2 gap-3">
                        <button
                            onClick={() => handleSocialLogin('google')}
                            className="flex items-center justify-center px-4 py-2 border-2 border-[#173658]/20 rounded-lg hover:bg-[#F3E7E3] transition font-medium text-[#173658]"
                        >
                            <span>Google</span>
                        </button>
                        <button
                            onClick={() => handleSocialLogin('kakao')}
                            className="flex items-center justify-center px-4 py-2 bg-[#FEE500] border-2 border-[#FEE500] rounded-lg hover:bg-[#FDD835] transition font-medium"
                        >
                            <span className="text-[#000000bd]">Kakao</span>
                        </button>
                    </div>

                    <div className="mt-6 text-center">
                        <Link href="/" className="text-sm text-[#5d6d7e] hover:text-[#173658] transition">
                            홈으로 돌아가기
                        </Link>
                    </div>
                </div>
            </div>
        </div>
    );
}
