import { useEffect, useState } from 'react';
import axios from 'axios';
import { API_URL } from '../services/api';
import { useLocation } from 'react-router-dom';
import { trackEvent as trackAnalyticsEvent } from '../services/analyticsService';

interface UmamiConfig {
  enabled: boolean;
  website_id: string;
  script_url: string;
}

// Extend window object to include umami
declare global {
  interface Window {
    umami?: {
      track: (eventName: string, eventData?: Record<string, any>) => void;
    };
  }
}

export const useUmami = () => {
  const [config, setConfig] = useState<UmamiConfig | null>(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const location = useLocation();

  // Helper to check if current path is an admin route or system page
  const isAdminRoute = (pathname: string) => {
    return pathname.startsWith('/admin') || 
           pathname === '/login' || 
           pathname === '/setup';
  };

  useEffect(() => {
    // Don't load Umami for admin pages
    if (isAdminRoute(location.pathname)) {
      console.log('Umami tracking disabled for admin pages');
      return;
    }

    // Fetch Umami configuration from backend
    const fetchConfig = async () => {
      try {
        const response = await axios.get(`${API_URL}/umami/config`);
        const umamiConfig = response.data as UmamiConfig;
        setConfig(umamiConfig);

        // If enabled and not already loaded, inject the script
        if (umamiConfig.enabled && umamiConfig.website_id && !isLoaded) {
          loadUmamiScript(umamiConfig.script_url, umamiConfig.website_id);
        }
      } catch (error) {
        console.error('Failed to load Umami config:', error);
      }
    };

    fetchConfig();
  }, [location.pathname]);

  // Track page views when location changes (skip admin routes for Umami)
  useEffect(() => {
    if (location.pathname && !isAdminRoute(location.pathname)) {
      // Track with our analytics backend (public pages only)
      trackAnalyticsEvent({
        event_type: 'page_view',
        page_path: location.pathname,
        page_name: document.title,
      }).catch(err => {
        console.debug('Analytics tracking failed:', err);
      });
    }
  }, [location.pathname]);

  const loadUmamiScript = (scriptUrl: string, websiteId: string) => {
    // Check if script already exists
    const existingScript = document.querySelector(`script[data-website-id="${websiteId}"]`);
    if (existingScript) {
      setIsLoaded(true);
      return;
    }

    // Create and inject the script
    const script = document.createElement('script');
    script.async = true;
    script.defer = true;
    script.src = scriptUrl;
    script.setAttribute('data-website-id', websiteId);

    script.onload = () => {
      console.log('Umami tracking loaded');
      setIsLoaded(true);
    };

    script.onerror = () => {
      console.error('Failed to load Umami script');
    };

    document.head.appendChild(script);
  };

  // Track custom events (skip admin routes)
  const trackEvent = (eventName: string, eventData?: Record<string, any>) => {
    // Skip tracking for admin routes
    if (isAdminRoute(location.pathname)) {
      return;
    }

    // Track with Umami if available
    if (window.umami && isLoaded) {
      window.umami.track(eventName, eventData);
    }

    // Also track with our backend analytics
    trackAnalyticsEvent({
      event_type: eventName,
      page: location.pathname,
      data: eventData,
    }).catch(err => {
      console.debug('Backend tracking failed:', err);
    });
  };

  return {
    isEnabled: config?.enabled || false,
    isLoaded,
    trackEvent,
  };
};
