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

import { getCertificate } from 'src/pages/dashboard/learning/paths/services';
import { type Attachment } from 'src/types/attachments';
import { getAttachmentFromFileUrl } from 'src/utils/files';

import { pathsKeys } from '../queries';
import { type Path } from '../types';

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

  const mutation = useMutation(() => getCertificate(path.id), {
    onSuccess: response => {
      queryClient.invalidateQueries(pathsKeys.detail.path(path.id));
      if (response.data.certUrl) {
        openCertiticate(response.data.certUrl);
      }
    },
  });

  const openCertiticate = (url: string) =>
    setFile(getAttachmentFromFileUrl(url, `${path.title}.pdf`));

  const handleOpen = () =>
    path.certUrl ? openCertiticate(path.certUrl) : mutation.mutate();

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

  return {
    ...mutation,
    file,
    open: handleOpen,
    close: handleClose,
  };
};

export default useCertificate;
