import apiFetch from "@/lib/apiFetch";
import { ActionIcon, Flex, Modal } from "@mantine/core";
import { useShallowEffect } from "@mantine/hooks";
import { IconDownload, IconX } from "@tabler/icons-react";
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
import { useRef } from "react";
import useSWR from "swr";
import SKBedaBiodataDiri from "./surat/SKBedaBiodataDiri";
import SKBelumKawin from "./surat/SKBelumKawin";
import SKDomisiliOrganisasi from "./surat/SKDomisiliOrganisasi";
import SKKelahiran from "./surat/SKKelahiran";
import SKKelakuanBaik from "./surat/SKKelakuanBaik";
import SKKematian from "./surat/SKKematian";
import SKPenghasilan from "./surat/SKPenghasilan";
import SKTempatUsaha from "./surat/SKTempatUsaha";
import SKTidakMampu from "./surat/SKTidakMampu";
import SKUsaha from "./surat/SKUsaha";
import SKYatim from "./surat/SKYatimPiatu";

export default function ModalSurat({
  open,
  onClose,
  surat,
}: {
  open: boolean;
  onClose: () => void;
  surat: string;
}) {
  const A4Style = {
    width: "210mm",
    height: "297mm",
    padding: "20mm",
    background: "#fff",
    color: "#000",
    fontSize: "14px",
    fontFamily: "Times New Roman",
  };
  const hiddenRef = useRef<any>(null);
  const { data, mutate, isLoading } = useSWR("surat", () =>
    apiFetch.api.surat.detail.get({
      query: {
        id: surat,
      },
    }),
  );

  useShallowEffect(() => {
    mutate();
  }, []);

  const downloadPDF = async () => {
    const element = hiddenRef.current;
    const canvas = await html2canvas(element, {
      scale: 2,
      useCORS: true,
      allowTaint: true,
      width: element.offsetWidth,
      height: element.offsetHeight,
    });

    const imgData = canvas.toDataURL("image/jpeg", 1.0);

    const pdf = new jsPDF("p", "mm", "a4");
    const pageWidth = 210; // A4 width mm
    const pageHeight = 297; // A4 height mm

    const imgWidth = pageWidth;
    const imgHeight = (canvas.height * pageWidth) / canvas.width;

    pdf.addImage(imgData, "JPEG", 0, 0, imgWidth, imgHeight);

    pdf.save(`${data?.data?.surat?.nameCategory}.pdf`);
  };

  return (
    <>
      <Modal
        opened={open}
        onClose={() => onClose()}
        overlayProps={{ backgroundOpacity: 0.55, blur: 3 }}
        size="auto"
        withCloseButton={false}
        removeScrollProps={{ allowPinchZoom: true }}
        styles={{
          header: {
            display: "flex",
            justifyContent: "space-between",
            alignItems: "center",
            padding: "12px 16px",
          },
          title: {
            width: "100%",
          },
        }}
        title={
          <Flex justify="space-between" align="center" w="100%">
            <div style={{ fontSize: 18, fontWeight: 600 }}>Preview Surat</div>

            <Flex gap={8}>
              <ActionIcon size={32} variant="default">
                <IconDownload size={20} onClick={downloadPDF} />
              </ActionIcon>

              <ActionIcon size={32} variant="default" onClick={onClose}>
                <IconX size={20} />
              </ActionIcon>
            </Flex>
          </Flex>
        }
      >
        <div ref={hiddenRef} style={A4Style}>
          {data && data.data ? (
            data.data.surat.idCategory == "skusaha" ? (
              <SKUsaha data={data.data} />
            ) : data.data.surat.idCategory == "skkelahiran" ? (
              <SKKelahiran data={data.data} />
            ) : data.data.surat.idCategory == "skkelakuanbaik" ? (
              <SKKelakuanBaik data={data.data} />
            ) : data.data.surat.idCategory == "skpenghasilan" ? (
              <SKPenghasilan data={data.data} />
            ) : data.data.surat.idCategory == "sktidakmampu" ? (
              <SKTidakMampu data={data.data} />
            ) : data.data.surat.idCategory == "skyatimpiatu" ? (
              <SKYatim data={data.data} />
            ) : data.data.surat.idCategory == "skdomisiliorganisasi" ? (
              <SKDomisiliOrganisasi data={data.data} />
            ) : data.data.surat.idCategory == "skbedabiodata" ? (
              <SKBedaBiodataDiri data={data.data} />
            ) : data.data.surat.idCategory == "sktempatusaha" ? (
              <SKTempatUsaha data={data.data} />
            ) : data.data.surat.idCategory == "skbelumkawin" ? (
              <SKBelumKawin data={data.data} />
            ) : data.data.surat.idCategory == "skkematian" ? (
              <SKKematian data={data.data} />
            ) : (
              <></>
            )
          ) : (
            <></>
          )}
        </div>
      </Modal>
    </>
  );
}
