import type { StorageindexId } from "~/schemas/public/Storageindex";
import { api } from "~/utils/api";
import { LoadingPage } from "~/components/loading";
import { AllegatoIframe } from "~/components/allegato-iframe";
import { Button } from "~/components/ui/button";
import { handleDownload } from "~/hooks/filesHooks";

export const FileSection = ({ storageId }: { storageId: StorageindexId }) => {
  const { data: fileInfos, isLoading } = api.storage.getStorageFromId.useQuery({
    storageId,
  });
  const { mutateAsync: getToken } = api.storage.getStorageToken.useMutation();

  if (isLoading) return <LoadingPage />;
  if (!fileInfos) return <p>Errore nel caricamento del documento</p>;
  return (
    <>
      <AllegatoIframe
        allegato={fileInfos.id + fileInfos.ext}
        className="h-full max-h-[70vh] min-h-[60vh]"
      />

      <Button
        onClick={() =>
          handleDownload({
            file: fileInfos,
            getToken: async () => await getToken(),
          })
        }
        variant="link"
        className="underline underline-offset-1 after:content-['_↗']"
      >
        Scarica una copia del documento
      </Button>
    </>
  );
};
