import React, { useState } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useLogin } from '@/api/hooks';
import { useUIStore } from '@/store/uiStore';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';

const loginSchema = z.object({
  email: z.string().email(),
  password: z.string().min(1),
});

type LoginFormData = z.infer<typeof loginSchema>;

export function LoginPage() {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const loginMutation = useLogin();
  const { addToast } = useUIStore();
  const [submitError, setSubmitError] = useState<string | null>(null);

  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<LoginFormData>({
    resolver: zodResolver(loginSchema),
    defaultValues: { email: '', password: '' },
  });

  const onSubmit = async (data: LoginFormData) => {
    setSubmitError(null);
    try {
      await loginMutation.mutateAsync(data);
      addToast({ type: 'success', message: t('auth.login') + ' erfolgreich' });
      navigate('/dashboard');
    } catch (error: any) {
      const msg = error.message || t('auth.loginFailed');
      setSubmitError(msg);
      addToast({ type: 'error', message: msg });
    }
  };

  return (
    <div className="min-h-screen flex items-center justify-center bg-secondary-50 px-4" data-testid="login-page">
      <div className="w-full max-w-md">
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold text-primary-600">leocrm</h1>
          <p className="text-secondary-500 mt-2">{t('app.tagline')}</p>
        </div>
        <div className="bg-white rounded-lg shadow-md p-8">
          <h2 className="text-xl font-semibold text-secondary-900 mb-6">{t('auth.login')}</h2>
          <form onSubmit={handleSubmit(onSubmit)} className="space-y-4" noValidate aria-label={t('auth.login')}>
            <Input
              label={t('auth.email')}
              type="email"
              autoComplete="email"
              required
              error={errors.email?.message}
              {...register('email')}
            />
            <Input
              label={t('auth.password')}
              type="password"
              autoComplete="current-password"
              required
              error={errors.password?.message}
              {...register('password')}
            />
            {submitError && (
              <div role="alert" className="text-sm text-danger-600 bg-danger-50 rounded-md p-3">
                {submitError}
              </div>
            )}
            <Button type="submit" fullWidth isLoading={loginMutation.isPending}>
              {t('auth.loginButton')}
            </Button>
          </form>
          <div className="mt-4 text-center">
            <Link to="/password-reset" className="text-sm text-primary-600 hover:text-primary-700 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary-500 rounded">
              {t('auth.forgotPassword')}
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
}
