"use client";
import React, { createContext, useContext, useState, useEffect } from 'react';
import { core } from '@tauri-apps/api';
import { User, ChatInstance } from '../types';

interface ChatContextType {
  line: any;
  user: User;
  instance: ChatInstance | null;
  sendActivity: (activity: any) => void;
  selectedVoice: any;
  setVoice: (voice: any) => void;
}

const ChatContext = createContext<ChatContextType | undefined>(undefined);

export function ChatProvider({ children }: { children: React.ReactNode }) {
  const [line, setLine] = useState<any>(null);
  const [instance, setInstance] = useState<ChatInstance | null>(null);
  const [selectedVoice, setSelectedVoice] = useState(null);
  const [user] = useState<User>({
    id: `user_${Math.random().toString(36).slice(2)}`,
    name: 'You'
  });
  
  useEffect(() => {
    const initializeChat = async () => {
      try {
        const botId = window.location.pathname.split('/')[1] || 'default';
        const instanceData = await core.invoke('get_chat_instance', { botId });
        setInstance(instanceData as ChatInstance);
        
        // Initialize DirectLine or other chat service
        const directLine = { 
          activity$: { subscribe: () => {} },
          postActivity: () => ({ subscribe: () => {} })
        };
        setLine(directLine);
      } catch (error) {
        console.error('Failed to initialize chat:', error);
      }
    };

    initializeChat();
  }, []);

  const sendActivity = async (activity: any) => {
    try {
      await core.invoke('send_chat_activity', {
        activity: {
          ...activity,
          from: user,
          timestamp: new Date().toISOString()
        }
      });
      line?.postActivity(activity).subscribe();
    } catch (error) {
      console.error('Failed to send activity:', error);
    }
  };

  const setVoice = (voice: any) => {
    setSelectedVoice(voice);
  };

  return (
    <ChatContext.Provider value={{ line, user, instance, sendActivity, selectedVoice, setVoice }}>
      {children}
    </ChatContext.Provider>
  );
}

export function useChat() {
  const context = useContext(ChatContext);
  if (!context) {
    throw new Error('useChat must be used within ChatProvider');
  }
  return context;
}
