'use client';

import { FormEvent, Suspense, useEffect, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useAuth0 } from '@auth0/auth0-react';
import { loginWithEmail, getSafeRedirectUrl } from '@/lib/auth';
import { useTranslation } from '@/lib/i18n';

// Google "G" logo SVG (official brand colours)
function GoogleLogo() {
  return (
    <svg width="18" height="18" viewBox="0 0 18 18" xmlns="http://www.w3.org/2000/svg">
      <path d="M17.64 9.205c0-.639-.057-1.252-.164-1.841H9v3.481h4.844a4.14 4.14 0 0 1-1.796 2.716v2.259h2.908c1.702-1.567 2.684-3.875 2.684-6.615z" fill="#4285F4"/>
      <path d="M9 18c2.43 0 4.467-.806 5.956-2.18l-2.908-2.259c-.806.54-1.837.86-3.048.86-2.344 0-4.328-1.584-5.036-3.711H.957v2.332A8.997 8.997 0 0 0 9 18z" fill="#34A853"/>
      <path d="M3.964 10.71A5.41 5.41 0 0 1 3.682 9c0-.593.102-1.17.282-1.71V4.958H.957A8.996 8.996 0 0 0 0 9c0 1.452.348 2.827.957 4.042l3.007-2.332z" fill="#FBBC05"/>
      <path d="M9 3.58c1.321 0 2.508.454 3.44 1.345l2.582-2.58C13.463.891 11.426 0 9 0A8.997 8.997 0 0 0 .957 4.958L3.964 6.29C4.672 4.163 6.656 3.58 9 3.58z" fill="#EA4335"/>
    </svg>
  );
}

