import { useState } from 'react';
import { useMutation, useQueryClient } from 'react-query';

import { type Attachment } from 'src/types/attachments';
import { getAttachmentFromFileUrl } from 'src/utils/files';

import { sessionsKeys } from '../queries';
import { getCertificate } from '../services';
import { type SessionDetail } from '../types';

export const useCertificate = (session: SessionDetail) => {
  const queryClient = useQueryClient();
  const [file, setFile] = useState<Attachment | null>(null);

  const mutation = useMutation(
    () => getCertificate(session.learningSessionId),
    {
      onSuccess: response => {
        queryClient.invalidateQueries(
          sessionsKeys.detail(session.learningSessionId),
        );
        openCertiticate(response.data.certUrl);
      },
    },
  );

  const openCertiticate = (url?: string) => {
    if (!url) return;
    setFile(getAttachmentFromFileUrl(url, `${session.title}.pdf`));
  };

  const handleDownload = () =>
    session.certUrl ? openCertiticate(session.certUrl) : mutation.mutate();

  const handleClose = () => setFile(null);

  return {
    ...mutation,
    file,
    download: handleDownload,
    close: handleClose,
  };
};

export default useCertificate;
