'use client';

import { FormEvent, useState, useEffect } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { useRouter } from 'next/navigation';

export default function AuthPage() {
  const { login, register, isLoading, user } = useAuth();
  const router = useRouter();
  const [mode, setMode] = useState<'login' | 'register'>('login');
  const [email, setEmail] = useState('');
  const [name, setName] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState<string | null>(null);

  // Redirect if already logged in
  useEffect(() => {
    if (user) {
      router.push('/dashboard');
    }
  }, [user, router]);

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    setError(null);
    try {
      if (mode === 'login') {
        await login(email, password);
      } else {
        await register(email, password, name);
      }
      // Will auto-redirect via useEffect when user state updates
    } catch (err: any) {
      setError(err.message || 'Something went wrong');
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-[#050316] text-white">
      <div className="w-full max-w-md space-y-6 p-8 bg-white/5 rounded-3xl border border-white/10">
        <div className="text-center space-y-2">
          <h1 className="text-3xl font-bold">HolaCompi</h1>
          <p className="text-sm text-gray-300">
            {mode === 'login'
              ? 'Welcome back, sign in to continue'
              : 'Create your HolaCompi account'}
          </p>
        </div>

        <div className="flex justify-center space-x-2 bg-white/5 rounded-full p-1">
          <button
            type="button"
            onClick={() => setMode('login')}
            className={`flex-1 py-2 text-sm rounded-full ${
              mode === 'login' ? 'bg-white text-black' : 'text-gray-300'
            }`}
          >
            Login
          </button>
          <button
            type="button"
            onClick={() => setMode('register')}
            className={`flex-1 py-2 text-sm rounded-full ${
              mode === 'register' ? 'bg-white text-black' : 'text-gray-300'
            }`}
          >
            Register
          </button>
        </div>

        {error && (
          <div className="text-sm text-red-400 bg-red-400/10 border border-red-400/40 rounded-lg px-3 py-2">
            {error}
          </div>
        )}

        {user && (
          <div className="text-xs text-green-400 bg-green-400/10 border border-green-400/40 rounded-lg px-3 py-2">
            Logged in as {user.email}
          </div>
        )}

        <form onSubmit={handleSubmit} className="space-y-4">
          {mode === 'register' && (
            <div>
              <label className="block text-sm mb-1">Name</label>
              <input
                type="text"
                className="w-full rounded-lg px-3 py-2 bg-black/30 border border-white/10 text-sm outline-none focus:border-purple-400"
                value={name}
                onChange={e => setName(e.target.value)}
                required
              />
            </div>
          )}

          <div>
            <label className="block text-sm mb-1">Email</label>
            <input
              type="email"
              className="w-full rounded-lg px-3 py-2 bg-black/30 border border-white/10 text-sm outline-none focus:border-purple-400"
              value={email}
              onChange={e => setEmail(e.target.value)}
              required
            />
          </div>

          <div>
            <label className="block text-sm mb-1">Password</label>
            <input
              type="password"
              className="w-full rounded-lg px-3 py-2 bg-black/30 border border-white/10 text-sm outline-none focus:border-purple-400"
              value={password}
              onChange={e => setPassword(e.target.value)}
              required
            />
          </div>

          <button
            type="submit"
            disabled={isLoading}
            className="w-full py-2.5 rounded-lg bg-purple-500 hover:bg-purple-600 disabled:opacity-70 text-sm font-medium"
          >
            {isLoading
              ? 'Please wait...'
              : mode === 'login'
              ? 'Login'
              : 'Create account'}
          </button>
        </form>
      </div>
    </div>
  );
}
