import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';
import Button from '../components/ui/Button';
import Input from '../components/ui/Input';
import Card from '../components/ui/Card';

export default function Login() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const { login, customerLogin } = useAuth();
  const navigate = useNavigate();

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError(''); // Fehler nur beim Klick auf Login löschen
    setIsLoading(true);

    try {
      // Erst Mitarbeiter-Login versuchen
      await login(email, password);
      navigate('/');
      return;
    } catch {
      // Mitarbeiter-Login fehlgeschlagen, versuche Kunden-Login
    }

    try {
      await customerLogin(email, password);
      navigate('/');
    } catch {
      // Beide fehlgeschlagen
      setError('Ungültige Anmeldedaten');
      setIsLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-gray-100">
      <Card className="w-full max-w-md">
        <div className="text-center mb-8">
          <h1 className="text-2xl font-bold text-gray-900">OpenCRM</h1>
          <p className="text-gray-600 mt-2">Melden Sie sich an</p>
        </div>

        {error && (
          <div className="mb-4 p-4 bg-red-50 border border-red-200 text-red-700 rounded-lg">
            {error}
          </div>
        )}

        <form onSubmit={handleSubmit} className="space-y-4">
          <Input
            label="E-Mail"
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
            autoComplete="email"
          />

          <Input
            label="Passwort"
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            required
            autoComplete="current-password"
          />

          <Button type="submit" className="w-full" disabled={isLoading}>
            {isLoading ? 'Anmeldung...' : 'Anmelden'}
          </Button>
        </form>
      </Card>
    </div>
  );
}
