'use client';

import { useState, Suspense } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useAuth } from '@/contexts/AuthContext';
import { trackLogin } from '@/lib/analytics';
import { Wordmark } from '@/components/vyndr';
import { GoogleIcon, AppleIcon, XIcon } from '@/components/OAuthIcons';

// Session 14 — small helper so each OAuth button has the same icon+label
// rhythm without inlining the flex container three times.
function ProviderButton({ provider, label, disabled, onClick, children }: {
  provider: 'google' | 'apple' | 'twitter';
  label: string;
  disabled: boolean;
  onClick: () => void;
  children: React.ReactNode;
}) {
  return (
    <button
      onClick={onClick}
      disabled={disabled}
      aria-label={`Continue with ${label}`}
      className="btn-ghost"
      style={{
        width: '100%',
        padding: 12,
        display: 'inline-flex',
        alignItems: 'center',
        justifyContent: 'center',
        gap: 10,
      }}
      data-provider={provider}
    >
      {children}
      <span>Continue with {label}</span>
    </button>
  );
}

function LoginInner() {
  const router = useRouter();
  const search = useSearchParams();
  const next = search.get('next') || '/dashboard';
  const { signIn, signInWithProvider } = useAuth();

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [busy, setBusy] = useState(false);

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setBusy(true);
    setError('');
    const { error: err } = await signIn(email, password);
    setBusy(false);
    if (err) {
      setError(err);
      return;
    }
    trackLogin({ method: 'password' });
    router.replace(next);
  };

  // Session 13 — generic OAuth dispatch. Apple + X providers must be
  // configured in the Supabase dashboard (Apple needs a Service ID +
  // private key; X needs OAuth 2.0 client creds) before the redirect
  // succeeds. Unconfigured providers return an inline error string
  // instead of silently failing.
  const handleOAuth = async (provider: 'google' | 'apple' | 'twitter') => {
    setBusy(true);
    setError('');
    const { error: err } = await signInWithProvider(provider);
    if (err) {
      setError(err);
      setBusy(false);
    }
    // On success the page redirects to the provider; no state change here.
  };

  return (
    <section className="scanlines" style={{ minHeight: '80vh', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '32px 16px', position: 'relative' }}>
      <div className="fade-in" style={{ width: '100%', maxWidth: 420, padding: 32, background: 'var(--bg-1)', border: '1px solid var(--border-hi)', borderRadius: 12, position: 'relative' }}>
        <a
          href="/"
          style={{ display: 'flex', justifyContent: 'center', color: 'var(--text-0)', textDecoration: 'none', marginBottom: 24 }}
          aria-label="VYNDR — home"
        >
          <Wordmark size="md" cursor beta />
        </a>

        <h1 className="mono" style={{ fontSize: 18, fontWeight: 800, textAlign: 'center', marginBottom: 6, letterSpacing: '0.04em' }}>ACCESS THE SIGNAL</h1>
        <p className="mono" style={{ textAlign: 'center', color: 'var(--text-1)', fontSize: 12.5, marginBottom: 24 }}>
          Welcome back. Let&apos;s read something.
        </p>

        <div style={{ display: 'grid', gap: 8, marginBottom: 16 }}>
          <ProviderButton provider="google" label="Google" disabled={busy} onClick={() => handleOAuth('google')}>
            <GoogleIcon />
          </ProviderButton>
          <ProviderButton provider="apple" label="Apple" disabled={busy} onClick={() => handleOAuth('apple')}>
            <AppleIcon />
          </ProviderButton>
          <ProviderButton provider="twitter" label="X" disabled={busy} onClick={() => handleOAuth('twitter')}>
            <XIcon />
          </ProviderButton>
        </div>

        <div style={dividerStyle}>
          <span style={dividerLine} />
          <span className="mono" style={{ fontSize: 11, color: 'var(--text-tertiary)', letterSpacing: '0.08em' }}>OR</span>
          <span style={dividerLine} />
        </div>

        <form onSubmit={handleLogin} style={{ display: 'grid', gap: 12 }}>
          <div>
            <label className="mono" style={labelStyle}>Email</label>
            <input
              type="email"
              required
              autoComplete="email"
              className="input-field"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
            />
          </div>
          <div>
            <label className="mono" style={labelStyle}>Password</label>
            <input
              type="password"
              required
              autoComplete="current-password"
              className="input-field"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
            />
            <a href="/forgot-password" style={{ display: 'inline-block', marginTop: 8, fontSize: 12, color: 'var(--text-secondary)', textDecoration: 'none' }}>
              Forgot password?
            </a>
          </div>

          {error && (
            <p style={{ color: 'var(--grade-d)', fontSize: 13, margin: 0 }}>{error}</p>
          )}

          <button type="submit" disabled={busy} className="btn-primary" style={{ padding: 14, marginTop: 4 }}>
            {busy ? 'Logging in…' : 'Log in'}
          </button>
        </form>

        <p style={{ textAlign: 'center', fontSize: 13, color: 'var(--text-secondary)', marginTop: 20 }}>
          No account?{' '}
          <a href={`/signup${next ? `?next=${encodeURIComponent(next)}` : ''}`} style={{ color: 'var(--grade-a)' }}>
            Sign up free
          </a>
        </p>
      </div>
    </section>
  );
}

export default function LoginPage() {
  return (
    <Suspense fallback={null}>
      <LoginInner />
    </Suspense>
  );
}

const labelStyle: React.CSSProperties = {
  display: 'block',
  fontSize: 11,
  fontWeight: 700,
  letterSpacing: '0.08em',
  textTransform: 'uppercase',
  color: 'var(--text-tertiary)',
  marginBottom: 6,
};

const dividerStyle: React.CSSProperties = {
  display: 'grid',
  gridTemplateColumns: '1fr auto 1fr',
  gap: 12,
  alignItems: 'center',
  margin: '16px 0',
};

const dividerLine: React.CSSProperties = {
  height: 1,
  background: 'var(--border)',
};
