"use client";

import { useRef, useEffect, useCallback, useState } from "react";
import { useEchoStore } from "@/stores/echo-store";
import { Message } from "@/stores/echo-store";
import { cn } from "@/lib/utils";
import { Bot, User, Volume2, VolumeX, Loader2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";

function MessageBubble({ message }: { message: Message }) {
  const isUser = message.role === "user";
  const { autoSpeak, isSpeaking, setIsSpeaking } = useEchoStore();
  const [hasSpoken, setHasSpoken] = useState(false);

  const speakText = useCallback(
    (text: string) => {
      if (hasSpoken) return;
      if (!autoSpeak || !window.speechSynthesis) return;

      window.speechSynthesis.cancel();
      const utterance = new SpeechSynthesisUtterance(text);
      utterance.rate = 1.0;
      utterance.pitch = 1.0;
      utterance.onstart = () => setIsSpeaking(true);
      utterance.onend = () => {
        setIsSpeaking(false);
        setHasSpoken(true);
      };
      utterance.onerror = () => {
        setIsSpeaking(false);
        setHasSpoken(true);
      };
      window.speechSynthesis.speak(utterance);
    },
    [autoSpeak, hasSpoken, setIsSpeaking]
  );

  useEffect(() => {
    if (!isUser && autoSpeak && message.content) {
      speakText(message.content);
    }
    return () => {
      setHasSpoken(false);
    };
  }, [message.content, message.id, autoSpeak, speakText]);

  const handleManualSpeak = () => {
    if (window.speechSynthesis) {
      window.speechSynthesis.cancel();
      if (isSpeaking) {
        setIsSpeaking(false);
        return;
      }
      speakText(message.content);
      setHasSpoken(false);
    }
  };

  return (
    <div
      className={cn(
        "flex gap-3 px-4 py-3 group",
        isUser ? "flex-row-reverse" : ""
      )}
    >
      {/* Avatar */}
      <div
        className={cn(
          "flex items-center justify-center h-8 w-8 rounded-full shrink-0",
          isUser
            ? "bg-primary text-primary-foreground"
            : "bg-muted text-muted-foreground"
        )}
      >
        {isUser ? <User className="h-4 w-4" /> : <Bot className="h-4 w-4" />}
      </div>

      {/* Content */}
      <div
        className={cn(
          "max-w-[75%] rounded-2xl px-4 py-2.5 text-sm leading-relaxed",
          isUser
            ? "bg-primary text-primary-foreground rounded-tr-sm"
            : "bg-muted text-muted-foreground rounded-tl-sm"
        )}
      >
        {message.content}
      </div>

      {/* Speak button (assistant messages only) */}
      {!isUser && window.speechSynthesis && (
        <Button
          variant="ghost"
          size="icon"
          className={cn(
            "h-7 w-7 shrink-0 opacity-0 group-hover:opacity-100 transition-opacity self-center",
            isSpeaking && "opacity-100 text-primary"
          )}
          onClick={handleManualSpeak}
        >
          {isSpeaking ? (
            <VolumeX className="h-3.5 w-3.5" />
          ) : (
            <Volume2 className="h-3.5 w-3.5" />
          )}
        </Button>
      )}
    </div>
  );
}

export function ChatArea() {
  const {
    messages,
    activeConversationId,
    isGenerating,
    streamingContent,
    loadMessages,
    isLoadingMessages,
  } = useEchoStore();

  const scrollRef = useRef<HTMLDivElement>(null);
  const bottomRef = useRef<HTMLDivElement>(null);

  // Load messages when conversation changes
  useEffect(() => {
    if (activeConversationId) {
      loadMessages(activeConversationId);
    }
  }, [activeConversationId, loadMessages]);

  // Auto-scroll to bottom
  useEffect(() => {
    bottomRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages, streamingContent]);

  // No active conversation
  if (!activeConversationId) {
    return (
      <div className="flex-1 flex items-center justify-center p-8">
        <div className="text-center space-y-4 max-w-md">
          <div className="mx-auto w-16 h-16 rounded-2xl bg-primary/10 flex items-center justify-center">
            <Bot className="h-8 w-8 text-primary" />
          </div>
          <h2 className="text-2xl font-semibold">Echo Voice Assistant</h2>
          <p className="text-muted-foreground text-sm leading-relaxed">
            Start a new conversation to begin talking with Echo. You can type
            messages or use your voice to interact.
          </p>
        </div>
      </div>
    );
  }

  if (isLoadingMessages) {
    return (
      <div className="flex-1 flex items-center justify-center">
        <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
      </div>
    );
  }

  return (
    <ScrollArea className="flex-1" ref={scrollRef}>
      <div className="max-w-3xl mx-auto py-4">
        {messages.length === 0 && !isGenerating && (
          <div className="flex items-center justify-center h-full min-h-[300px]">
            <p className="text-muted-foreground text-sm">
              Say something to start the conversation...
            </p>
          </div>
        )}

        {messages.map((msg) => (
          <MessageBubble key={msg.id} message={msg} />
        ))}

        {/* Streaming response */}
        {isGenerating && streamingContent && (
          <div className="flex gap-3 px-4 py-3">
            <div className="flex items-center justify-center h-8 w-8 rounded-full shrink-0 bg-muted text-muted-foreground">
              <Bot className="h-4 w-4" />
            </div>
            <div className="max-w-[75%] rounded-2xl rounded-tl-sm px-4 py-2.5 bg-muted text-muted-foreground text-sm leading-relaxed">
              {streamingContent}
              <span className="inline-block w-1.5 h-4 bg-current/60 animate-pulse ml-0.5 align-text-bottom" />
            </div>
          </div>
        )}

        {/* Generating indicator (no content yet) */}
        {isGenerating && !streamingContent && (
          <div className="flex gap-3 px-4 py-3">
            <div className="flex items-center justify-center h-8 w-8 rounded-full shrink-0 bg-muted text-muted-foreground">
              <Bot className="h-4 w-4" />
            </div>
            <div className="rounded-2xl rounded-tl-sm px-4 py-3 bg-muted">
              <div className="flex gap-1.5 items-center">
                <div className="w-2 h-2 rounded-full bg-muted-foreground/40 animate-bounce [animation-delay:0ms]" />
                <div className="w-2 h-2 rounded-full bg-muted-foreground/40 animate-bounce [animation-delay:150ms]" />
                <div className="w-2 h-2 rounded-full bg-muted-foreground/40 animate-bounce [animation-delay:300ms]" />
              </div>
            </div>
          </div>
        )}

        <div ref={bottomRef} />
      </div>
    </ScrollArea>
  );
}
