import { useState, useRef, useEffect } from 'react';
import AudioVisualizer from './AudioVisualizer';
import OpenAI from 'openai';

//load dotenv
import dotenv from 'dotenv';

// Load environment variables from .env file
dotenv.config();
interface ChatMessage {
  role: 'user' | 'assistant';
  content: string;
}
const assistantId = 'asst_7irZB6IXtmhc2qsygBdEWtPD'
// Initialize OpenAI client
const client = new OpenAI({
  apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted
});

export default function VoiceAssistant() {
  const [messages, setMessages] = useState<ChatMessage[]>([]);
  const [input, setInput] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [isListening, setIsListening] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [audioContext, setAudioContext] = useState<AudioContext | null>(null);
  const [analyser, setAnalyser] = useState<AnalyserNode | null>(null);

  const audioRef = useRef<HTMLAudioElement>(null);
  const mediaRecorderRef = useRef<MediaRecorder | null>(null);
  const chunksRef = useRef<Blob[]>([]);
  const streamRef = useRef<MediaStream | null>(null);

  useEffect(() => {
    const initAudio = async () => {
      try {
        const context = new (window.AudioContext)();
        const analyserNode = context.createAnalyser();
        analyserNode.fftSize = 256;
        analyserNode.smoothingTimeConstant = 0.8;

        setAudioContext(context);
        setAnalyser(analyserNode);

        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        streamRef.current = stream;
        const source = context.createMediaStreamSource(stream);
        source.connect(analyserNode);
      } catch (error) {
        console.error('Error initializing audio:', error);
        setError('فشل في تهيئة الصوت. يرجى التحقق من إذن الميكروفون.');
      }
    };

    initAudio();

    return () => {
      if (streamRef.current) {
        streamRef.current.getTracks().forEach(track => track.stop());
      }
      if (audioContext) {
        audioContext.close();
      }
    };
  }, []);

  const startListening = () => {
    if (!window.SpeechRecognition && !window.webkitSpeechRecognition) {
      setError('متصفحك لا يدعم التعرف على الصوت.');
      return;
    }

    const SpeechRecognition =
      window.SpeechRecognition || window.webkitSpeechRecognition;
    const recognition = new SpeechRecognition();
    recognition.lang = 'ar-SA';
    recognition.continuous = false;
    recognition.interimResults = false;

    recognition.onstart = () => setIsListening(true);
    recognition.onerror = (event) => {
      console.error('Speech recognition error:', event.error);
      setError('حدث خطأ أثناء التعرف على الصوت.');
      setIsListening(false);
    };

    recognition.onresult = async (event) => {
      const transcript = event.results[0][0].transcript;
      setIsListening(false);
      await sendMessage(transcript);
    };

    recognition.onend = () => setIsListening(false);
    recognition.start();
  };

  const stopListening = () => {
    setIsListening(false);
  };

  const sendMessage = async (content: string) => {
    if (!content.trim()) return;

    try {
      setError(null);
      const newMessage: ChatMessage = { role: 'user', content };
      setMessages(prev => [...prev, newMessage]);
      setInput('');
      setIsLoading(true);

      // Simulate API call to ChatGPT
      const response = await sendToChatGPT(content);
      setMessages(prev => [...prev, response]);
    } catch (error) {
      console.error('Error sending message:', error);
      setError('فشل في إرسال الرسالة');
    } finally {
      setIsLoading(false);
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    await sendMessage(input);
  };

  return (
    <div className="w-full max-w-2xl mx-auto bg-white dark:bg-gray-800 rounded-lg shadow-lg overflow-hidden">
      {audioContext && analyser && (
        <AudioVisualizer audioContext={audioContext} analyser={analyser} />
      )}

      <div className="h-96 overflow-y-auto p-4 space-y-4">
        {messages.map((message, index) => (
          <div
            key={index}
            className={`flex ${
              message.role === 'user' ? 'justify-end' : 'justify-start'
            }`}
          >
            <div
              className={`max-w-[80%] rounded-lg p-3 ${
                message.role === 'user'
                  ? 'bg-primary text-white'
                  : 'bg-gray-100 dark:bg-gray-700'
              }`}
            >
              {message.content}
            </div>
          </div>
        ))}
        {isLoading && (
          <div className="flex justify-center animate-pulse text-primary">
            جاري المعالجة...
          </div>
        )}
        {error && (
          <div className="flex justify-center text-red-500">
            {error}
          </div>
        )}
      </div>

      <div className="border-t dark:border-gray-700">
        <form onSubmit={handleSubmit} className="p-4 flex gap-2">
          <input
            type="text"
            value={input}
            onChange={(e) => setInput(e.target.value)}
            placeholder="اكتب رسالتك هنا..."
            className="flex-1 rounded-lg border dark:border-gray-700 dark:bg-gray-800 p-2"
          />
          <button
            type="button"
            onClick={isListening ? stopListening : startListening}
            className={`p-2 rounded-lg ${
              isListening ? 'bg-red-500' : 'bg-primary'
            } text-white`}
          >
            {isListening ? 'إيقاف' : 'استماع'}
          </button>
          <button type="submit" className="bg-primary text-white p-2 rounded-lg">
            إرسال
          </button>
        </form>
      </div>
    </div>
  );
}
const thread = await client.beta.threads.create();
const threadId = thread.id;

async function sendToChatGPT(content: string): Promise<ChatMessage> {
  try {
    // Create a user message in the thread
    const response = await client.beta.threads.messages.create(threadId, {
      role: "user",
      content: content,
    });

    // Create a run and wait for it to complete
    const run = await client.beta.threads.runs.createAndPoll(thread.id, {
      assistant_id: assistantId,
    });
    if (run.status !== "completed") {
      throw new Error("Run failed: " + run.status);
    }

    // Fetch all messages in the thread
    const messagesCursor = await client.beta.threads.messages.list(threadId,{});
    const messages = [];
    for await (const message of messagesCursor) {
      messages.push(message);
    }

    // Get the last message from the assistant
    const assistantMessage = messages.length > 0 ? messages[messages.length - 1].content : null;
    if (!assistantMessage) {
      throw new Error("No response from the assistant");
    }

    // Return the assistant's response
    return { role: 'assistant', content: assistantMessage };

  } catch (error) {
    console.error('Error communicating with OpenAI:', error);
    return { role: 'assistant', content: 'عذرًا، حدث خطأ أثناء الاتصال.' };
  }
}


fix this tsx make it functinal