import { useState, useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import { useFormValidation } from '@/hooks/useFormValidation';

// T0166: Schema de validation Zod pour le formulaire de connexion
const loginSchema = z.object({
  email: z.string().email('Invalid email address'),
  password: z.string().min(1, 'Password is required'),
  remember_me: z.boolean().optional(),
});

export type LoginFormData = z.infer<typeof loginSchema>;

interface LoginFormProps {
  onSubmit: (data: LoginFormData) => Promise<void>;
  disabled?: boolean;
}

// T0166: Composant LoginForm avec champs email, password et checkbox "Remember Me"
export function LoginForm({ onSubmit, disabled = false }: LoginFormProps) {
  const {
    register,
    handleSubmit,
    formState: { errors },
    watch,
    setValue,
  } = useForm<LoginFormData>({
    resolver: zodResolver(loginSchema),
    mode: 'onChange',
    reValidateMode: 'onChange',
    defaultValues: {
      remember_me: false,
    },
  });

  const [isLoading, setIsLoading] = useState(false);
  const isFormDisabled = disabled || isLoading;
  const remember_me = watch('remember_me');
  const formData = watch();

  // Action 5.2.1.4: Pre-validation with backend
  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 = {
        email: formData.email || '',
        password: formData.password || '',
        remember_me: formData.remember_me || false,
      };
      validate(loginData);
    }
  }, [formData.email, formData.password, formData.remember_me, validate]);

  const handleFormSubmit = async (data: LoginFormData) => {
    setIsLoading(true);
    try {
      await onSubmit(data);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <form onSubmit={handleSubmit(handleFormSubmit)} className="space-y-4">
      <div className="space-y-2">
        <Label htmlFor="email">Email</Label>
        <Input
          id="email"
          type="email"
          placeholder="Enter your email"
          {...register('email')}
          disabled={isFormDisabled}
          aria-invalid={errors.email ? 'true' : 'false'}
          aria-describedby={errors.email ? 'email-error' : undefined}
        />
        {errors.email && (
          <p id="email-error" className="text-sm text-destructive" role="alert">
            {errors.email.message}
          </p>
        )}
      </div>

      <div className="space-y-2">
        <Label htmlFor="password">Password</Label>
        <Input
          id="password"
          type="password"
          placeholder="Enter your password"
          {...register('password')}
          disabled={isFormDisabled}
          aria-invalid={errors.password ? 'true' : 'false'}
          aria-describedby={errors.password ? 'password-error' : undefined}
        />
        {errors.password && (
          <p
            id="password-error"
            className="text-sm text-destructive"
            role="alert"
          >
            {errors.password.message}
          </p>
        )}
      </div>

      <div className="flex items-center space-x-2">
        <Checkbox
          id="remember_me"
          checked={remember_me || false}
          onCheckedChange={(checked) => {
            setValue('remember_me', checked === true, { shouldValidate: true });
          }}
          disabled={isFormDisabled}
        />
        <Label
          htmlFor="remember_me"
          className="text-sm font-normal cursor-pointer"
        >
          Remember Me
        </Label>
      </div>

      <Button type="submit" disabled={isFormDisabled} className="w-full">
        {isLoading ? 'Logging in...' : 'Login'}
      </Button>
    </form>
  );
}
