import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from './useAuth';

export default function Login() {
  const { login, loading, error, logout } = useAuth();
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [message, setMessage] = useState<string | null>(null);
  const isDev = import.meta.env.MODE !== 'production';
  const navigate = useNavigate();

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setMessage(null);
    try {
      await login(username, password);
      setMessage('Login erfolgreich');
      // Redirect to dashboard after successful login
      navigate('/');
    } catch (err) {
      setMessage(err instanceof Error ? err.message : 'Login fehlgeschlagen');
    }
  };

  return (
    <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '100vh' }}>
      <form onSubmit={handleSubmit} style={{ width: 360, padding: 24, border: '1px solid #ddd', borderRadius: 8, background: '#fff' }}>
        <h2 style={{ marginTop: 0 }}>Anmeldung</h2>
        {message && <div style={{ color: message.includes('erfolgreich') ? 'green' : 'crimson', marginBottom: 12 }}>{message}</div>}
        {error && <div style={{ color: 'crimson', marginBottom: 12 }}>{error}</div>}
        <div style={{ marginBottom: 12 }}>
          <label style={{ display: 'block', marginBottom: 4 }}>Benutzername</label>
          <input
            type="text"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            disabled={loading}
            style={{ width: '100%', padding: 8 }}
            autoFocus
          />
        </div>
        <div style={{ marginBottom: 12 }}>
          <label style={{ display: 'block', marginBottom: 4 }}>Passwort</label>
          <input
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            disabled={loading}
            style={{ width: '100%', padding: 8 }}
          />
        </div>
        <button type="submit" disabled={loading} style={{ width: '100%', padding: 10 }}>
          {loading ? 'Anmelden ...' : 'Anmelden'}
        </button>
        {isDev && (
          <button
            type="button"
            onClick={async () => {
              setMessage(null);
              try {
                const res = await fetch('/api/auth/dev-login-superadmin', {
                  method: 'POST',
                  credentials: 'include',
                });
                const data = await res.json();
                if (!res.ok || data.error) throw new Error(data.error || 'Dev-Login fehlgeschlagen');
                setMessage('Dev-Login erfolgreich (Superadmin)');
                // Refresh the page/state; the RequireAuth will render the app
                window.location.href = '/';
              } catch (err) {
                setMessage(err instanceof Error ? err.message : 'Dev-Login fehlgeschlagen');
              }
            }}
            disabled={loading}
            style={{ width: '100%', padding: 10, marginTop: 10 }}
          >
            Dev-Login (Superadmin)
          </button>
        )}
        <button
          type="button"
          onClick={async () => {
            try {
              await logout();
              setMessage('Abgemeldet.');
            } catch {
              // ignore
            }
          }}
          style={{ width: '100%', padding: 10, marginTop: 10, background: '#f5f5f5' }}
        >
          Abmelden & zurück zur Anmeldung
        </button>
      </form>
    </div>
  );
}
