import { useEffect } from 'react';
import { useIsAuthenticated } from './auth.store';
import { useTenantActions, useAvailableTenants, useCurrentTenant } from './tenant.store';
import { useIsDemoMode, useDemoSessionId, useDemoAccountType } from '../hooks/useAccessControl';

/**
 * Hook to automatically initialize tenant data when user is authenticated or in demo mode
 * This should be used at the app level to ensure tenant data is loaded
 */
export const useTenantInitializer = () => {
  const isAuthenticated = useIsAuthenticated();
  const isDemoMode = useIsDemoMode();
  const demoSessionId = useDemoSessionId();
  const demoAccountType = useDemoAccountType();
  const availableTenants = useAvailableTenants();
  const currentTenant = useCurrentTenant();
  const { loadUserTenants, setCurrentTenant } = useTenantActions();

  // Load tenants for authenticated users
  useEffect(() => {
    if (isAuthenticated && !availableTenants) {
      loadUserTenants();
    }
  }, [isAuthenticated, availableTenants, loadUserTenants]);

  // Set up mock tenant for demo mode
  useEffect(() => {
    if (isDemoMode && demoSessionId) {
      const demoTenantId = localStorage.getItem('demo_tenant_id') || 'demo-tenant-id';

      console.log('🔍 [TenantInitializer] Demo mode detected:', {
        isDemoMode,
        demoSessionId,
        demoTenantId,
        demoAccountType,
        currentTenant: currentTenant?.id
      });

      // Check if current tenant is the demo tenant and is properly set
      const isValidDemoTenant = currentTenant &&
        typeof currentTenant === 'object' &&
        currentTenant.id === demoTenantId;

      if (!isValidDemoTenant) {
        console.log('🔧 [TenantInitializer] Setting up demo tenant...');

        const accountTypeName = demoAccountType === 'individual_bakery'
          ? 'Panadería San Pablo - Demo'
          : 'Panadería La Espiga - Demo';

        // Create a complete tenant object matching TenantResponse structure
        const mockTenant = {
          id: demoTenantId,
          name: accountTypeName,
          subdomain: `demo-${demoSessionId.slice(0, 8)}`,
          business_type: demoAccountType === 'individual_bakery' ? 'bakery' : 'central_baker',
          business_model: demoAccountType,
          address: 'Demo Address',
          city: 'Madrid',
          postal_code: '28001',
          phone: null,
          is_active: true,
          subscription_tier: 'demo',
          ml_model_trained: false,
          last_training_date: null,
          owner_id: 'demo-user',
          created_at: new Date().toISOString(),
        };

        // Set the demo tenant as current
        setCurrentTenant(mockTenant);

        // **CRITICAL: Also set tenant ID in API client**
        // This ensures API requests include the tenant ID header
        import('../api/client').then(({ apiClient }) => {
          apiClient.setTenantId(demoTenantId);
          console.log('✅ [TenantInitializer] Set API client tenant ID:', demoTenantId);
        });
      }
    }
  }, [isDemoMode, demoSessionId, demoAccountType, currentTenant, setCurrentTenant]);
};