import React from 'react';

import { Helmet } from 'react-helmet-async';
import Loading from '../common/lib/Loading';
import PageNotFound from '../common/lib/PageNotFound';
import { BrainAtlasType, MultiLang } from '../config';
import Functions from '../functions';
import ItemType from './item-type';
import ItemUtil, { Item } from './lib/ItemUtil';

interface Props {
  lang: MultiLang;
  type: BrainAtlasType;
  id: number;
  doi: string;
}

const XoonipsDetailItem: React.FC<Props> = (props) => {
  const { lang, type, id, doi } = props;

  const [loading, setLoading] = React.useState<boolean>(true);
  const [item, setItem] = React.useState<Item | null>(null);

  React.useEffect(() => {
    if (doi !== '') {
      ItemUtil.getByDoi(type, doi, (item) => {
        setItem(item);
        setLoading(false);
      });
    } else if (id !== 0) {
      ItemUtil.get(type, id, (item) => {
        setItem(item);
        setLoading(false);
      });
    } else {
      setLoading(true);
    }
  }, [type, id, doi]);

  if (loading) {
    return <Loading />;
  }
  if (item === null) {
    return <PageNotFound lang={lang} />;
  }

  return (
    <>
      <Helmet>
        <title>
          {Functions.mlang(item.title, lang)} -{' '}
          {Functions.mlang('[en]Database[/en][ja]データベース[/ja]', lang)} -{' '}
          {Functions.siteTitle(lang)}
        </title>
      </Helmet>
      <h3>{Functions.mlang('[en]Detail[/en][ja]詳細[/ja]', lang)}</h3>
      <br />
      <ItemType.Detail lang={lang} item={item} type={type} />
    </>
  );
};

export default XoonipsDetailItem;
