import React, { useEffect, useState, type ReactNode } from "react";
import fontIcon from "../assets/icons/font.svg";
import { getScriptPredictor, type ISO_15924_CODE } from "@sortug/langlib";
import ThaiFontLoader from "./Thai";
import HanFontLoader from "./Hani";
import LatnFontLoader from "./Latn";
import JpanFontLoader from "./Jpan";

function findFontCount(lang: ISO_15924_CODE): number {
  if (lang === "Thai") return 7;
  if (lang === "Jpan") return 6;
  // TODO get more latin fonts
  if (lang === "Latn") return 1;
  if ((lang as any) === "IPA") return 6;
  if (lang.startsWith("Han")) return 23;
  return 0;
}

function FontChanger({
  text,
  script,
  children,
}: {
  text: string;
  script?: ISO_15924_CODE;
  lang?: string;
  children: ReactNode;
}) {
  const [script2, setScript] = useState<ISO_15924_CODE | null>(script || null);
  useEffect(() => {
    if (script) return;
    const predictor = getScriptPredictor();
    const res = predictor(text);
    console.log("script predicted", res);
    const rescript: ISO_15924_CODE | null = res[0];
    if (!rescript) {
      console.error("script undetected", text);
      return;
    }
    setScript(rescript);
    setFontCount(findFontCount(rescript));
  }, [text]);

  const [fontIdx, setFont] = useState(0);
  const [fontCount, setFontCount] = useState(0);
  function changeFont() {
    if (fontIdx === fontCount) setFont(0);
    else setFont((prev) => prev + 1);
  }
  if (!script2)
    return <div className="error">Couldn't detect script of {text}</div>;
  return (
    <div className={`font-changer font-${script}-${fontIdx}`}>
      <img className="font-icon cp" onClick={changeFont} src={fontIcon} />
      {script2 === "Thai" ? (
        <ThaiFontLoader>{children}</ThaiFontLoader>
      ) : script2.startsWith("Han") ? (
        <HanFontLoader>{children}</HanFontLoader>
      ) : script2 === "Jpan" ? (
        <JpanFontLoader>{children}</JpanFontLoader>
      ) : script2 === "Latn" ? (
        <LatnFontLoader>{children}</LatnFontLoader>
      ) : null}
    </div>
  );
}

export default FontChanger;
