import { useState, useRef } from "react";
import { domToPng } from "modern-screenshot";
import ImageToPieces from "image-to-pieces";
import JSZip from "jszip";
import download from "downloadjs";

import {
  DEFAULT_VALUE,
  RATIONAL_BADGE_WIDTH,
} from "components/editor-badge/badge-editor.constants";
import BackgroundTransparent from "assets/images/editor/transparent_bg.svg";
import { API } from "@/utils/api";
import { useUser } from "@/utils/auth";

import { MainForm } from "./comps/header/form/main";
import { AdvancedForm } from "./comps/header/form/advanced";
import { Badge } from "./comps/badge";
import { EditorTabs } from "./comps/tabs";
import { UserCard } from "./comps/user_card";

export default function Editor() {
  const { user } = useUser();
  const [badge, setBadge] = useState({
    ...DEFAULT_VALUE,
  });

  const badgeRef = useRef<any>(null);
  const [current, setCurrent] = useState(0);

  const handleSave = (hasImage = false) => {
    domToPng(
      document.getElementById("discotools-selected-badge") as HTMLElement,
      {
        scale: 2,
      }
    ).then(async (dataUrl) => {
      if (hasImage) {
        download(dataUrl, "badge.png", "image/png");
        // API.downloadBadge();
        return;
      }

      if (!badgeRef?.current) return;
      const badgeWidth = badgeRef.current.getBoundingClientRect().width;
      const image = new ImageToPieces(
        null,
        badgeWidth / RATIONAL_BADGE_WIDTH,
        1
      );
      await image.loadImageByUrl(dataUrl);
      const tiles = image
        .getTiles()
        ?.map((tile: any) => tile.data?.replace("data:image/png;base64,", ""));
      const zip_folder = new JSZip();
      tiles.forEach((tile: any, i: number) =>
        zip_folder.file(`${i}.png`, tile, { base64: true })
      );

      zip_folder.generateAsync({ type: "blob" }).then(function (content) {
        download(content, "badges.zip");
        // API.downloadBadge();
      });
    });
  };

  const renderTabs = () => {
    switch (current) {
      case 0:
        return <MainForm badge={badge} setBadge={setBadge} />;
      case 1:
        return <AdvancedForm badge={badge} setBadge={setBadge} />;
    }
  };

  return (
    <div className="flex-col lg:flex-row flex max-w-5xl mx-auto gap-5 lg:gap-10 mt-10">
      <div className="flex-1 bg-dark-500 shadow-lg rounded-2xl">
        <EditorTabs current={current} onChange={setCurrent} />
        {renderTabs()}
      </div>
      <div className="flex items-start flex-col gap-5 lg:gap-10 lg:max-w-[375px] w-full">
        <header
          className="relative p-5 flex items-center justify-center bg-repeat h-[100px] w-full z-10 transition-all duration-200 first-step rounded-2xl"
          style={{
            backgroundImage: `url(${BackgroundTransparent.src})`,
          }}
        >
          <Badge ref={badgeRef} badge={badge} />
        </header>
        <UserCard badge={badge} onSave={handleSave} />
      </div>
    </div>
  );
}
