import { useState, useRef, useEffect, type SubmitEvent } from 'react';
import OpenAI from 'openai';

const ai = new OpenAI({
  apiKey: 'ollama',
  baseURL: 'http://localhost:11434/v1',
  dangerouslyAllowBrowser: true,
});

export type Message = {
  role: 'user' | 'assistant' | 'system';
  content: string;
};

export function useChat() {
  const [messages, setMessages] = useState<Message[]>([
    {
      role: 'assistant',
      content: 'Hallo! Ich bin Llama3.2. Wie kann ich Ihnen helfen?',
    },
  ]);
  const [input, setInput] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const endRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    endRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  const send = async (e: SubmitEvent) => {
    e.preventDefault();
    if (!input.trim() || isLoading) return;

    const next: Message[] = [
      ...messages,
      { role: 'user', content: input.trim() },
    ];
    setMessages(next);
    setInput('');
    setIsLoading(true);

    try {
      const stream = await ai.chat.completions.create({
        model: 'llama3.2:1b',
        messages: next,
        stream: true,
      });
      let content = '';
      setMessages([...next, { role: 'assistant', content: '' }]);
      for await (const chunk of stream) {
        const delta = chunk.choices[0]?.delta?.content;
        if (delta) {
          content += delta;
          setMessages([...next, { role: 'assistant', content }]);
        }
      }
      if (!content) {
        setMessages([
          ...next,
          { role: 'assistant', content: 'Keine Antwort.' },
        ]);
      }
    } catch {
      setMessages([
        ...next,
        {
          role: 'assistant',
          content: 'Verbindung zu Ollama fehlgeschlagen. Ist es aktiv?',
        },
      ]);
    } finally {
      setIsLoading(false);
    }
  };

  return { messages, input, setInput, isLoading, endRef, send };
}
