import { checkTemplate, getInputFromTemplate, Template } from "@pdfme/common";
import { Viewer } from "@pdfme/ui";
import { useEffect, useRef, useState } from "react";

import LoaderSun from "@/components/common/Loader/LoaderSun";
import { obterTemplateProposta } from "@/requests/CRM/Proposta/obterTemplateProposta";
import { baixarAwsContent } from "@/requests/common/Aws/baixarAws";
import { getFontsData, getPlugins, isJsonString } from "@/utils/pdfme/helper";
import { toast } from "react-toastify";

const VisualizarTemplateProposta = ({ dadosCard }: any) => {
  const uiRef = useRef<HTMLDivElement | null>(null);
  const ui = useRef<Viewer | null>(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [documentId, setDocumentId] = useState<string | null>(null);

  useEffect(() => {
    let cancelado = false;

    const carregarTemplate = async () => {
      try {
        const res = await obterTemplateProposta({
          id_tipo_negocio: dadosCard?.tipoNegocio_coleta,
          id_loja: dadosCard?.id_loja_coleta,
        });

        if (!res) {
          toast.error(
            "Nenhum template encontrado para esse tipo de negócio e loja"
          );
          return;
        }

        // Template usado na geração real (Google Docs)
        if (res.documentId_templateProposta_loja) {
          if (!cancelado) {
            setDocumentId(res.documentId_templateProposta_loja);
            setIsLoaded(true);
          }
          return;
        }

        // Fallback: template pdfme (fluxo antigo)
        const templateString = await baixarAwsContent(
          res.caminho_templateProposta_loja
        );

        if (!isJsonString(templateString)) {
          toast.error("Template da proposta inválido ou não encontrado");
          return;
        }

        const template = JSON.parse(templateString) as Template;
        checkTemplate(template);

        const font = await getFontsData();

        if (cancelado || !uiRef.current) return;

        ui.current = new Viewer({
          domContainer: uiRef.current,
          // @ts-ignore
          template,
          inputs: getInputFromTemplate(template) ?? [{}],
          options: {
            font,
            theme: {
              token: {
                colorPrimary: "#25c2a0",
              },
            },
          },
          plugins: getPlugins(),
        });

        setIsLoaded(true);
      } catch (err) {
        console.error("Erro ao carregar o template da proposta", err);
        toast.error("Erro ao carregar o template da proposta");
      }
    };

    carregarTemplate();

    return () => {
      cancelado = true;
      if (ui.current) {
        ui.current.destroy();
        ui.current = null;
      }
    };
  }, []);

  return (
    <div className="relative w-full h-[75vh] mt-4">
      {!isLoaded && (
        <div className="absolute inset-0 flex items-center justify-center">
          <LoaderSun />
        </div>
      )}
      {documentId ? (
        <div className="w-full h-full flex flex-col gap-2">
          <a
            href={`https://docs.google.com/document/d/${documentId}/edit`}
            target="_blank"
            rel="noreferrer"
            className="text-primary underline text-sm w-fit"
          >
            Abrir no Google Docs
          </a>
          <iframe
            src={`https://docs.google.com/document/d/${documentId}/preview`}
            className="w-full h-full rounded-md border border-stroke"
            title="Template da Proposta"
          />
        </div>
      ) : (
        <div ref={uiRef} className="w-full h-full" />
      )}
    </div>
  );
};

export default VisualizarTemplateProposta;
