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

type ChoiceLike = Extract<RenderableBlock, { type: "choice" | "multi_choice" }>;

export function BlockChoice({ block }: { block: ChoiceLike }) {
  const { sessionId, applyStep, setError, pushMessage } = useSession();
  const [selected, setSelected] = useState<number[]>([]);
  const [submitting, setSubmitting] = useState(false);

  const isMulti = block.type === "multi_choice";

  const submit = async (indices: number[]) => {
    if (!sessionId) return;
    setSubmitting(true);
    try {
      const labels = indices.map((i) => block.data.options[i]?.label ?? "");
      pushMessage({
        role: "user",
        content: labels.join(", "),
        block_id: block.id,
        ts: Date.now(),
      });

      const answer = isMulti
        ? { values: indices.map((i) => block.data.options[i]?.value).filter(Boolean) as string[] }
        : { choice_index: indices[0], value: block.data.options[indices[0]!]?.value };

      const { step } = await answerBlock(sessionId, block.id, answer);
      applyStep(step);
    } catch (err) {
      setError((err as Error).message);
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <div className="flex flex-col gap-2">
      <div className="flex flex-wrap gap-2">
        {block.data.options.map((opt, i) => {
          const isSelected = selected.includes(i);
          return (
            <motion.button
              key={i}
              whileTap={{ scale: 0.96 }}
              disabled={submitting}
              onClick={() => {
                if (isMulti) {
                  setSelected((s) =>
                    s.includes(i) ? s.filter((x) => x !== i) : [...s, i],
                  );
                } else {
                  void submit([i]);
                }
              }}
              className={`rounded-full px-4 py-2 text-sm font-medium transition disabled:opacity-50 ${
                isSelected
                  ? "ring-2 ring-white/60"
                  : "hover:bg-white/15"
              }`}
              style={{
                background: isSelected ? "var(--bot-primary)" : "rgba(255,255,255,0.08)",
                color: isSelected ? "var(--bot-text-on-primary)" : "white",
              }}
            >
              {opt.label}
            </motion.button>
          );
        })}
      </div>
      {isMulti && selected.length > 0 && (
        <button
          onClick={() => submit(selected)}
          disabled={submitting}
          className="self-start rounded-full px-4 py-2 text-sm font-semibold text-[var(--bot-text-on-primary)] disabled:opacity-50"
          style={{ background: "var(--bot-primary)" }}
        >
          Confirmar ({selected.length})
        </button>
      )}
    </div>
  );
}
