'use client';

import { useState } from 'react';
import Image from 'next/image';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { Eye, EyeOff } from 'lucide-react';
import { api, ApiError } from '@/lib/api';
import { useGoogleLogin } from '@react-oauth/google';

const hasGoogleClientId = !!process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID;

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

  function GoogleOAuthButton() {
    const googleLogin = useGoogleLogin({
      scope: 'openid email profile',
      onSuccess: async (tokenResponse: any) => {
        try {
          setError('');
          setLoading(true);
          const credential = (tokenResponse as any)?.access_token;
          if (!credential) {
            setError('Erreur de connexion Google');
            return;
          }
          const data = await api.auth.oauth('google', { credential });
          localStorage.setItem('ol_token', data.accessToken);
          if ((data as any).refreshToken) {
            localStorage.setItem('ol_refresh_token', (data as any).refreshToken);
          }
          router.push('/play');
        } catch {
          setError('Erreur de connexion Google');
        } finally {
          setLoading(false);
        }
      },
      onError: () => setError('Connexion Google annulée'),
    });

    return (
      <button type="button" onClick={() => googleLogin()} disabled={loading} className="flex-1 flex items-center justify-center gap-2 py-2.5 rounded-lg text-sm disabled:opacity-50"
        style={{ background: 'var(--bg-tertiary)', color: 'var(--text-primary)', border: '1px solid var(--border-dark)' }}>
        <svg width="16" height="16" viewBox="0 0 24 24"><path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 01-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z" fill="#4285F4" /><path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853" /><path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05" /><path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335" /></svg>
        Google
      </button>
    );
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setLoading(true);
    try {
      const data = await api.auth.login(email, password);
      localStorage.setItem('ol_token', data.accessToken);
      if ((data as any).refreshToken) {
        localStorage.setItem('ol_refresh_token', (data as any).refreshToken);
      }
      router.push('/play');
    } catch (err: unknown) {
      if (err instanceof ApiError) {
        setError(err.message || 'Erreur de connexion');
      } else if (err instanceof Error) {
        setError(err.message || 'Erreur de connexion');
      } else {
        setError('Erreur de connexion');
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center px-4 py-12" style={{ background: 'var(--bg-primary)' }}>
      <div className="w-full max-w-md panel-glass rounded-2xl p-8" style={{ boxShadow: '0 0 60px rgba(196,30,30,0.15)' }}>
        <div className="text-center mb-8">
          <Link href="/"><Image src="/images/logo.png" alt="Logo" width={80} height={80} className="mx-auto mb-4" /></Link>
          <h1 className="font-gothic text-2xl text-gold-gradient">Connexion</h1>
          <p className="text-sm mt-1" style={{ color: 'var(--text-muted)' }}>Reprends le contrôle de ton empire</p>
        </div>

        {error && (
          <div className="mb-4 p-3 rounded text-sm" style={{ background: 'rgba(196,30,30,0.15)', color: 'var(--color-red-light)', border: '1px solid var(--color-red-dark)' }}>
            {error}
          </div>
        )}

        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <label className="block text-xs mb-1" style={{ color: 'var(--text-secondary)' }}>Email</label>
            <input type="email" required value={email} onChange={(e) => setEmail(e.target.value)}
              className="w-full px-4 py-2.5 rounded-lg text-sm outline-none"
              style={{ background: 'var(--bg-tertiary)', color: 'var(--text-primary)', border: '1px solid var(--border-dark)' }}
              placeholder="ton@email.com" />
          </div>

          <div className="relative">
            <label className="block text-xs mb-1" style={{ color: 'var(--text-secondary)' }}>Mot de passe</label>
            <input type={showPassword ? 'text' : 'password'} required value={password} onChange={(e) => setPassword(e.target.value)}
              className="w-full px-4 py-2.5 rounded-lg text-sm outline-none pr-10"
              style={{ background: 'var(--bg-tertiary)', color: 'var(--text-primary)', border: '1px solid var(--border-dark)' }}
              placeholder="Ton mot de passe" />
            <button type="button" onClick={() => setShowPassword(!showPassword)} className="absolute right-3 top-8" style={{ color: 'var(--text-muted)' }}>
              {showPassword ? <EyeOff size={16} /> : <Eye size={16} />}
            </button>
          </div>

          <div className="flex justify-end">
            <Link href="/auth/reset" className="text-xs hover:underline" style={{ color: 'var(--color-gold)' }}>Mot de passe oublié ?</Link>
          </div>

          {/* OAuth */}
          <div className="flex gap-3">
            {hasGoogleClientId ? (
              <GoogleOAuthButton />
            ) : (
              <button type="button" disabled title="Google OAuth non configuré" className="flex-1 flex items-center justify-center gap-2 py-2.5 rounded-lg text-sm opacity-50 cursor-not-allowed"
                style={{ background: 'var(--bg-tertiary)', color: 'var(--text-primary)', border: '1px solid var(--border-dark)' }}>
                <svg width="16" height="16" viewBox="0 0 24 24"><path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 01-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z" fill="#4285F4" /><path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853" /><path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05" /><path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335" /></svg>
                Google
              </button>
            )}
            <button type="button" disabled title="Bientôt disponible" className="flex-1 flex items-center justify-center gap-2 py-2.5 rounded-lg text-sm opacity-50 cursor-not-allowed" style={{ background: '#1877F2', color: 'white' }}>
              <svg width="16" height="16" fill="white" viewBox="0 0 24 24"><path d="M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z"/></svg>
              Facebook
            </button>
          </div>

          <button type="submit" disabled={loading}
            className="w-full py-3 rounded-lg font-bold text-sm transition-all hover:scale-[1.02] disabled:opacity-50"
            style={{ background: 'linear-gradient(135deg, var(--color-red-dark), var(--color-red))', color: 'white', boxShadow: '0 4px 20px rgba(196,30,30,0.3)' }}>
            {loading ? 'Connexion...' : 'Se connecter'}
          </button>
        </form>

        <p className="text-center text-xs mt-6" style={{ color: 'var(--text-muted)' }}>
          Pas encore de compte ?{' '}
          <Link href="/auth/register" style={{ color: 'var(--color-gold)' }} className="hover:underline">Créer un compte</Link>
        </p>
      </div>
    </div>
  );
}
