import React, { useState, useEffect } from 'react';
import { GhostGridLogo } from './Header';
import { authFetch, saveSession } from '../lib/auth';
import { User } from '../types';
import { LogIn, Eye, EyeOff, AlertCircle } from 'lucide-react';

interface LoginPageProps {
  onLogin: (user: User) => void;
  onNavigateToRegister: () => void;
  authError?: string;
}

export default function LoginPage({ onLogin, onNavigateToRegister, authError }: LoginPageProps) {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [error, setError] = useState(authError || '');
  const [loading, setLoading] = useState(false);
  const [azureEnabled, setAzureEnabled] = useState(false);

  useEffect(() => {
    fetch('/api/auth/config')
      .then(r => r.json())
      .then(d => setAzureEnabled(Boolean(d.azureEnabled)))
      .catch(() => {});
  }, []);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setLoading(true);

    try {
      const res = await authFetch('/api/auth/login', {
        method: 'POST',
        body: JSON.stringify({ email, password }),
      });

      const data = await res.json();
      if (!res.ok) {
        setError(data.error || 'Login failed.');
        return;
      }

      saveSession(data.token, data.user);
      onLogin(data.user);
    } catch {
      setError('Could not reach the server. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-[#0B0F19] text-slate-100 font-sans flex items-center justify-center p-4">
      <div className="w-full max-w-md space-y-8">

        {/* Logo & Brand */}
        <div className="text-center space-y-3">
          <div className="inline-flex p-3 bg-slate-950/80 border border-slate-800 rounded-2xl shadow-[0_0_40px_rgba(6,182,212,0.15)]">
            <GhostGridLogo className="w-14 h-14" />
          </div>
          <div>
            <h1 className="text-2xl font-bold tracking-tight text-white">GhostGrid</h1>
            <p className="text-[10px] font-mono text-cyan-400 tracking-widest uppercase mt-0.5">
              BUILD AND CONTROL INVISIBLE INFRASTRUCTURE
            </p>
            <div className="flex items-center justify-center gap-1.5 mt-2">
              <span className="text-[9px] text-slate-500 font-sans">A product by</span>
              <span className="airit-badge inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[8px] font-sans font-semibold">
                <span className="w-1.5 h-1.5 rounded-sm bg-white/70 inline-block" />
                AirITSystems
              </span>
            </div>
          </div>
        </div>

        {/* Login Card */}
        <div className="bg-[#0F172A] border border-[#1E293B] rounded-2xl p-8 shadow-2xl space-y-6">
          <div>
            <h2 className="text-lg font-semibold text-white">Sign in</h2>
            <p className="text-xs text-slate-400 mt-1">Enter your credentials to access the platform.</p>
          </div>

          {error && (
            <div className="flex items-center gap-2 bg-red-950/60 border border-red-800/60 rounded-lg px-3 py-2.5 text-xs text-red-300">
              <AlertCircle className="w-4 h-4 shrink-0 text-red-400" />
              {error}
            </div>
          )}

          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="space-y-1.5">
              <label className="block text-xs font-semibold text-slate-300" htmlFor="email">
                Email address
              </label>
              <input
                id="email"
                type="email"
                autoComplete="email"
                required
                value={email}
                onChange={e => setEmail(e.target.value)}
                className="w-full bg-slate-900 border border-slate-700 rounded-lg px-3 py-2.5 text-sm text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/50 focus:border-cyan-500/50 transition-all"
                placeholder=""
              />
            </div>

            <div className="space-y-1.5">
              <label className="block text-xs font-semibold text-slate-300" htmlFor="password">
                Password
              </label>
              <div className="relative">
                <input
                  id="password"
                  type={showPassword ? 'text' : 'password'}
                  autoComplete="current-password"
                  required
                  value={password}
                  onChange={e => setPassword(e.target.value)}
                  className="w-full bg-slate-900 border border-slate-700 rounded-lg px-3 py-2.5 pr-10 text-sm text-white placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-cyan-500/50 focus:border-cyan-500/50 transition-all"
                  placeholder=""
                />
                <button
                  type="button"
                  onClick={() => setShowPassword(v => !v)}
                  className="absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 hover:text-slate-200 transition-colors"
                  tabIndex={-1}
                >
                  {showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                </button>
              </div>
            </div>

            <button
              type="submit"
              disabled={loading}
              className="w-full flex items-center justify-center gap-2 bg-cyan-600 hover:bg-cyan-500 disabled:bg-slate-700 disabled:text-slate-500 text-white font-semibold text-sm py-2.5 rounded-lg transition-all shadow-lg shadow-cyan-900/30"
            >
              {loading ? (
                <span className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" />
              ) : (
                <LogIn className="w-4 h-4" />
              )}
              {loading ? 'Signing in…' : 'Sign in'}
            </button>
          </form>

          {azureEnabled && (
            <>
              <div className="flex items-center gap-3">
                <div className="flex-1 h-px bg-slate-800" />
                <span className="text-[10px] font-mono text-slate-500 uppercase tracking-widest">or</span>
                <div className="flex-1 h-px bg-slate-800" />
              </div>
              <button
                type="button"
                onClick={() => { window.location.href = '/api/auth/azure'; }}
                className="w-full flex items-center justify-center gap-3 bg-slate-800 hover:bg-slate-700 border border-slate-700 hover:border-slate-600 text-white font-semibold text-sm py-2.5 rounded-lg transition-all"
              >
                {/* Microsoft M logo */}
                <svg width="18" height="18" viewBox="0 0 21 21" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                  <rect x="1" y="1" width="9" height="9" fill="#F25022" />
                  <rect x="11" y="1" width="9" height="9" fill="#7FBA00" />
                  <rect x="1" y="11" width="9" height="9" fill="#00A4EF" />
                  <rect x="11" y="11" width="9" height="9" fill="#FFB900" />
                </svg>
                Sign In with Entra ID
              </button>
            </>
          )}

          <p className="text-center text-xs text-slate-400">
            No account yet?{' '}
            <button
              onClick={onNavigateToRegister}
              className="text-cyan-400 hover:text-cyan-300 font-semibold transition-colors"
            >
              Create one
            </button>
          </p>
        </div>
      </div>
    </div>
  );
}
