// app/login/page.tsx
'use client';

import { useState } from 'react';
import { signIn } from 'next-auth/react';
import { useRouter, useSearchParams } from 'next/navigation';
import LoginForm from '@/components/auth/LoginForm';

type LoginValues = {
  identifier: string;
  password: string;
};

export default function LoginPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [errorMessage, setErrorMessage] = useState<string | null>(null);

  const callbackUrl = searchParams?.get('callbackUrl') ?? '/dashboard';

  const handleSubmit = async (values: LoginValues) => {
    setIsSubmitting(true);
    setErrorMessage(null);

    const res = await signIn('credentials', {
      redirect: false,
      email: values.identifier,
      password: values.password,
      callbackUrl,
    });

    setIsSubmitting(false);

    if (!res) {
      setErrorMessage('Unbekannter Fehler.');
      return;
    }

    if (res.error) {
      setErrorMessage('Anmeldung fehlgeschlagen. Bitte Zugangsdaten prüfen.');
      return;
    }

    router.push(res.url ?? callbackUrl);
  };

  return (
    <LoginForm
      onSubmit={handleSubmit}
      isSubmitting={isSubmitting}
      errorMessage={errorMessage}
    />
  );
}
