import { useRef } from "react";
import { TalentButton } from "@komi-app/components";
import "./CampaignReportPage.scss";
import { useMutation } from "@tanstack/react-query";
import { toCampaignStatuses } from "utils/dca/campaigns";
import CampaignPageHeader from "../CampaignPageHeader";
import { useHistory } from "react-router-dom";
import { jsPDF } from "jspdf";
import notification from "utils/notification";
import CampaignMenu from "../CampaignMenu";
import { campaignsUrl } from "constants/dca/campaigns";
import { useCampaignQuery } from "../queries";
import CampaignReportPerformanceV2 from "./ReportPerformanceV2";
import CampaignReportStatsV2 from "./ReportStatsV2";
import CampaignReportDetailsV2 from "./ReportDetailsV2";

export interface CampaignReportPageProps {
  campaignId: string;
}

const CampaignReportPageV2 = ({ campaignId }: CampaignReportPageProps) => {
  const { data: campaign } = useCampaignQuery(campaignId);

  const router = useHistory();

  const ref = useRef<HTMLDivElement | null>(null);
  const pdfGenerationData =
    ref.current && campaign
      ? {
          ready: true as const,
          element: ref.current,
          campaignName: campaign.name,
        }
      : { ready: false as const };

  const pdfCreationMutation = useMutation(async () => {
    if (pdfGenerationData.ready) {
      await generatePDF(
        pdfGenerationData.element,
        pdfGenerationData.campaignName
      );
      notification.success({
        message: `"${pdfGenerationData.campaignName}" Report exported to PDF`,
      });
    }
  });

  return (
    <div className="campaign-report-page" ref={ref}>
      <CampaignPageHeader
        name={campaign?.name ?? "--"}
        onBackClick={() => router.push(campaignsUrl)}
        status={
          campaign
            ? toCampaignStatuses(
                campaign.status,
                campaign.schedule.startTimestamp
              )
            : null
        }
        menu={
          campaign && (
            <CampaignMenu
              campaignId={campaignId}
              campaignName={campaign.name}
              campaignStatus={toCampaignStatuses(
                campaign.status,
                campaign.schedule.startTimestamp
              )}
              omitViewReportOption
            />
          )
        }
      />

      <hr className="campaign-report-page-divider" />

      <CampaignReportPerformanceV2
        campaignId={campaignId}
        campaign={campaign}
      />

      <hr className="campaign-report-page-divider" />

      <CampaignReportDetailsV2 campaignId={campaignId} campaign={campaign} />

      <hr className="campaign-report-page-divider" />

      <CampaignReportStatsV2 campaignId={campaignId} />

      <hr className="campaign-report-page-divider" />

      <section className="controls-section">
        <TalentButton
          disabled={!pdfGenerationData.ready || pdfCreationMutation.isLoading}
          onClick={() => {
            pdfCreationMutation.mutate();
          }}
        >
          Export as PDF
        </TalentButton>
      </section>
    </div>
  );
};

export default CampaignReportPageV2;

async function generatePDF(element: HTMLElement, campaignName: string) {
  const isoDateString = new Date().toISOString();

  const doc = new jsPDF({
    orientation: "landscape",
    unit: "px",
    format: [element.clientHeight, element.clientWidth],
  });

  await new Promise<void>((resolve) => {
    doc.html(element, {
      html2canvas: {
        allowTaint: false,
        useCORS: true,
        ignoreElements: (el) =>
          el instanceof SVGElement || el instanceof HTMLButtonElement,
      },
      callback: () => {
        doc.save(`${campaignName}-${isoDateString}.pdf`);
        resolve();
      },
    });
  });
}
