import { useState, useEffect } from 'react';
import { shire } from '@/api/shireClient';

const ALLOWED_EMAIL = '3drays85@gmail.com';

export default function Login() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);
  const [denied, setDenied] = useState(false);

  // Check if already logged in
  useEffect(() => {
    shire.auth.isAuthenticated().then(async isAuth => {
      if (isAuth) {
        const user = await shire.auth.me();
        if (user?.email === ALLOWED_EMAIL) {
          window.location.href = '/';
        } else {
          await shire.auth.logout();
          setDenied(true);
        }
      }
    });
  }, []);

  const handleSubmit = async e => {
    e.preventDefault();
    setError('');
    setDenied(false);
    setLoading(true);
    try {
      await shire.auth.loginViaEmailPassword(email, password);
      const user = await shire.auth.me();
      if (user?.email !== ALLOWED_EMAIL) {
        await shire.auth.logout();
        setDenied(true);
        setLoading(false);
        return;
      }
      window.location.href = '/';
    } catch (err) {
      setError(err.message || 'Invalid email or password.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center" style={{ background: '#1a0a2e' }}>
      <div className="w-full max-w-md mx-4">
        <div className="bg-white rounded-2xl shadow-2xl p-8">
          {/* Header */}
          <div className="text-center mb-8">
            <div className="text-5xl mb-3">🖨️</div>
            <h1 className="text-2xl font-bold text-gray-900">Shire 3D Manager</h1>
            <p className="text-gray-500 text-sm mt-1">Your marketplace command centre</p>
          </div>

          {denied && (
            <div className="mb-5 p-3 rounded-lg bg-red-50 border border-red-200 text-red-700 text-sm text-center">
              Access denied. This is a private application.
            </div>
          )}
          {error && (
            <div className="mb-5 p-3 rounded-lg bg-red-50 border border-red-200 text-red-700 text-sm">
              {error}
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
              <input
                type="email"
                value={email}
                onChange={e => setEmail(e.target.value)}
                required
                autoFocus
                className="w-full px-4 py-3 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-orange-400"
                placeholder="you@example.com"
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-1">Password</label>
              <input
                type="password"
                value={password}
                onChange={e => setPassword(e.target.value)}
                required
                className="w-full px-4 py-3 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-orange-400"
                placeholder="••••••••"
              />
            </div>
            <button
              type="submit"
              disabled={loading}
              className="w-full py-3 rounded-lg text-white font-semibold text-sm transition-opacity disabled:opacity-60"
              style={{ background: '#f97316' }}
            >
              {loading ? 'Signing in…' : 'Sign In'}
            </button>
          </form>
        </div>
      </div>
    </div>
  );
}