import { useState } from 'react';
import { useNavigate, useSearchParams, Link } 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 [searchParams] = useSearchParams();
  const passwordChanged = searchParams.get('changed') === '1';
  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 {
      const portalUser = await customerLogin(email, password);
      // Einmalpasswort-Login → erzwungenes Passwort-Setzen vor Dashboard
      if (portalUser?.mustChangePassword) {
        navigate('/change-initial-password', { replace: true });
      } else {
        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>

        {passwordChanged && !error && (
          <div className="mb-4 p-4 bg-green-50 border border-green-200 text-green-700 rounded-lg text-sm">
            Passwort wurde geändert. Bitte mit dem neuen Passwort anmelden.
          </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>

          <div className="text-center">
            <Link
              to="/password-reset/request"
              className="text-sm text-blue-600 hover:text-blue-800 hover:underline"
            >
              Passwort vergessen?
            </Link>
          </div>
        </form>
      </Card>
    </div>
  );
}
