"use client";

import { useEffect, useRef, useState } from "react";

/**
 * O "resolveu?" do fim do artigo.
 *
 * Mede o que leitura sozinha não mede: se a pessoa foi embora sabendo. O
 * artigo mais lido do help pode ser o mais confuso, e sem esta pergunta os
 * dois seriam indistinguíveis no painel.
 *
 * A resposta vai por rota, com a chave de serviço. Uma por pessoa por artigo:
 * mudar de ideia sobrescreve, em vez de somar duas respostas da mesma pessoa e
 * sujar o percentual.
 */

export default function Resolveu({ artigoId }: { artigoId: string }) {
  const [respondido, setRespondido] = useState<null | boolean>(null);
  const [enviando, setEnviando] = useState(false);
  const jaContou = useRef(false);

  /* A leitura é contada daqui, e não da página: ela é servida do cache por um
     minuto, e contar lá daria uma leitura por minuto em vez de uma por pessoa.
     O efeito só dispara uma chamada e não mexe em estado nenhum, então não
     esbarra na regra da casa sobre `setState` dentro de efeito. */
  useEffect(() => {
    if (jaContou.current) return;
    jaContou.current = true;
    void fetch("/api/help/resposta", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ article_id: artigoId, acao: "leitura" }),
    }).catch(() => undefined);
  }, [artigoId]);

  async function responder(ajudou: boolean) {
    setEnviando(true);
    try {
      await fetch("/api/help/resposta", {
        method: "POST",
        headers: { "content-type": "application/json" },
        body: JSON.stringify({ article_id: artigoId, helpful: ajudou }),
      });
      setRespondido(ajudou);
    } catch {
      /* Resposta que não chegou não vira erro na cara de quem leu: ela é um
         sinal para a gente, não uma tarefa da pessoa. */
      setRespondido(ajudou);
    } finally {
      setEnviando(false);
    }
  }

  return (
    <div className="hl-util">
      <div>
        <h4>Este artigo resolveu?</h4>
        <p>
          {respondido === null
            ? "Sua resposta guia o que a gente escreve depois."
            : respondido
            ? "Que bom. Obrigado por dizer."
            : "Anotado. Este artigo entra na fila de revisão."}
        </p>
      </div>

      {respondido === null ? (
        <div className="hl-util-bts">
          <button type="button" className="hl-util-bt" disabled={enviando} onClick={() => void responder(true)}>
            <svg width="17" height="17" viewBox="0 0 24 24" fill="none" aria-hidden="true">
              <path d="M7 10.6 11.2 4a2.1 2.1 0 0 1 3.9 1.1V9h4a2 2 0 0 1 2 2.4l-1.4 6.6a2.6 2.6 0 0 1-2.5 2H7" stroke="currentColor" strokeWidth="1.9" strokeLinejoin="round" />
              <rect x="2.8" y="10.6" width="4.2" height="9.4" rx="1.4" stroke="currentColor" strokeWidth="1.9" />
            </svg>
            Sim
          </button>
          <button type="button" className="hl-util-bt" disabled={enviando} onClick={() => void responder(false)}>
            <svg width="17" height="17" viewBox="0 0 24 24" fill="none" style={{ transform: "rotate(180deg)" }} aria-hidden="true">
              <path d="M7 10.6 11.2 4a2.1 2.1 0 0 1 3.9 1.1V9h4a2 2 0 0 1 2 2.4l-1.4 6.6a2.6 2.6 0 0 1-2.5 2H7" stroke="currentColor" strokeWidth="1.9" strokeLinejoin="round" />
              <rect x="2.8" y="10.6" width="4.2" height="9.4" rx="1.4" stroke="currentColor" strokeWidth="1.9" />
            </svg>
            Não
          </button>
        </div>
      ) : (
        <span className="hl-util-obrigado">Obrigado!</span>
      )}
    </div>
  );
}
