import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { useNavigate } from 'react-router-dom';
import { useAuthStore } from '../store/authStore';
import { formatErrorMessage } from '@/utils/apiErrorHandler';
import type { LoginRequest } from '@/services/api/auth';
import type { ApiError } from '@/schemas/apiSchemas';
import { Button } from '@/components/ui/button';
import { FloatingInput } from '@/components/ui/floating-input';
import { Checkbox } from '@/components/ui/checkbox';
import { logger } from '@/utils/logger';
import { useFormValidation } from '@/hooks/useFormValidation';
import { Mail, Lock } from 'lucide-react';

import { useEffect } from 'react';
import { useToast } from '@/hooks/useToast';

const loginSchema = z.object({
  email: z.string().email('Email invalide'),
  password: z.string().min(1, 'Le mot de passe est requis'),
  remember_me: z.boolean().optional(),
});

type LoginFormData = z.infer<typeof loginSchema>;

/**
 * LoginForm with Kōdō Design System
 * MIGRATED: Now using Kōdō Input and Button components
 */
export const LoginForm = () => {
  const navigate = useNavigate();
  const { login: loginStore, isLoading, error } = useAuthStore();
  const { toast } = useToast();

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

  // Action 5.2.1.2: Pre-validation with backend
  const formData = watch();
  const { validate, errors: backendErrors } = useFormValidation({
    type: 'LoginRequest',
    debounceMs: 300,
  });

  // Validate on form data change (debounced)
  useEffect(() => {
    const hasData = formData.email || formData.password;
    if (hasData) {
      const loginData: LoginRequest = {
        email: formData.email || '',
        password: formData.password || '',
        remember_me: formData.remember_me || false,
      };
      validate(loginData);
    }
  }, [formData.email, formData.password, formData.remember_me, validate]);

  const onSubmit = async (data: LoginFormData) => {
    try {
      const loginRequest: LoginRequest = {
        email: data.email,
        password: data.password,
        remember_me: data.remember_me || false,
      };
      await loginStore(loginRequest);
      // Redirection après succès
      navigate('/dashboard');
    } catch (err) {
      // L'erreur est déjà gérée par le store, mais afficher aussi un toast pour visibilité
      const errorMessage = formatErrorMessage(err as ApiError);
      logger.error('Login error', {
        error: err instanceof Error ? err.message : String(err),
        stack: err instanceof Error ? err.stack : undefined,
      });
      toast({
        message: errorMessage,
        type: 'error',
      });
    }
  };

  const getFieldError = (fieldName: keyof LoginFormData) => {
    const formError = errors[fieldName]?.message;
    const backendError = backendErrors.find(e => e.field === fieldName)?.message;
    return formError || backendError;
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="w-full space-y-8" noValidate>

      {error && (
        <div
          className="bg-kodo-red/10 border border-kodo-red/20 text-kodo-red text-sm px-4 py-3 rounded-lg flex items-center gap-2 animate-in fade-in slide-in-from-top-1"
          role="alert"
        >
          <span className="w-1.5 h-1.5 rounded-full bg-kodo-red shrink-0" />
          <span>{formatErrorMessage(error as ApiError)}</span>
        </div>
      )}

      <div className="space-y-4">
        <FloatingInput
          label="Email"
          type="email"
          autoComplete="email"
          icon={<Mail className="h-4 w-4" />}
          {...register('email')}
          error={getFieldError('email')}
        />

        <FloatingInput
          label="Mot de passe"
          type="password"
          autoComplete="current-password"
          icon={<Lock className="h-4 w-4" />}
          {...register('password')}
          error={getFieldError('password')}
        />
      </div>

      <div className="flex items-center justify-between">
        <Checkbox
          id="remember_me"
          checked={watch('remember_me')}
          onCheckedChange={(checked) => setValue('remember_me', checked === true)}
          label="Se souvenir de moi"
        />

        {/* Helper Link could go here */}
      </div>

      <Button
        type="submit"
        disabled={isLoading}
        variant="default"
        size="lg"
        className="w-full bg-gradient-to-r from-kodo-cyan to-kodo-cyan-dim hover:from-kodo-cyan/90 hover:to-kodo-cyan-dim/90 text-kodo-ink font-bold tracking-wide shadow-lg shadow-kodo-cyan/20 rounded-xl"
      >
        {isLoading ? (
          <span className="flex items-center gap-2">
            <span className="h-4 w-4 border-2 border-current border-t-transparent rounded-full animate-spin" />
            Connexion...
          </span>
        ) : (
          'ACCÉDER AU TERMINAL'
        )}
      </Button>
    </form>
  );
};
