import { createContext, useContext, useState, useEffect, useCallback, useRef, ReactNode } from "react";
import { API_URL } from "@/lib/config";
import { supabase } from "@/lib/supabase";
import { RealtimeChannel } from "@supabase/supabase-js";

interface RecentCall {
  id: string;
  time: string;
  caller: string | null;
  duration: string;
  store_id: string;
}

interface DashboardStats {
  totalCalls: { value: number; change: string; changeType: string };
  todayCalls: { value: number; change: string; changeType: string };
  weekCalls: { value: number; change: string; changeType: string };
  avgDuration: { value: number; formatted: string; change: string; changeType: string };
  totalDuration: { value: number; formatted: string; change: string; changeType: string };
  recentCalls: RecentCall[];
}

interface DashboardContextType {
  stats: DashboardStats | null;
  loading: boolean;
  error: string | null;
  refetch: () => void;
  isRealtimeConnected: boolean;
}

const DashboardContext = createContext<DashboardContextType | undefined>(undefined);

export function DashboardProvider({ children }: { children: ReactNode }) {
  const [stats, setStats] = useState<DashboardStats | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [isRealtimeConnected, setIsRealtimeConnected] = useState(false);
  const [userStoreIds, setUserStoreIds] = useState<string[]>([]);
  const channelRef = useRef<RealtimeChannel | null>(null);

  const fetchStats = useCallback(async (showLoading = true) => {
    try {
      if (showLoading) setLoading(true);
      setError(null);

      const { data: { session } } = await supabase.auth.getSession();
      if (!session) {
        throw new Error('Not authenticated');
      }

      const response = await fetch(`${API_URL}/api/dashboard/stats`, {
        headers: {
          'Authorization': `Bearer ${session.access_token}`,
          'Content-Type': 'application/json'
        }
      });

      if (!response.ok) {
        throw new Error('Failed to fetch dashboard stats');
      }

      const data = await response.json();
      if (data.success) {
        setStats(data.stats);
      }
    } catch (err) {
      console.error('Error fetching dashboard stats:', err);
      setError(err instanceof Error ? err.message : 'Failed to load stats');
    } finally {
      setLoading(false);
    }
  }, []);

  // Fetch user's store IDs for realtime filtering
  const fetchUserStoreIds = useCallback(async () => {
    try {
      const { data: { session } } = await supabase.auth.getSession();
      if (!session) return [];

      const { data: stores } = await supabase
        .from('stores')
        .select('id')
        .eq('user_id', session.user.id);

      return stores?.map(s => s.id) || [];
    } catch (err) {
      console.error('Failed to fetch store IDs:', err);
      return [];
    }
  }, []);

  // Setup realtime subscription
  const setupRealtimeSubscription = useCallback(async (storeIds: string[]) => {
    // Clean up existing subscription
    if (channelRef.current) {
      await supabase.removeChannel(channelRef.current);
      channelRef.current = null;
    }

    if (storeIds.length === 0) {
      console.log('[Dashboard Realtime] No stores to subscribe to');
      return;
    }

    console.log('[Dashboard Realtime] Setting up subscription for stores:', storeIds);

    const channel = supabase
      .channel(`dashboard_realtime_${Date.now()}`)
      .on(
        'postgres_changes',
        {
          event: '*',
          schema: 'public',
          table: 'call_logs',
          filter: storeIds.length === 1
            ? `store_id=eq.${storeIds[0]}`
            : `store_id=in.(${storeIds.join(',')})`
        },
        (payload) => {
          console.log('[Dashboard Realtime] Received event:', payload.eventType);
          // Refetch stats without showing loading indicator
          fetchStats(false);
        }
      )
      .subscribe((status) => {
        console.log('[Dashboard Realtime] Subscription status:', status);
        setIsRealtimeConnected(status === 'SUBSCRIBED');
      });

    channelRef.current = channel;
  }, [fetchStats]);

  useEffect(() => {
    const initialize = async () => {
      await fetchStats();
      const storeIds = await fetchUserStoreIds();
      setUserStoreIds(storeIds);
      await setupRealtimeSubscription(storeIds);
    };

    initialize();

    // Cleanup on unmount
    return () => {
      if (channelRef.current) {
        console.log('[Dashboard Realtime] Cleaning up subscription');
        supabase.removeChannel(channelRef.current);
        channelRef.current = null;
      }
    };
  }, [fetchStats, fetchUserStoreIds, setupRealtimeSubscription]);

  return (
    <DashboardContext.Provider value={{ stats, loading, error, refetch: fetchStats, isRealtimeConnected }}>
      {children}
    </DashboardContext.Provider>
  );
}

export function useDashboard() {
  const context = useContext(DashboardContext);
  if (context === undefined) {
    throw new Error('useDashboard must be used within a DashboardProvider');
  }
  return context;
}
