import { useState } from 'react';
import { GoogleLogin, GoogleOAuthProvider } from '@react-oauth/google';
import { Navigate } from 'react-router';
import { useAuth } from '../auth/useAuth';

const GOOGLE_CLIENT_ID =
  '295080817934-1uqaqrkup9jnslajkl1ngpee7gm249fv.apps.googleusercontent.com';

export function LoginPage() {
  const { user, login, devLogin, loading } = useAuth();
  const [error, setError] = useState<string | null>(null);

  if (loading) return null;
  if (user && user.status === 'ACTIVE') return <Navigate to="/" replace />;
  if (user && user.status === 'PENDING')
    return <Navigate to="/pending" replace />;

  const handleLogin = async (credential: string) => {
    setError(null);
    try {
      await login(credential);
    } catch (e) {
      setError(
        e instanceof Error && e.message
          ? e.message
          : '로그인에 실패했습니다. 다시 시도해주세요.',
      );
    }
  };

  return (
    <GoogleOAuthProvider clientId={GOOGLE_CLIENT_ID}>
      <div className="min-h-screen bg-gradient-to-br from-slate-900 via-blue-950 to-slate-900 flex items-center justify-center px-4">
        <div className="bg-surface rounded-2xl shadow-2xl p-10 max-w-sm w-full text-center">
          <div className="mb-6">
            <div className="w-16 h-16 bg-accent rounded-xl mx-auto mb-4 flex items-center justify-center">
              <span className="text-white text-2xl font-bold">GC</span>
            </div>
            <h1 className="text-2xl font-bold text-text-primary">
              GC SI 개발자 가이드
            </h1>
            <p className="text-text-muted mt-2 text-sm">
              @gcsc.co.kr 계정으로 로그인하세요
            </p>
          </div>
          {error && (
            <div className="mb-4 px-4 py-2.5 bg-danger/10 border border-danger/30 rounded-lg text-sm text-danger">
              {error}
            </div>
          )}
          <div className="flex justify-center">
            <GoogleLogin
              onSuccess={(res) => {
                if (res.credential) handleLogin(res.credential);
              }}
              onError={() => setError('Google 인증에 실패했습니다.')}
              theme="outline"
              size="large"
              width="280"
            />
          </div>
          {devLogin && (
            <button
              onClick={devLogin}
              className="mt-4 w-full px-4 py-2 bg-amber-500/10 text-amber-600 border border-amber-500/30 rounded-lg text-sm font-medium hover:bg-amber-500/20 cursor-pointer"
            >
              개발 모드 로그인 (Mock)
            </button>
          )}
          <p className="text-xs text-text-muted mt-6">
            GC SI 사내 개발환경 전용
          </p>
        </div>
      </div>
    </GoogleOAuthProvider>
  );
}
