import { useState, type FormEvent } from "react";
import { useSession } from "../store/session";
import { aiTurn } from "../api/client";
import type { RenderableBlock } from "../types/flow";
import { TypingIndicator } from "./TypingIndicator";

export function BlockAI({ block }: { block: Extract<RenderableBlock, { type: "ai" }> }) {
  const { sessionId, applyStep, setError, pushMessage } = useSession();
  const [value, setValue] = useState("");
  const [thinking, setThinking] = useState(false);

  async function onSubmit(e: FormEvent) {
    e.preventDefault();
    if (!sessionId || !value.trim() || thinking) return;
    const msg = value.trim();
    setValue("");
    pushMessage({ role: "user", content: msg, block_id: block.id, ts: Date.now() });
    setThinking(true);
    try {
      const { reply, step } = await aiTurn(sessionId, block.id, msg);
      pushMessage({ role: "bot", content: reply, block_id: block.id, ts: Date.now() });
      if (step) applyStep(step);
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setThinking(false);
    }
  }

  return (
    <div className="flex flex-col gap-2">
      {thinking && (
        <div className="self-start">
          <TypingIndicator />
        </div>
      )}
      <form onSubmit={onSubmit} className="flex gap-2">
        <input
          type="text"
          value={value}
          onChange={(e) => setValue(e.target.value)}
          placeholder="Digite sua mensagem..."
          disabled={thinking}
          autoFocus
          className="flex-1 rounded-full bg-white/10 px-4 py-2.5 text-base outline-none ring-1 ring-white/10 placeholder:text-white/40 focus:ring-2 focus:ring-[var(--bot-primary)] disabled:opacity-50"
        />
        <button
          type="submit"
          disabled={thinking || !value.trim()}
          className="rounded-full px-5 py-2.5 text-sm font-semibold text-[var(--bot-text-on-primary)] disabled:opacity-50"
          style={{ background: "var(--bot-primary)" }}
        >
          Enviar
        </button>
      </form>
    </div>
  );
}
