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 { RegisterRequest } from '@/services/api/auth';
import type { ApiError } from '@/schemas/apiSchemas';
import { Button } from '@/components/ui/button';
import { FloatingInput } from '@/components/ui/floating-input';
import { logger } from '@/utils/logger';
import { useFormValidation } from '@/hooks/useFormValidation';
import { useEffect } from 'react';
import { useToast } from '@/hooks/useToast';
import { Mail, User, Lock } from 'lucide-react';

const registerSchema = z
  .object({
    email: z.string().email('Email invalide'),
    username: z
      .string()
      .min(3, "Le nom d'utilisateur doit contenir au moins 3 caractères"),
    password: z
      .string()
      .min(12, 'Le mot de passe doit contenir au moins 12 caractères'),
    password_confirm: z.string().min(1, 'La confirmation est requise'),
  })
  .refine((data) => data.password === data.password_confirm, {
    message: 'Les mots de passe ne correspondent pas',
    path: ['password_confirm'],
  });

type RegisterFormData = z.infer<typeof registerSchema>;

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

  const {
    register,
    handleSubmit,
    formState: { errors },
    watch,
  } = useForm<RegisterFormData>({
    resolver: zodResolver(registerSchema),
    defaultValues: {
      email: '',
      username: '',
      password: '',
      password_confirm: '',
    },
  });

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

  // Validate on form data change (debounced)
  useEffect(() => {
    const hasData =
      formData.email || formData.username || formData.password || formData.password_confirm;
    if (hasData) {
      // Backend expects password_confirmation, not password_confirm
      const registerData = {
        email: formData.email || '',
        username: formData.username || '',
        password: formData.password || '',
        password_confirmation: formData.password_confirm || '',
      };
      validate(registerData);
    }
  }, [formData.email, formData.username, formData.password, formData.password_confirm, validate]);

  const onSubmit = async (data: RegisterFormData) => {
    try {
      const registerRequest: RegisterRequest = {
        email: data.email,
        username: data.username,
        password: data.password,
        password_confirm: data.password_confirm,
      };
      await registerStore(registerRequest);

      // Redirection après succès
      const { isAuthenticated } = useAuthStore.getState();
      if (isAuthenticated) {
        navigate('/dashboard');
      } else {
        navigate('/login');
      }
    } catch (err) {
      const errorMessage = formatErrorMessage(err as ApiError);
      logger.error('Register error', {
        error: err instanceof Error ? err.message : String(err),
        stack: err instanceof Error ? err.stack : undefined,
      });
      toast({
        message: errorMessage,
        type: 'error',
      });
    }
  };

  useEffect(() => {
    if (error) {
      const errorMessage = formatErrorMessage(error);
      toast({
        message: errorMessage,
        type: 'error',
      });
    }
  }, [error, toast]);

  const getFieldError = (fieldName: keyof RegisterFormData | 'password_confirmation') => {
    // Handle zod errors
    // @ts-expect-error - dynamic key access
    const formError = errors[fieldName]?.message;

    // Handle backend errors
    const backendError = backendErrors.find(e => e.field === fieldName)?.message;

    return formError || backendError;
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="space-y-6" 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"
          icon={<Mail className="h-4 w-4" />}
          {...register('email')}
          error={getFieldError('email')}
        />

        <FloatingInput
          label="Nom d'utilisateur"
          type="text"
          icon={<User className="h-4 w-4" />}
          {...register('username')}
          error={getFieldError('username')}
        />

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

        <FloatingInput
          label="Confirmer le mot de passe"
          type="password"
          icon={<Lock className="h-4 w-4" />}
          {...register('password_confirm')}
          error={getFieldError('password_confirm') || getFieldError('password_confirmation')}
        />
      </div>

      <Button
        type="submit"
        disabled={isLoading}
        variant="default"
        size="lg"
        className="w-full bg-gradient-to-r from-kodo-magenta to-kodo-magenta-dim hover:from-kodo-magenta/90 hover:to-kodo-magenta-dim/90 text-white font-bold tracking-wide shadow-lg shadow-kodo-magenta/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" />
            Initialisation...
          </span>
        ) : (
          "S'INSCRIRE"
        )}
      </Button>
    </form>
  );
};
