'use client';

import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { useUser } from '@/app/contexts/UserContext';
import type { SupabaseUser } from '@/app/[locale]/chat/types/supabase';

interface SupabaseUserContextType {
  supabaseUser: SupabaseUser | null;
  supabaseUserId: string | null;
  loading: boolean;
  error: string | null;
}

const SupabaseUserContext = createContext<SupabaseUserContextType>({
  supabaseUser: null,
  supabaseUserId: null,
  loading: true,
  error: null,
});

export function SupabaseUserProvider({ children }: { children: ReactNode }) {
  const { user } = useUser();
  const [supabaseUser, setSupabaseUser] = useState<SupabaseUser | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!user?.id) {
      setSupabaseUser(null);
      setLoading(false);
      return;
    }

    let mounted = true;
    let retryCount = 0;
    const maxRetries = 3;

    const syncUser = async (isRetry: boolean = false): Promise<void> => {
      try {
        if (!isRetry) {
          setLoading(true);
        }
        setError(null);

        const response = await fetch('/api/chat/sync-user', {
          method: 'POST',
          credentials: 'include',
        });

        if (!response.ok) {
          throw new Error('Failed to sync user');
        }

        const data = await response.json();
        if (data.success && data.user && mounted) {
          setSupabaseUser(data.user);
          retryCount = 0; // Reset on success
          setLoading(false);
        } else if (mounted) {
          setError('User not found');
          setLoading(false);
        }
      } catch (err) {
        console.error('Error syncing user:', err);
        if (mounted) {
          // Retry automatique pour les erreurs réseau
          if (retryCount < maxRetries) {
            retryCount++;
            await new Promise(resolve => setTimeout(resolve, 1000 * retryCount)); // Délai exponentiel
            return syncUser(true); // Retry
          }
          setError('Failed to sync user');
          setLoading(false);
        }
      }
    };

    syncUser();

    return () => {
      mounted = false;
    };
  }, [user?.id]);

  return (
    <SupabaseUserContext.Provider
      value={{
        supabaseUser,
        supabaseUserId: supabaseUser?.id || null,
        loading,
        error,
      }}
    >
      {children}
    </SupabaseUserContext.Provider>
  );
}

export function useSupabaseUser() {
  return useContext(SupabaseUserContext);
}

