import { useState, useEffect, useRef } from 'react';
import { useUser } from '@/features/auth/hooks/useUser';
import { usersApi } from '@/services/api/users';
import { UserSettings } from '../types/settings';
import { SettingsTabs } from '../components/SettingsTabs';
import { Button, Card } from '@veza/design-system';
import { LoadingSpinner } from '@/components/ui/loading-spinner';
// CRITICAL FIX: Utiliser le wrapper lazy pour éviter les collisions de noms de variables
import toast from '@/utils/toast';
import { settingsSchema } from '../schemas/settingsSchema';
import { ErrorDisplay } from '@/components/ui/ErrorDisplay';

/**
 * SettingsPage with Kōdō Design System
 * MIGRATED: Now using Kōdō Button and Card components
 */
export function SettingsPage() {
  const { data: user } = useUser();
  const [settings, setSettings] = useState<UserSettings | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isSaving, setIsSaving] = useState(false);
  const [queryError, setQueryError] = useState<Error | null>(null);
  const [mutationError, setMutationError] = useState<Error | null>(null);
  const [retryCount, setRetryCount] = useState(0);
  const lastMutationRef = useRef<(() => Promise<void>) | null>(null);

  const loadSettings = async () => {
    if (!user?.id) {
      setQueryError(
        new Error('Vous devez être connecté pour accéder aux paramètres'),
      );
      setIsLoading(false);
      return;
    }

    try {
      setIsLoading(true);
      setQueryError(null);
      const userSettings = await usersApi.getSettings(user.id);
      setSettings(userSettings);
    } catch (err) {
      const errorMessage =
        err instanceof Error
          ? err.message
          : 'Erreur de chargement des paramètres';
      setQueryError(new Error(errorMessage));
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    loadSettings();
  }, [user?.id]);

  const handleSave = async () => {
    if (!user?.id || !settings) {
      return;
    }

    // Valider les settings avec le schéma Zod
    const validationResult = settingsSchema.safeParse(settings);
    if (!validationResult.success) {
      const errors = validationResult.error.errors
        .map((e) => `${e.path.join('.')}: ${e.message}`)
        .join(', ');
      toast.error(`Erreur de validation: ${errors}`);
      return;
    }

    // Action 3.4.1.3: Store mutation for retry
    const performMutation = async () => {
      await usersApi.updateSettings(user.id, settings);
      toast.success('Paramètres sauvegardés avec succès');
      setMutationError(null);
      setRetryCount(0);
      lastMutationRef.current = null;
    };

    lastMutationRef.current = performMutation;
    setIsSaving(true);
    setMutationError(null);

    try {
      await performMutation();
    } catch (err) {
      const errorMessage =
        err instanceof Error ? err.message : 'Erreur lors de la sauvegarde';
      setMutationError(new Error(errorMessage));
    } finally {
      setIsSaving(false);
    }
  };

  // Action 3.4.1.3: Retry handler for failed mutations
  const handleRetry = async () => {
    if (!lastMutationRef.current || retryCount >= 3) return;

    setRetryCount((prev) => prev + 1);
    setIsSaving(true);
    try {
      await lastMutationRef.current();
    } catch (error) {
      // Error will be handled by the mutation function
    } finally {
      setIsSaving(false);
    }
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center min-h-[400px]">
        <LoadingSpinner />
      </div>
    );
  }

  if (queryError && !settings) {
    return (
      <div className="container mx-auto px-4 py-8">
        <div className="max-w-2xl mx-auto">
          <h1 className="text-2xl font-display font-bold text-white mb-4">
            Paramètres
          </h1>
          <ErrorDisplay
            error={queryError}
            variant="card"
            severity="error"
            context={{
              action: 'fetching settings',
              resource: 'settings',
            }}
            onRetry={loadSettings}
          />
        </div>
      </div>
    );
  }

  // Si settings n'est pas chargé mais qu'il n'y a pas d'erreur, afficher un état de chargement
  // au lieu de retourner null (qui empêche la navigation de se terminer)
  if (!settings) {
    return (
      <div className="container mx-auto px-4 py-8">
        <div className="max-w-2xl mx-auto">
          <h1 className="text-2xl font-display font-bold text-white mb-4">
            Paramètres
          </h1>
          <div className="flex items-center justify-center min-h-[200px]">
            <LoadingSpinner />
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="container mx-auto px-4 py-8">
      {mutationError && (
        <ErrorDisplay
          error={mutationError}
          variant="banner"
          severity="error"
          context={{
            action: 'saving settings',
            resource: 'settings',
          }}
          onRetry={retryCount < 3 ? handleRetry : undefined}
          onDismiss={() => {
            setMutationError(null);
            setRetryCount(0);
            lastMutationRef.current = null;
          }}
        />
      )}
      <div className="max-w-4xl mx-auto">
        <div className="mb-6">
          <h1 className="text-3xl font-display font-bold text-white mb-2">
            Paramètres
          </h1>
          <p className="text-kodo-secondary">
            Gérez vos paramètres de compte et préférences
          </p>
        </div>

        <Card variant="default">
          <SettingsTabs settings={settings} onChange={setSettings} />

          <div className="mt-6 flex justify-end">
            <Button
              onClick={handleSave}
              disabled={isSaving}
              variant="primary"
              className="min-w-[120px]"
            >
              {isSaving ? (
                <>
                  <LoadingSpinner className="mr-2 h-4 w-4" />
                  Sauvegarde...
                </>
              ) : (
                'Sauvegarder'
              )}
            </Button>
          </div>
        </Card>
      </div>
    </div>
  );
}
