import React from "react";
import { Helmet } from "react-helmet-async";
import { Link, useLocation } from "react-router-dom";
import Config, { BrainAtlasType, MultiLang } from "../config";

interface Props {
  lang: MultiLang;
  type: BrainAtlasType;
}

type HeaderType = BrainAtlasType | "marmoset_3d" | "marmoset_std";

const titles = {
  degu: "Degu - 3D Brain Atlas",
  jm: "Japanese Macaque Monkey - the MRI Standard Brain",
  marmoset: "Marmoset",
  marmoset_3d: "Marmoset - 3D Brain Atlas",
  marmoset_std: "Marmoset - the MRI Standard Brain",
};
const urls = {
  degu: "/degu/modules/xoonips/listitem.php?index_id=24",
  jm: "/jm/modules/xoonips/listitem.php?index_id=9",
  marmoset: "/marmoset_html/",
  marmoset_3d: "/marmoset/modules/xoonips/listitem.php?index_id=66",
  marmoset_std: "/marmoset/modules/xoonips/listitem.php?index_id=71",
};

const getHeaderType = (type: BrainAtlasType, pathname: string, search: string): HeaderType => {
  if (type === "marmoset") {
    const params = new URLSearchParams(search);
    switch (pathname) {
      case "/marmoset/modules/xoonips/listitem.php": {
        const index_id = params.get("index_id") || "3";
        if (["66", "69"].includes(index_id)) {
          return "marmoset_3d";
        }
        if (["71", "73"].includes(index_id)) {
          return "marmoset_std";
        }
        break;
      }
      case "/marmoset/modules/xoonips/detail.php": {
        const item_id = params.get("item_id") || "";
        if (["77", "75", "79", "80"].includes(item_id)) {
          return "marmoset_3d";
        }
        if (["72"].includes(item_id)) {
          return "marmoset_std";
        }
        const id = params.get("id") || "";
        if (["Marmoset02", "Marmoset04", "Marmoset05", "Marmoset06"].includes(id)) {
          return "marmoset_3d";
        }
        if (["004"].includes(id)) {
          return "marmoset_std";
        }
        break;
      }
    }
  }
  return type;
};

const Header: React.FC<Props> = (props: Props) => {
  const { lang, type } = props;
  const location = useLocation();
  const { pathname, search } = location;
  const params = new URLSearchParams(search);
  params.set("ml_lang", lang === "en" ? "ja" : "en");
  const langUrl = location.pathname + "?" + params.toString();
  const langLabel = lang === "en" ? "To Japanese" : "To English";
  const xtype = getHeaderType(type, pathname, search);
  const title = Config.SITE_TITLE + " " + titles[xtype];
  const url = urls[xtype];
  return (
    <header className={xtype}>
      <Helmet>
        <title>{title}</title>
      </Helmet>
      <div className="selLang">
        <Link to={langUrl}>{langLabel}</Link>
      </div>
      <Link to={url} title={title}>
        <div className="title">
          <span>{title}</span>
        </div>
      </Link>
    </header>
  );
};

export default Header;
