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

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

import { type Course } from '../types';

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

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

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

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

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

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

export default useCertificate;
