import { useEffect, useState } from 'react';
import { useChatStore } from '@/features/chat/presentation/stores/chatStore';

const FINGERPRINT_KEY = 'iconsulting_fingerprint';
const USER_ID_KEY = 'iconsulting_user_id';

/**
 * Generate a simple browser fingerprint
 */
function generateFingerprint(): string {
  const components = [
    navigator.userAgent,
    navigator.language,
    screen.width,
    screen.height,
    screen.colorDepth,
    new Date().getTimezoneOffset(),
    navigator.hardwareConcurrency,
  ];

  // Simple hash function
  const str = components.join('|');
  let hash = 0;
  for (let i = 0; i < str.length; i++) {
    const char = str.charCodeAt(i);
    hash = (hash << 5) - hash + char;
    hash = hash & hash; // Convert to 32bit integer
  }

  return `fp_${Math.abs(hash).toString(36)}_${Date.now().toString(36)}`;
}

/**
 * Hook to handle anonymous authentication
 */
export function useAnonymousAuth() {
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const { userId, setUserId } = useChatStore();

  useEffect(() => {
    const initAuth = async () => {
      try {
        // Check for existing user ID
        let storedUserId = localStorage.getItem(USER_ID_KEY);
        let fingerprint = localStorage.getItem(FINGERPRINT_KEY);

        if (storedUserId) {
          // Use existing user
          setUserId(storedUserId);
          setIsLoading(false);
          return;
        }

        // Generate fingerprint if not exists
        if (!fingerprint) {
          fingerprint = generateFingerprint();
          localStorage.setItem(FINGERPRINT_KEY, fingerprint);
        }

        // Create anonymous user
        const response = await fetch('/api/v1/auth/anonymous', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ fingerprint }),
        });

        if (!response.ok) {
          throw new Error('Failed to create anonymous session');
        }

        const data = await response.json();
        if (data.success && data.data?.userId) {
          localStorage.setItem(USER_ID_KEY, data.data.userId);
          setUserId(data.data.userId);
        } else {
          // Fallback: use fingerprint as user ID for demo
          const fallbackId = `anon_${fingerprint}`;
          localStorage.setItem(USER_ID_KEY, fallbackId);
          setUserId(fallbackId);
        }
      } catch (err) {
        console.error('Auth error:', err);
        // Fallback for demo purposes
        const fallbackId = `anon_${Date.now().toString(36)}`;
        localStorage.setItem(USER_ID_KEY, fallbackId);
        setUserId(fallbackId);
        setError(err instanceof Error ? err.message : 'Authentication failed');
      } finally {
        setIsLoading(false);
      }
    };

    initAuth();
  }, [setUserId]);

  const logout = () => {
    localStorage.removeItem(USER_ID_KEY);
    localStorage.removeItem(FINGERPRINT_KEY);
    setUserId('');
    window.location.reload();
  };

  return {
    userId,
    isLoading,
    error,
    logout,
  };
}
