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

type InputLike = Extract<
  RenderableBlock,
  { type: "input_text" | "input_email" | "input_phone" }
>;

export function BlockInput({ block }: { block: InputLike }) {
  const { sessionId, applyStep, setError, pushMessage } = useSession();
  const [value, setValue] = useState("");
  const [submitting, setSubmitting] = useState(false);

  const inputType =
    block.type === "input_email"
      ? "email"
      : block.type === "input_phone"
        ? "tel"
        : "text";

  const placeholder =
    block.type === "input_text"
      ? block.data.placeholder ?? "Digite aqui..."
      : block.type === "input_email"
        ? "voce@email.com"
        : "(11) 99999-9999";

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

  return (
    <form onSubmit={onSubmit} className="flex gap-2">
      <input
        type={inputType}
        value={value}
        onChange={(e) => setValue(e.target.value)}
        placeholder={placeholder}
        disabled={submitting}
        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={submitting || !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>
  );
}
