'use client';

import { useState, FormEvent } from 'react';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { Card } from '@/components/ui/Card';
import { useToast } from '@/components/ui/Toast';
import { useI18n } from '@/lib/i18n';
import { login as apiLogin } from '@/lib/api';

export default function LoginPage() {
  const router = useRouter();
  const { t } = useI18n();
  const { showToast } = useToast();

  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [errors, setErrors] = useState<{ email?: string; password?: string }>({});

  const validate = (): boolean => {
    const newErrors: typeof errors = {};
    if (!email) {
      newErrors.email = t('auth.error.emailRequired');
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      newErrors.email = t('auth.error.emailInvalid');
    }
    if (!password) {
      newErrors.password = t('auth.error.passwordRequired');
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleSubmit = async (e: FormEvent) => {
    e.preventDefault();
    if (!validate()) return;

    setLoading(true);
    try {
      await apiLogin(email, password);
      showToast(t('auth.loginSuccess'), 'success');
      router.push('/dashboard');
    } catch (err) {
      const message = (err as any)?.error?.message || t('auth.error.loginFailed');
      showToast(message, 'error');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-background px-4">
      <Card className="w-full max-w-md" title={t('auth.loginTitle')}>
        <form onSubmit={handleSubmit} className="space-y-4" data-testid="login-form">
          <Input
            label={t('auth.email')}
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            error={errors.email}
            placeholder="name@firma.de"
            data-testid="email-input"
          />
          <Input
            label={t('auth.password')}
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            error={errors.password}
            placeholder="********"
            data-testid="password-input"
          />
          <Button
            type="submit"
            loading={loading}
            className="w-full"
            data-testid="login-button"
          >
            {t('auth.loginButton')}
          </Button>
        </form>
      </Card>
    </div>
  );
}