function LoginPageContent() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const { t } = useTranslation();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  // Auth0 hook (safe to call unconditionally; only active when Auth0Provider wraps the tree)
  const auth0 = useAuth0();

  // Surface errors forwarded from the callback page query string
  useEffect(() => {
    const err = searchParams.get('error');
    if (err) setError(decodeURIComponent(err));
  }, [searchParams]);

  async function handleSubmit(e: FormEvent) {
    e.preventDefault();
    const trimmed = email.trim().toLowerCase();
    if (!trimmed || !trimmed.includes('@')) {
      setError(t('login.errorEmail'));
      return;
    }
    if (!password) {
      setError(t('login.errorPassword'));
      return;
    }
    setLoading(true);
    setError(null);
    try {
      await loginWithEmail(trimmed, password);
      router.replace(getSafeRedirectUrl(searchParams.get('redirect')));
    } catch (err: unknown) {
      const msg = err instanceof Error ? err.message : t('login.errorFailed');
      setError(msg);
    } finally {
      setLoading(false);
    }
  }

  function handleGoogleLogin() {
    if (!auth0.loginWithRedirect) return;
    setError(null);
    const redirectTo = getSafeRedirectUrl(searchParams.get('redirect'), '');
    if (redirectTo) {
      sessionStorage.setItem('investibook_login_redirect', redirectTo);
    }
    auth0.loginWithRedirect({
      authorizationParams: {
        connection: 'google-oauth2',
        redirect_uri: `${window.location.origin}/auth/callback`,        // Hint Google to show only @pingcap.com accounts in the account picker.
        // This is a UX hint only; domain enforcement happens in the Auth0 Post-Login Action.
        hd: 'pingcap.com',      },
    });
  }

  return (
    <div
      style={{
        minHeight: '100vh',
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        background: 'linear-gradient(135deg, #f5f7ff 0%, #eef0fb 100%)',
      }}
    >
      <div
        style={{
          background: '#fff',
          borderRadius: 16,
          boxShadow: '0 4px 32px rgba(92,95,188,0.10)',
          padding: '48px 40px 40px',
          width: 400,
          maxWidth: '90vw',
        }}
      >
        {/* Logo / Title */}
        <div style={{ textAlign: 'center', marginBottom: 32 }}>
          <div
            style={{
              width: 56,
              height: 56,
              borderRadius: 12,
              background: 'linear-gradient(135deg, #5c5fbc, #7c7fdc)',
              display: 'inline-flex',
              alignItems: 'center',
              justifyContent: 'center',
              marginBottom: 16,
            }}
          >
            <svg width="28" height="28" viewBox="0 0 28 28" fill="none">
              <rect x="4" y="2" width="20" height="24" rx="3" fill="white" fillOpacity="0.25" />
              <rect x="4" y="2" width="20" height="24" rx="3" stroke="white" strokeWidth="1.5" />
              <rect x="7" y="7" width="6" height="4" rx="1" fill="white" fillOpacity="0.7" />
              <rect x="15" y="7" width="6" height="1.5" rx="0.75" fill="white" fillOpacity="0.5" />
              <rect x="15" y="10" width="4" height="1.5" rx="0.75" fill="white" fillOpacity="0.5" />
              <rect x="7" y="14" width="14" height="1.5" rx="0.75" fill="white" fillOpacity="0.4" />
              <rect x="7" y="17" width="11" height="1.5" rx="0.75" fill="white" fillOpacity="0.4" />
              <rect x="7" y="20" width="12" height="1.5" rx="0.75" fill="white" fillOpacity="0.4" />
            </svg>
          </div>
          <h1 style={{ margin: 0, fontSize: 26, fontWeight: 700, color: '#1a1a2e', letterSpacing: '-0.5px' }}>
            Investibook
          </h1>
          <p style={{ margin: '6px 0 0', fontSize: 14, color: '#6b7280' }}>
            {t('login.tagline')}
          </p>
        </div>

        {/* Google SSO button */}
        <button
          type="button"
          onClick={handleGoogleLogin}
          disabled={auth0.isLoading}
          style={{
            width: '100%',
            padding: '11px 0',
            background: '#fff',
            color: '#374151',
            border: '1.5px solid #d1d5db',
            borderRadius: 8,
            fontSize: 15,
            fontWeight: 600,
            cursor: auth0.isLoading ? 'not-allowed' : 'pointer',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            gap: 10,
            transition: 'border-color 0.15s, box-shadow 0.15s',
          }}
          onMouseEnter={(e) => {
            e.currentTarget.style.borderColor = '#5c5fbc';
            e.currentTarget.style.boxShadow = '0 1px 6px rgba(92,95,188,0.15)';
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.borderColor = '#d1d5db';
            e.currentTarget.style.boxShadow = 'none';
          }}
        >
          <GoogleLogo />
          {t('login.continueWithGoogle')}
        </button>

        <div
          style={{
            display: 'flex',
            alignItems: 'center',
            margin: '20px 0',
            gap: 10,
            color: '#9ca3af',
            fontSize: 13,
          }}
        >
          <div style={{ flex: 1, height: 1, background: '#e5e7eb' }} />
          {t('login.or')}
          <div style={{ flex: 1, height: 1, background: '#e5e7eb' }} />
        </div>

        {/* Email form */}
        <form onSubmit={handleSubmit}>
          <label
            htmlFor="email"
            style={{ display: 'block', fontSize: 14, fontWeight: 600, color: '#374151', marginBottom: 6 }}
          >
            {t('login.emailLabel')}
          </label>
          <input
            id="email"
            type="email"
            autoFocus
            placeholder=""
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            disabled={loading}
            style={{
              width: '100%',
              boxSizing: 'border-box',
              padding: '10px 14px',
              border: error ? '1.5px solid #e53e3e' : '1.5px solid #d1d5db',
              borderRadius: 8,
              fontSize: 15,
              outline: 'none',
              transition: 'border-color 0.15s',
              background: loading ? '#f9fafb' : '#fff',
            }}
            onFocus={(e) => (e.currentTarget.style.borderColor = '#5c5fbc')}
            onBlur={(e) => (e.currentTarget.style.borderColor = error ? '#e53e3e' : '#d1d5db')}
          />

          <label
            htmlFor="password"
            style={{ display: 'block', fontSize: 14, fontWeight: 600, color: '#374151', marginBottom: 6, marginTop: 16 }}
          >
            {t('login.passwordLabel')}
          </label>
          <input
            id="password"
            type="password"
            placeholder=""
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            disabled={loading}
            style={{
              width: '100%',
              boxSizing: 'border-box',
              padding: '10px 14px',
              border: error ? '1.5px solid #e53e3e' : '1.5px solid #d1d5db',
              borderRadius: 8,
              fontSize: 15,
              outline: 'none',
              transition: 'border-color 0.15s',
              background: loading ? '#f9fafb' : '#fff',
            }}
            onFocus={(e) => (e.currentTarget.style.borderColor = '#5c5fbc')}
            onBlur={(e) => (e.currentTarget.style.borderColor = error ? '#e53e3e' : '#d1d5db')}
          />

          {error && (
            <p style={{ margin: '6px 0 0', fontSize: 13, color: '#e53e3e' }}>{error}</p>
          )}

          <button
            type="submit"
            disabled={loading}
            style={{
              marginTop: 20,
              width: '100%',
              padding: '11px 0',
              background: loading ? '#a5a7dc' : 'linear-gradient(135deg, #5c5fbc, #7c7fdc)',
              color: '#fff',
              border: 'none',
              borderRadius: 8,
              fontSize: 15,
              fontWeight: 600,
              cursor: loading ? 'not-allowed' : 'pointer',
              transition: 'opacity 0.15s',
            }}
          >
            {loading ? t('login.signingIn') : t('login.signIn')}
          </button>
        </form>

        <p style={{ marginTop: 24, fontSize: 13, color: '#9ca3af', textAlign: 'center' }}>
          {t('login.contactAdmin')}
        </p>
      </div>
    </div>
  );
}

export default function LoginPage() {
  return (
    <Suspense>
      <LoginPageContent />
    </Suspense>
  );
}
