import { useEffect, useRef } from "react";
import { useSession } from "../store/session";
import { MessageBubble } from "./MessageBubble";
import { BlockText } from "./BlockText";
import { BlockChoice } from "./BlockChoice";
import { BlockInput } from "./BlockInput";
import { BlockAI } from "./BlockAI";
import { BlockMedia } from "./BlockMedia";

export function BotRenderer() {
  const { meta, currentBlock, messages, status, redirectUrl } = useSession();
  const scrollRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    scrollRef.current?.scrollTo({
      top: scrollRef.current.scrollHeight,
      behavior: "smooth",
    });
  }, [messages, currentBlock]);

  if (!meta) return null;

  return (
    <div className="flex h-full flex-col bg-[var(--bot-bg-dark)] text-white">
      {/* Header */}
      <header className="flex items-center gap-3 border-b border-white/10 px-4 py-3">
        <div
          className="flex h-9 w-9 items-center justify-center rounded-full font-semibold"
          style={{
            background: `linear-gradient(135deg, var(--bot-primary), var(--bot-secondary))`,
            color: "var(--bot-text-on-primary)",
          }}
        >
          {meta.theme.avatar_letter ?? meta.bot_name[0]?.toUpperCase()}
        </div>
        <div className="flex-1">
          <h1 className="text-sm font-semibold">{meta.bot_name}</h1>
          <p className="text-xs opacity-60">Online agora</p>
        </div>
      </header>

      {/* Conversa */}
      <div ref={scrollRef} className="flex-1 overflow-y-auto px-4 py-6">
        <div className="mx-auto flex max-w-2xl flex-col gap-3">
          {messages.map((m, i) => (
            <MessageBubble
              key={i}
              role={m.role}
              content={m.content}
              avatarLetter={meta.theme.avatar_letter ?? meta.bot_name[0]}
            />
          ))}

          {status === "completed" && (
            <div className="mt-4 rounded-lg bg-white/5 p-4 text-center text-sm opacity-80">
              {redirectUrl ? "Redirecionando..." : "Conversa finalizada."}
            </div>
          )}
        </div>
      </div>

      {/* Bloco interativo */}
      {currentBlock && status === "active" && (
        <div className="border-t border-white/10 bg-black/30 p-4">
          <div className="mx-auto max-w-2xl">{renderBlock(currentBlock)}</div>
        </div>
      )}
    </div>
  );
}

function renderBlock(block: NonNullable<ReturnType<typeof useSession>["currentBlock"]>) {
  switch (block.type) {
    case "text":
      return <BlockText block={block} />;
    case "image":
    case "video":
      return <BlockMedia block={block} />;
    case "input_text":
    case "input_email":
    case "input_phone":
      return <BlockInput block={block} />;
    case "choice":
      return <BlockChoice block={block} />;
    case "multi_choice":
      return <BlockChoice block={block} />;
    case "ai":
      return <BlockAI block={block} />;
    default:
      return null;
  }
}
