'use client';

import React, { createContext, useContext, useEffect, useState, useRef } from 'react';
import { usePathname } from 'next/navigation';
import api from '@/lib/api-client';

interface Suggestion {
  next_steps?: string[];
  form_defaults?: Record<string, any>;
}

interface SmartContextType {
  suggestions: Suggestion | null;
  trackEvent: (type: string, target: string, metadata?: any) => void;
}

const SmartContext = createContext<SmartContextType | undefined>(undefined);

export function SmartProvider({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const [suggestions, setSuggestions] = useState<Suggestion | null>(null);
  const eventQueue = useRef<any[]>([]);
  const flushInterval = useRef<NodeJS.Timeout | null>(null);

  const getToken = () => {
    if (typeof window === 'undefined') return null;
    return localStorage.getItem('gcx_fshs_token');
  };

  // 1. Track Page Views & Fetch Suggestions
  useEffect(() => {
    if (!pathname) return;

    // IGNORE AUTH PAGES: Don't run smart assistant on login/public pages
    const isAuthPage = ['/login', '/reset-password', '/register'].some(p => pathname.startsWith(p));
    if (isAuthPage) {
      setSuggestions(null);
      return;
    }

    const token = getToken();
    if (!token) {
      // Not authenticated yet (e.g. /login). Don't call protected smart endpoints.
      setSuggestions(null);
      return;
    }

    // Track Page View
    trackEvent('PAGE_VIEW', pathname);

    // Fetch Suggestions for this context
    const fetchSuggestions = async () => {
      try {
        const { data } = await api.get('/smart/suggestions', {
          params: { context: pathname }
        });
        if (data.suggestions) {
          setSuggestions(data.suggestions);
        }
      } catch (err: any) {
        // PERMITTED FAILURES: 401 (stale token), network errors (backend offline
        // or endpoint missing), and aborted requests are all silent — this is a
        // background intelligence feature and should never spam the console.
        const status = err?.response?.status;
        const code = err?.code;
        const isTransient = status === 401
          || status === 404
          || status === 0
          || code === 'ERR_NETWORK'
          || code === 'ECONNABORTED'
          || code === 'ERR_CANCELED';
        if (!isTransient) {
          console.warn('[smart] suggestions unavailable', err?.message || err);
        }
      }
    };

    fetchSuggestions();
  }, [pathname]);

  // 2. Telemetry Batching
  const trackEvent = (type: string, target: string, metadata: any = {}) => {
    if (!getToken()) return;
    eventQueue.current.push({
      type,
      target,
      metadata,
      timestamp: new Date().toISOString(),
      duration: 0 // Could calculate time on page
    });
  };

  // Flush queue periodically
  useEffect(() => {
    flushInterval.current = setInterval(async () => {
      if (!getToken()) {
        // If user is logged out, drop queued events and avoid 401 spam.
        eventQueue.current = [];
        return;
      }
      if (eventQueue.current.length === 0) return;

      const events = [...eventQueue.current];
      eventQueue.current = []; // Clear queue

      try {
        await api.post('/smart/telemetry', { events });
      } catch (err: any) {
        // Silent on auth/network errors — telemetry is best-effort.
        const status = err?.response?.status;
        const code = err?.code;
        const isTransient = status === 401
          || status === 404
          || code === 'ERR_NETWORK'
          || code === 'ECONNABORTED'
          || code === 'ERR_CANCELED';
        if (!isTransient) {
          console.warn('[smart] telemetry failed', err?.message || err);
        }
      }
    }, 10000); // Every 10 seconds

    return () => {
      if (flushInterval.current) clearInterval(flushInterval.current);
    };
  }, []);

  return (
    <SmartContext.Provider value={{ suggestions, trackEvent }}>
      {children}
    </SmartContext.Provider>
  );
}

export function useSmart() {
  const context = useContext(SmartContext);
  if (context === undefined) {
    throw new Error('useSmart must be used within a SmartProvider');
  }
  return context;
}
