'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 { ToastProvider, useToast } from '@/components/ui/Toast';
import { I18nProvider, useI18n } from '@/lib/i18n';
import { login as apiLogin, setTokens } from '@/lib/api';

function LoginForm() {
  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: { email?: string; password?: string } = {};
    if (!email) {
      newErrors.email = t('login.error.emailRequired');
    } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      newErrors.email = t('login.error.emailInvalid');
    }
    if (!password) {
      newErrors.password = t('login.error.passwordRequired');
    }
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

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

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

  return (
    <div className="min-h-screen flex items-center justify-center p-4">
      <Card className="w-full max-w-md" title={t('login.title')}>
        <form onSubmit={handleSubmit} className="space-y-4" data-testid="login-form">
          <Input
            label={t('login.email')}
            type="email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            error={errors.email}
            placeholder="user@example.com"
            data-testid="login-email"
          />
          <Input
            label={t('login.password')}
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            error={errors.password}
            placeholder="********"
            data-testid="login-password"
          />
          <Button
            type="submit"
            loading={loading}
            className="w-full"
            data-testid="login-submit"
          >
            {t('login.submit')}
          </Button>
        </form>
      </Card>
    </div>
  );
}

export default function LoginPage() {
  return (
    <I18nProvider initialLocale="de">
      <ToastProvider>
        <LoginForm />
      </ToastProvider>
    </I18nProvider>
  );
}
