
'use client';

import { createContext, useContext, useEffect, useState, ReactNode } from 'react';
import { getWebSocketClient } from '@/lib/websocket-client';
import { toast } from '@/components/ui/use-toast';

interface RealtimeContextType {
  isConnected: boolean;
  subscribe: (event: string, callback: (data: any) => void) => () => void;
  send: (event: string, data: any) => void;
}

const RealtimeContext = createContext<RealtimeContextType | undefined>(undefined);

export function RealtimeProvider({ children }: { children: ReactNode }) {
  const [isConnected, setIsConnected] = useState(false);

  useEffect(() => {
    // For now, we'll simulate connection since WebSocket server isn't implemented
    // In production, use actual WebSocket connection
    setIsConnected(true);

    // Simulate real-time notifications
    const interval = setInterval(() => {
      // This would be replaced with actual WebSocket events
    }, 30000);

    return () => clearInterval(interval);
  }, []);

  const subscribe = (event: string, callback: (data: any) => void) => {
    // In production, this would use the actual WebSocket client
    // const wsClient = getWebSocketClient();
    // return wsClient.subscribe(event, callback);
    
    // For now, return a no-op unsubscribe function
    return () => {};
  };

  const send = (event: string, data: any) => {
    // In production, this would use the actual WebSocket client
    // const wsClient = getWebSocketClient();
    // wsClient.send(event, data);
  };

  return (
    <RealtimeContext.Provider value={{ isConnected, subscribe, send }}>
      {children}
    </RealtimeContext.Provider>
  );
}

export function useRealtime() {
  const context = useContext(RealtimeContext);
  if (context === undefined) {
    throw new Error('useRealtime must be used within a RealtimeProvider');
  }
  return context;
}

// Custom hooks for specific real-time features
export function useRealtimeQuotes() {
  const { subscribe } = useRealtime();
  const [quotes, setQuotes] = useState<any[]>([]);

  useEffect(() => {
    const unsubscribe = subscribe('quote:created', (data) => {
      setQuotes(prev => [data, ...prev]);
      toast({
        title: 'New Quote Created',
        description: `Quote #${data.quoteNumber} has been created`,
      });
    });

    return unsubscribe;
  }, [subscribe]);

  return quotes;
}

export function useRealtimeLeads() {
  const { subscribe } = useRealtime();
  const [leads, setLeads] = useState<any[]>([]);

  useEffect(() => {
    const unsubscribe = subscribe('lead:created', (data) => {
      setLeads(prev => [data, ...prev]);
      toast({
        title: 'New Lead Received',
        description: `Lead from ${data.firstName} ${data.lastName}`,
      });
    });

    return unsubscribe;
  }, [subscribe]);

  return leads;
}

export function useRealtimeContracts() {
  const { subscribe } = useRealtime();
  const [contracts, setContracts] = useState<any[]>([]);

  useEffect(() => {
    const unsubscribeCreated = subscribe('contract:created', (data) => {
      setContracts(prev => [data, ...prev]);
      toast({
        title: 'Contract Generated',
        description: `Contract #${data.id} has been generated`,
      });
    });

    const unsubscribeSigned = subscribe('contract:signed', (data) => {
      setContracts(prev => 
        prev.map(c => c.id === data.id ? data : c)
      );
      toast({
        title: 'Contract Signed',
        description: `Contract #${data.id} has been signed`,
      });
    });

    return () => {
      unsubscribeCreated();
      unsubscribeSigned();
    };
  }, [subscribe]);

  return contracts;
}
