import React, { useState, useEffect } from 'react';
import { Navigate, Link } from 'react-router-dom';
import { useAuthStore } from '../store/authStore';
import { AuthLayout } from '../components/AuthLayout';
import { PasswordStrengthIndicator } from '../components/PasswordStrengthIndicator';
import { useRegister } from '../hooks/useRegister';
import { useUsernameAvailability } from '../hooks/useUsernameAvailability';
import { authApi } from '@/services/api/auth';
import { logger } from '@/utils/logger';
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 { Loader2 } from 'lucide-react';
import type { RegisterFormData } from '../types';

export function RegisterPage() {
  const { isAuthenticated } = useAuthStore();
  const {
    mutate: handleRegister,
    isPending: loading,
    error,
    isSuccess: success,
  } = useRegister();
  const [formData, setFormData] = useState<RegisterFormData>({
    email: '',
    password: '',
    password_confirm: '',
    username: '',
  });
  const { available: usernameAvailable, checking: checkingUsername } =
    useUsernameAvailability(formData.username);
  const [errors, setErrors] = useState<
    Partial<Record<keyof RegisterFormData | 'terms', string>>
  >({});
  const [acceptedTerms, setAcceptedTerms] = useState(false);
  const [showVerificationNotice, setShowVerificationNotice] = useState(false);
  const [resendLoading, setResendLoading] = useState(false);
  const [resendSuccess, setResendSuccess] = useState(false);

  // Détecter quand l'inscription réussit
  useEffect(() => {
    if (success) {
      setShowVerificationNotice(true);
    }
  }, [success]);

  // Rediriger si déjà connecté
  if (isAuthenticated) {
    return <Navigate to="/dashboard" replace />;
  }

  const validate = (): boolean => {
    const newErrors: Partial<Record<keyof RegisterFormData | 'terms', string>> =
      {};

    if (!formData.email) {
      newErrors.email = 'Email requis';
    } else if (!/\S+@\S+\.\S+/.test(formData.email)) {
      newErrors.email = 'Email invalide';
    }

    if (!formData.username) {
      newErrors.username = "Nom d'utilisateur requis";
    } else if (formData.username.length < 3) {
      newErrors.username =
        "Le nom d'utilisateur doit contenir au moins 3 caractères";
    } else if (usernameAvailable === false) {
      newErrors.username = "Ce nom d'utilisateur est déjà pris";
    }

    if (!formData.password) {
      newErrors.password = 'Mot de passe requis';
    } else if (formData.password.length < 12) {
      newErrors.password =
        'Le mot de passe doit contenir au moins 12 caractères';
    }

    if (formData.password !== formData.password_confirm) {
      newErrors.password_confirm = 'Les mots de passe ne correspondent pas';
    }

    if (!acceptedTerms) {
      newErrors.terms =
        "Vous devez accepter les conditions d'utilisation et la politique de confidentialité";
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  const handleChange = (field: keyof RegisterFormData, value: string) => {
    setFormData({ ...formData, [field]: value });
    // Clear error for this field when user starts typing
    if (errors[field]) {
      setErrors({ ...errors, [field]: undefined });
    }
  };

  const handleBlur = (field: keyof RegisterFormData) => {
    const value = formData[field];
    let error: string | undefined;

    switch (field) {
      case 'email':
        if (!value) {
          error = 'Email requis';
        } else if (!/\S+@\S+\.\S+/.test(value)) {
          error = 'Email invalide';
        }
        break;
      case 'username':
        if (!value) {
          error = "Nom d'utilisateur requis";
        } else if (value.length < 3) {
          error = "Le nom d'utilisateur doit contenir au moins 3 caractères";
        }
        break;
      case 'password':
        if (!value) {
          error = 'Mot de passe requis';
        } else if (value.length < 12) {
          error = 'Le mot de passe doit contenir au moins 12 caractères';
        }
        break;
      case 'password_confirm':
        if (formData.password !== value) {
          error = 'Les mots de passe ne correspondent pas';
        }
        break;
    }

    if (error) {
      setErrors({ ...errors, [field]: error });
    } else {
      setErrors({ ...errors, [field]: undefined });
    }
  };

  const onSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (validate()) {
      await handleRegister(formData);
    }
  };

  const handleResendVerificationEmail = async () => {
    try {
      setResendLoading(true);
      setResendSuccess(false);
      await authApi.resendVerification({ email: formData.email });
      setResendSuccess(true);
    } catch (err) {
      // Gérer l'erreur silencieusement ou afficher un message
      logger.error("Erreur lors du renvoi de l'email:", { error: err });
    } finally {
      setResendLoading(false);
    }
  };

  return (
    <AuthLayout
      title="Inscription"
      subtitle="Créez votre compte"
      footerLinks={[{ label: 'Déjà un compte ? Se connecter', to: '/login' }]}
    >
      {showVerificationNotice ? (
        <div className="text-center space-y-4" role="status" aria-live="polite">
          <div
            className="bg-kodo-lime/10 border border-kodo-lime text-kodo-lime px-4 py-4 rounded"
            role="alert"
            aria-live="assertive"
          >
            <p className="font-medium">Inscription réussie !</p>
            <p className="text-sm mt-1">
              Un email de vérification a été envoyé à {formData.email}
            </p>
          </div>
          <p className="text-sm text-kodo-content-dim">
            Veuillez vérifier votre boîte mail et cliquer sur le lien de
            vérification.
          </p>
          {resendSuccess && (
            <p
              className="text-sm text-kodo-lime"
              role="status"
              aria-live="polite"
            >
              Email de vérification renvoyé avec succès !
            </p>
          )}
          <Button
            type="button"
            variant="ghost"
            onClick={handleResendVerificationEmail}
            disabled={resendLoading}
            className="text-kodo-cyan hover:underline text-sm disabled:opacity-50"
            aria-label="Renvoyer l'email de vérification"
          >
            {resendLoading ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                Envoi en cours...
              </>
            ) : (
              "Renvoyer l'email de vérification"
            )}
          </Button>
        </div>
      ) : (
        <form
          onSubmit={onSubmit}
          className="space-y-4"
          aria-label="Formulaire d'inscription"
        >
          {error && (
            <div
              className="bg-kodo-red/10 border border-kodo-red text-kodo-red px-4 py-4 rounded"
              role="alert"
              aria-live="assertive"
            >
              {error.message}
            </div>
          )}
          <div className="space-y-2">
            <Label htmlFor="username">Nom d'utilisateur *</Label>
            <Input
              id="username"
              type="text"
              value={formData.username}
              onChange={(e) => handleChange('username', e.target.value)}
              onBlur={() => handleBlur('username')}
              required
              autoComplete="username"
              aria-invalid={errors.username ? 'true' : 'false'}
            />
            {errors.username && (
              <p className="mt-1 text-sm text-kodo-red" role="alert">
                {errors.username}
              </p>
            )}
            {formData.username.length >= 3 && (
              <div className="mt-1" aria-live="polite" aria-atomic="true">
                {checkingUsername ? (
                  <p className="text-xs text-kodo-content-dim" role="status">
                    <span className="sr-only">Vérification en cours</span>
                    <span aria-hidden="true">Vérification en cours...</span>
                  </p>
                ) : usernameAvailable === true ? (
                  <p className="text-xs text-kodo-lime" role="status">
                    <span className="sr-only">Disponible:</span>
                    <span aria-hidden="true">✓</span> Ce nom d'utilisateur est
                    disponible
                  </p>
                ) : usernameAvailable === false ? (
                  <p className="text-xs text-kodo-red" role="alert">
                    <span className="sr-only">Indisponible:</span>
                    <span aria-hidden="true">✗</span> Ce nom d'utilisateur est
                    déjà pris
                  </p>
                ) : null}
              </div>
            )}
          </div>
          <div className="space-y-2">
            <Label htmlFor="email">Email *</Label>
            <Input
              id="email"
              type="email"
              value={formData.email}
              onChange={(e) => handleChange('email', e.target.value)}
              onBlur={() => handleBlur('email')}
              required
              autoComplete="email"
              aria-invalid={errors.email ? 'true' : 'false'}
            />
            {errors.email && (
              <p className="mt-1 text-sm text-kodo-red" role="alert">
                {errors.email}
              </p>
            )}
          </div>
          <div className="space-y-2">
            <Label htmlFor="password">Mot de passe *</Label>
            <Input
              id="password"
              type="password"
              value={formData.password}
              onChange={(e) => handleChange('password', e.target.value)}
              onBlur={() => handleBlur('password')}
              required
              autoComplete="new-password"
              aria-invalid={errors.password ? 'true' : 'false'}
            />
            {errors.password && (
              <p className="mt-1 text-sm text-kodo-red" role="alert">
                {errors.password}
              </p>
            )}
            <PasswordStrengthIndicator password={formData.password} />
          </div>
          <div className="space-y-2">
            <Label htmlFor="password_confirm">Confirmer le mot de passe *</Label>
            <Input
              id="password_confirm"
              type="password"
              value={formData.password_confirm}
              onChange={(e) => handleChange('password_confirm', e.target.value)}
              onBlur={() => handleBlur('password_confirm')}
              required
              autoComplete="new-password"
              aria-invalid={errors.password_confirm ? 'true' : 'false'}
            />
            {errors.password_confirm && (
              <p className="mt-1 text-sm text-kodo-red" role="alert">
                {errors.password_confirm}
              </p>
            )}
          </div>
          <div className="flex items-start">
            <Checkbox
              id="terms"
              checked={acceptedTerms}
              onCheckedChange={(checked) => {
                setAcceptedTerms(checked as boolean);
                if (errors.terms) {
                  setErrors({ ...errors, terms: undefined });
                }
              }}
              required
              aria-invalid={errors.terms ? 'true' : 'false'}
              aria-describedby={
                errors.terms ? 'terms-error' : 'terms-description'
              }
            />
            <label htmlFor="terms" className="ml-2 block text-sm text-kodo-text-main">
              J'accepte les{' '}
              <Link
                to="/terms"
                className="text-kodo-cyan hover:underline focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 rounded"
                aria-label="Lire les conditions d'utilisation"
              >
                conditions d'utilisation
              </Link>{' '}
              et la{' '}
              <Link
                to="/privacy"
                className="text-kodo-cyan hover:underline focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 rounded"
                aria-label="Lire la politique de confidentialité"
              >
                politique de confidentialité
              </Link>
            </label>
          </div>
          <p id="terms-description" className="sr-only">
            Vous devez accepter les conditions d'utilisation et la politique de
            confidentialité pour créer un compte
          </p>
          {errors.terms && (
            <p id="terms-error" className="text-sm text-kodo-red" role="alert">
              {errors.terms}
            </p>
          )}
          <Button type="submit" disabled={loading} className="w-full">
            {loading ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                Inscription en cours...
              </>
            ) : (
              "S'inscrire"
            )}
          </Button>
        </form>
      )}
    </AuthLayout>
  );
}

export default RegisterPage;
