import LoaderSun from "@/components/common/Loader/LoaderSun";
import PDFViewer from "@/components/PdfViewer/PDFViewer";
import { obterArquivosPorCaminho } from "@/requests/CRUD/DocumentosGerados/obterDocumentoPersonalizadoGeradoPorId";
import { Maximize } from "lucide-react";
import { useEffect, useRef, useState } from "react";

const VisualizarDocGerado = ({ caminho }: any) => {
  const [documento, setDocumento] = useState<any>();
  const [isLoading, setIsLoading] = useState(true);
  const [isPdfFullscreen, setIsPdfFullscreen] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const pdfContainerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (caminho) {
      setIsLoading(true);
      setError(null);

      obterArquivosPorCaminho(caminho)
        .then((res) => {
          setIsLoading(false);
          setDocumento(res);

          if (!res?.link_documento_gerado) {
            setError("Documento carregado mas sem link válido");
          }
        })
        .catch((err) => {
          setIsLoading(false);
          setError(`Erro ao carregar documento: ${err.message}`);
        });
    } else {
      setError("Nenhum caminho de documento fornecido");
      setIsLoading(false);
    }
  }, [caminho]);

  const handleFullscreen = () => {
    if (pdfContainerRef.current) {
      const container = pdfContainerRef.current;
      if (container.requestFullscreen) {
        container.requestFullscreen();
        setIsPdfFullscreen(true);
      } else if ((container as any).webkitRequestFullscreen) {
        (container as any).webkitRequestFullscreen(); // Safari
        setIsPdfFullscreen(true);
      } else if ((container as any).msRequestFullscreen) {
        (container as any).msRequestFullscreen(); // IE11
        setIsPdfFullscreen(true);
      }
    }
  };

  // Listener para detectar quando sai do fullscreen
  useEffect(() => {
    const handleFullscreenChange = () => {
      if (!document.fullscreenElement) {
        setIsPdfFullscreen(false);
      }
    };

    document.addEventListener("fullscreenchange", handleFullscreenChange);
    document.addEventListener("webkitfullscreenchange", handleFullscreenChange);
    document.addEventListener("msfullscreenchange", handleFullscreenChange);

    return () => {
      document.removeEventListener("fullscreenchange", handleFullscreenChange);
      document.removeEventListener(
        "webkitfullscreenchange",
        handleFullscreenChange
      );
      document.removeEventListener(
        "msfullscreenchange",
        handleFullscreenChange
      );
    };
  }, []);

  return (
    <div className="flex w-full">
      <div className="flex flex-col w-full items-center bg-white rounded-2xl p-2">
        <div className="flex justify-between w-full mb-2">
          <div className="flex gap-2">
            {/* Espaço para futuros controles */}
          </div>
          <div></div>
        </div>

        <div className="flex w-full justify-center">
          {isLoading ? (
            <div className="flex justify-center my-5">
              <LoaderSun />
            </div>
          ) : error ? (
            <div className="flex flex-col items-center justify-center p-8 bg-red-50 border border-red-200 rounded-lg">
              <div className="text-red-600 text-lg font-semibold mb-2">
                ❌ Erro ao carregar documento
              </div>
              <div className="text-red-500 text-sm text-center mb-4">
                {error}
              </div>
              <button
                onClick={() => window.location.reload()}
                className="bg-red-500 text-white px-4 py-2 rounded hover:bg-red-600"
              >
                🔄 Recarregar Página
              </button>
            </div>
          ) : documento?.link_documento_gerado ? (
            <div
              ref={pdfContainerRef}
              style={{
                width: isPdfFullscreen ? "100vw" : "1000px",
                height: isPdfFullscreen ? "100vh" : "700px",
                backgroundColor: "#f5f5f5",
              }}
              className="border border-gray-300 rounded-lg overflow-hidden"
            >
              <div className="text-xs text-gray-500 p-2 bg-gray-100 flex justify-between items-center">
                <span>
                  📄 Carregando PDF:{" "}
                  {documento.link_documento_gerado.substring(0, 80)}...
                </span>
                <button
                  onClick={handleFullscreen}
                  className=" text-black px-4 py-1 rounded hover:text-primary"
                >
                  <Maximize />
                </button>
              </div>
              <div
                style={{ height: "calc(100% - 40px)", position: "relative" }}
              >
                <PDFViewer pdfUrl={documento.link_documento_gerado} />
              </div>
            </div>
          ) : (
            <div className="flex flex-col items-center justify-center p-8 bg-yellow-50 border border-yellow-200 rounded-lg">
              <div className="text-yellow-600 text-lg font-semibold mb-2">
                ⚠️ Documento sem link
              </div>
              <div className="text-yellow-500 text-sm text-center">
                O documento foi carregado mas não possui um link válido
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default VisualizarDocGerado;
