'use client';

import { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { RootState } from '@/store/store';
import { useRouter } from 'next/navigation';

export default function LoginPage() {
  const router = useRouter();
  const { isAuthenticated, isDevMode } = useSelector(
    (state: RootState) => state.auth
  );

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

  useEffect(() => {
    if (isAuthenticated) {
      router.push('/dashboard');
    }
  }, [isAuthenticated, router]);

  const handleMicrosoftLogin = () => {
    window.location.href = '/api/v1/auth/login';
  };

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

    try {
      const response = await fetch('/api/v1/auth/dev-login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password }),
      });

      if (response.ok) {
        window.location.href = '/dashboard';
      } else {
        const data = await response.json();
        setError(data.detail || 'Invalid credentials');
      }
    } catch {
      setError('Network error. Please try again.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen bg-[hsl(var(--surface))] flex items-center justify-center p-4">
      <div className="max-w-md w-full animate-scaleIn">
        <div className="bg-white rounded-2xl shadow-xl border border-border p-8">
          <div className="text-center mb-8">
            {/* Brand mark */}
            <div className="inline-flex items-center justify-center w-12 h-12 rounded-xl bg-[hsl(var(--primary-light))] mb-4">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
                <rect x="3" y="3" width="8" height="8" rx="1.5" fill="hsl(var(--primary))" />
                <rect x="13" y="3" width="8" height="8" rx="1.5" fill="hsl(var(--primary))" opacity="0.6" />
                <rect x="3" y="13" width="8" height="8" rx="1.5" fill="hsl(var(--primary))" opacity="0.4" />
                <rect x="13" y="13" width="8" height="8" rx="1.5" fill="hsl(var(--primary))" opacity="0.8" />
              </svg>
            </div>
            <h1 className="text-2xl font-bold text-foreground font-inter">
              OLIVER DeckForge
            </h1>
            <p className="text-sm text-muted-foreground mt-2">
              AI-powered presentation generation for enterprise teams
            </p>
          </div>

          {!isDevMode && (
            <button
              onClick={handleMicrosoftLogin}
              className="w-full flex items-center justify-center gap-3 bg-[#2F2F2F] text-white rounded-lg px-4 py-3 font-medium hover:bg-[#1a1a1a] transition-colors"
            >
              <svg width="20" height="20" viewBox="0 0 21 21" fill="none">
                <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 Microsoft
            </button>
          )}

          {isDevMode && (
            <form onSubmit={handleDevLogin} className="space-y-4">
              <div className="bg-[hsl(var(--warning)/0.08)] border border-[hsl(var(--warning)/0.3)] rounded-lg p-3 mb-4">
                <p className="text-xs text-[hsl(var(--warning))] font-medium">
                  Development Mode — Azure AD not configured
                </p>
              </div>

              <div>
                <label
                  htmlFor="email"
                  className="block text-sm font-medium text-foreground mb-1"
                >
                  Email
                </label>
                <input
                  id="email"
                  type="email"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  required
                  className="w-full rounded-lg border border-border px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-[hsl(var(--primary))] focus:border-transparent"
                  placeholder="admin@deckforge.dev"
                />
              </div>

              <div>
                <label
                  htmlFor="password"
                  className="block text-sm font-medium text-foreground mb-1"
                >
                  Password
                </label>
                <input
                  id="password"
                  type="password"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  required
                  className="w-full rounded-lg border border-border px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-[hsl(var(--primary))] focus:border-transparent"
                  placeholder="••••••••"
                />
              </div>

              {error && (
                <p className="text-sm text-[hsl(var(--error))]">{error}</p>
              )}

              <button
                type="submit"
                disabled={loading}
                className="w-full bg-[hsl(var(--primary))] text-white rounded-lg px-4 py-3 font-medium hover:bg-[hsl(var(--primary-hover))] transition-colors disabled:opacity-50"
              >
                {loading ? 'Signing in...' : 'Sign in (Development)'}
              </button>
            </form>
          )}
        </div>
      </div>
    </div>
  );
}
