"use client";
import React, { createContext, useContext, useState, useEffect } from 'react';
import { User } from '../types';

const ChatContext = createContext(undefined);

async function apiFetch(endpoint, options = {}) {
  const baseUrl = 'http://localhost:4242/';
  const response = await fetch(`${baseUrl}${endpoint}`, options);
  if (!response.ok) throw new Error('API request failed');
  return response.json();
}

export function ChatProvider({ children }) {
  const [line, setLine] = useState(null);
  const [instance, setInstance] = useState(null);
  const [user] = useState<User>({
    id: `user_${Math.random().toString(36).slice(2)}`,
    name: 'You',
  });

  useEffect(() => {
    const initializeChat = async () => {
      try {
        const botId = 'doula'; // Default bot ID
        const instanceData = await apiFetch(`/instances/${botId}`);
        setInstance(instanceData);

        const chatService = {
          activity$: { subscribe: () => {} },
          postActivity: () => ({
            subscribe: () => {
              return { unsubscribe: () => {} };
            },
          }),
        };
        setLine(chatService);
      } catch (error) {
        console.error('Failed to initialize chat:', error);
      }
    };
    initializeChat();
  }, []);

  const sendActivity = async (activity) => {
    try {
      const fullActivity = {
        ...activity,
        from: user,
        timestamp: new Date().toISOString(),
      };
      await apiFetch('/activities', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(fullActivity),
      });
      line?.postActivity(fullActivity).subscribe();
    } catch (error) {
      console.error('Failed to send activity:', error);
    }
  };

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

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