import { useState, useEffect, useMemo, type FormEvent } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import api from '../api/client';
import { useAuth } from './AuthContext';
import styles from './LoginPage.module.css';

interface BrandingData {
  logo: string | null;
  loginBgType: 'gradient' | 'solid' | 'image' | null;
  loginBgColor1: string | null;
  loginBgColor2: string | null;
  loginBgImage: string | null;
}

export function LoginPage() {
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();
  const { login } = useAuth();

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [totpCode, setTotpCode] = useState('');
  const [showTotp, setShowTotp] = useState(false);
  const [error, setError] = useState('');
  const [isSubmitting, setIsSubmitting] = useState(false);

  // SSO-Fehler aus URL-Parameter lesen (Redirect von Backend)
  useEffect(() => {
    const ssoError = searchParams.get('sso_error');
    if (ssoError) {
      setError(ssoError);
    }
  }, [searchParams]);

  // Branding laden (kein Auth-Guard auf diesem Endpoint)
  const { data: branding } = useQuery<BrandingData>({
    queryKey: ['settings', 'branding'],
    queryFn: async () => {
      const res = await api.get<BrandingData>('/settings/branding');
      return res.data;
    },
    staleTime: 5 * 60 * 1000,
    retry: false,
  });

  // Dynamischer Hintergrund basierend auf Branding
  const containerStyle = useMemo((): React.CSSProperties => {
    if (!branding) return {};
    const type = branding.loginBgType || 'gradient';
    if (type === 'gradient') {
      const c1 = branding.loginBgColor1 || '#1a56db';
      const c2 = branding.loginBgColor2 || '#1e3a5f';
      return { background: `linear-gradient(135deg, ${c1} 0%, ${c2} 100%)` };
    }
    if (type === 'solid') {
      return { background: branding.loginBgColor1 || '#1a56db' };
    }
    if (type === 'image' && branding.loginBgImage) {
      return { background: `url(${branding.loginBgImage}) center/cover no-repeat` };
    }
    return {};
  }, [branding]);

  // SSO-Status abfragen: Ist Microsoft SSO konfiguriert?
  const { data: ssoStatus } = useQuery<{ microsoft: boolean }>({
    queryKey: ['sso', 'status'],
    queryFn: async () => {
      const res = await api.get<{ microsoft: boolean }>('/auth/sso/status');
      return res.data;
    },
    staleTime: 5 * 60 * 1000, // 5 Minuten cachen
    retry: false,
  });

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

    try {
      const result = await login(
        email,
        password,
        showTotp ? totpCode : undefined,
      );

      if (result.requiresTwoFactor) {
        setShowTotp(true);
        setIsSubmitting(false);
        return;
      }

      if (result.success) {
        navigate('/');
      } else {
        setError(result.error ?? 'Login fehlgeschlagen');
      }
    } finally {
      setIsSubmitting(false);
    }
  };

  const handleMicrosoftLogin = () => {
    // Direkt zum Backend SSO-Endpoint redirecten
    window.location.href = '/api/v1/auth/sso/microsoft';
  };

  return (
    <div className={styles.container} style={containerStyle}>
      <div className={styles.card}>
        <div className={styles.logo}>
          {branding?.logo ? (
            <img src={branding.logo} alt="Logo" className={styles.logoImage} />
          ) : (
            <h1>INSIGHT</h1>
          )}
          <p>Business Platform</p>
        </div>

        <form onSubmit={handleSubmit} className={styles.form}>
          {error && <div className={styles.error}>{error}</div>}

          <div className={styles.field}>
            <label htmlFor="email">E-Mail</label>
            <input
              id="email"
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              placeholder="ihre@email.de"
              required
              autoFocus
              disabled={showTotp}
            />
          </div>

          <div className={styles.field}>
            <label htmlFor="password">Passwort</label>
            <input
              id="password"
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              placeholder="Passwort eingeben"
              required
              minLength={8}
              disabled={showTotp}
            />
          </div>

          {showTotp && (
            <div className={styles.field}>
              <label htmlFor="totp">2FA-Code</label>
              <input
                id="totp"
                type="text"
                value={totpCode}
                onChange={(e) => setTotpCode(e.target.value)}
                placeholder="6-stelliger Code"
                maxLength={6}
                pattern="[0-9]{6}"
                required
                autoFocus
              />
              <small>Code aus Ihrer Authenticator-App eingeben</small>
            </div>
          )}

          <button
            type="submit"
            className={styles.button}
            disabled={isSubmitting}
          >
            {isSubmitting ? 'Anmeldung...' : 'Anmelden'}
          </button>
        </form>

        {/* Microsoft SSO Button */}
        {ssoStatus?.microsoft && (
          <>
            <div className={styles.divider}>
              <span>oder</span>
            </div>
            <button
              type="button"
              className={styles.ssoButton}
              onClick={handleMicrosoftLogin}
            >
              <svg
                width="20"
                height="20"
                viewBox="0 0 21 21"
                xmlns="http://www.w3.org/2000/svg"
              >
                <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>
              Mit Microsoft anmelden
            </button>
          </>
        )}
      </div>
    </div>
  );
}
