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

const GOOGLE_CLIENT_ID = import.meta.env.VITE_GOOGLE_CLIENT_ID || '';

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

  if (loading) {
    return (
      <div className="auth-loading">
        <div className="auth-loading__spinner" />
      </div>
    );
  }

  if (user) {
    return <Navigate to="/" replace />;
  }

  const handleSuccess = async (credentialResponse: { credential?: string }) => {
    if (!credentialResponse.credential) {
      setError('Google 인증 토큰을 받지 못했습니다.');
      return;
    }
    try {
      setError(null);
      await login(credentialResponse.credential);
    } catch (e) {
      setError(e instanceof Error ? e.message : '로그인에 실패했습니다.');
    }
  };

  return (
    <div className="auth-page">
      <div className="auth-card">
        <div className="auth-logo"><span style={{ position: 'relative' }}>GC WING<span style={{ position: 'absolute', right: -48, bottom: 0, color: '#F59E0B', fontSize: 12, fontWeight: 600 }}>demo</span></span></div>
        <div className="auth-title">조업감시 대시보드</div>
        <div className="auth-subtitle">@gcsc.co.kr 계정으로 로그인하세요</div>

        {error && <div className="auth-error">{error}</div>}

        <div className="auth-google-btn">
          <GoogleOAuthProvider clientId={GOOGLE_CLIENT_ID}>
            <GoogleLogin
              onSuccess={handleSuccess}
              onError={() => setError('Google 로그인에 실패했습니다.')}
              theme="filled_black"
              size="large"
              width="280"
            />
          </GoogleOAuthProvider>
        </div>

        {devLogin && (
          <button className="auth-dev-btn" onClick={devLogin}>
            DEV Mock 로그인
          </button>
        )}

        <div className="auth-footer">
          GC SI Team &middot; Wing Fleet Dashboard
        </div>
      </div>
    </div>
  );
}
