import { create } from "zustand";
import type { BotMeta, EngineStep, Message, RenderableBlock } from "../types/flow";

type SessionState = {
  meta: BotMeta | null;
  sessionId: string | null;
  currentBlock: RenderableBlock | null;
  messages: Message[];
  status: "idle" | "loading" | "active" | "completed" | "error";
  error: string | null;
  redirectUrl: string | null;

  setMeta: (m: BotMeta) => void;
  startSession: (sessionId: string, step: EngineStep) => void;
  pushMessage: (m: Message) => void;
  applyStep: (step: EngineStep) => void;
  setError: (msg: string) => void;
};

export const useSession = create<SessionState>((set) => ({
  meta: null,
  sessionId: null,
  currentBlock: null,
  messages: [],
  status: "idle",
  error: null,
  redirectUrl: null,

  setMeta: (m) => set({ meta: m }),

  startSession: (sessionId, step) => {
    set({ sessionId, status: "active", error: null });
    applyStepInternal(set, step);
  },

  pushMessage: (m) =>
    set((s) => ({ messages: [...s.messages, m] })),

  applyStep: (step) => applyStepInternal(set, step),

  setError: (msg) => set({ status: "error", error: msg }),
}));

function applyStepInternal(
  set: (partial: Partial<SessionState> | ((s: SessionState) => Partial<SessionState>)) => void,
  step: EngineStep,
): void {
  if (step.kind === "complete") {
    set({
      status: "completed",
      currentBlock: null,
      redirectUrl: step.redirect?.url ?? null,
    });
    if (step.redirect?.url) {
      setTimeout(() => {
        window.location.href = step.redirect!.url;
      }, 1500);
    }
    return;
  }

  set((s) => {
    const block = step.block;
    const messages = [...s.messages];

    // Adiciona mensagem do bot pra blocos textuais
    if (block.type === "text") {
      messages.push({
        role: "bot",
        content: block.data.content,
        block_id: block.id,
        ts: Date.now(),
      });
    } else if (
      block.type === "input_text" ||
      block.type === "input_email" ||
      block.type === "input_phone" ||
      block.type === "choice" ||
      block.type === "multi_choice"
    ) {
      messages.push({
        role: "bot",
        content: block.data.prompt,
        block_id: block.id,
        ts: Date.now(),
      });
    }

    return { currentBlock: block, messages };
  });
}
